branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>rahmatov/redmine_chat_telegram<file_sep>/extras/init-telegram-cli #!/bin/bash # # telegram-cli Startup script # # chkconfig: - 85 15 # processname: telegram-cli # pidfile: /opt/redmine/tmp/pids/telegram-cli.pid # # Source function library. . /etc/init.d/functions NAME=telegram-cli USER=redmine PORT=2391 LOG=/opt/redmine/log/telegram-cli-daemon.log PID=/opt/redmine/tmp/pids/telegram-cli.pid get_pid() { cat "$PID" } is_running() { [ -f "$PID" ] && ps `get_pid` > /dev/null 2>&1 } start() { if is_running; then echo "Already started" else echo -n "Starting $NAME: " echo `telegram-cli -U $USER -d -vvvRDCW --json -P $PORT -L $LOG >> $LOG 2>&1 & echo $!` > $PID touch /var/lock/subsys/$NAME echo "Started" fi } stop() { if is_running; then echo -n "Shutting down $NAME : " kill -9 $(cat $PID) for i in {1..10} do if ! is_running; then break fi echo -n "." sleep 1 done echo if is_running; then echo "Not stopped; may still be shutting down or shutdown may have failed" exit 1 else echo "Stopped" if [ -f "$PID" ]; then rm "$PID" rm -f /var/lock/subsys/$NAME fi fi else echo "Not running" fi } case "$1" in start) start ;; stop) stop ;; restart) stop if is_running; then echo "Unable to stop, will not attempt to start" exit 1 fi start ;; status) if is_running; then echo "Running" else echo "Stopped" exit 1 fi ;; *) echo "Usage: telegram-cli {start|stop|restart|status}" exit 1 ;; esac exit $? <file_sep>/lib/redmine_chat_telegram.rb require 'timeout' module RedmineChatTelegram def self.table_name_prefix 'redmine_chat_telegram_' end def self.bot_token Setting.plugin_redmine_chat_telegram['bot_token'] end def self.set_locale I18n.locale = Setting['default_language'] end def self.issue_url(issue_id) if Setting['protocol'] == 'https' URI::HTTPS.build(host: Setting['host_name'], path: "/issues/#{issue_id}").to_s else URI::HTTP.build(host: Setting['host_name'], path: "/issues/#{issue_id}").to_s end end def self.cli_base cli_path = REDMINE_CHAT_TELEGRAM_CONFIG['telegram_cli_path'] public_key_path = REDMINE_CHAT_TELEGRAM_CONFIG['telegram_cli_public_key_path'] "#{cli_path} -WCD -v --json -k #{public_key_path} -e " end def self.mode REDMINE_CHAT_TELEGRAM_CONFIG['telegram_cli_mode'].to_i end def self.run_cli_command(cmd, logger = nil) logger.debug cmd if logger cmd_as_param = cmd.gsub('"', '\\"') logger.debug %( #{cli_base} "#{cmd_as_param}" ) if logger result = ` #{cli_base} "#{cmd_as_param}" ` logger.debug result if logger json_string = result.scan(/\[?{.+}\]?/).first JSON.parse(json_string) if json_string.present? end def self.socket_cli_command(cmd, logger = nil) logger.debug cmd if logger socket = TCPSocket.open('127.0.0.1', 2391) socket.puts cmd socket.flush answer = socket.readline length = answer.match(/ANSWER (\d+)/)[1].to_i result = socket.read(length) logger.debug result if logger JSON.parse result rescue puts $ERROR_INFO ensure socket.close if socket end CHAT_HISTORY_PAGE_SIZE = 100 HISTORY_UPDATE_LOG = Logger.new(Rails.root.join('log/chat_telegram', 'telegram-group-history-update.log')) def self.create_new_messages(issue_id, chat_name, bot_ids, present_message_ids, page) cmd = "history #{chat_name} #{CHAT_HISTORY_PAGE_SIZE} #{CHAT_HISTORY_PAGE_SIZE * page}" json_messages = RedmineChatTelegram.socket_cli_command(cmd, HISTORY_UPDATE_LOG) if json_messages.present? new_json_messages = json_messages.select do |message| from = message['from'] if from.present? peer_id = from['peer_id'] || from['id'] !present_message_ids.include?(message['id']) && !bot_ids.include?(peer_id) end end new_json_messages.each do |message| message_id = message['id'] sent_at = Time.at message['date'] from = message['from'] from_id = from['id'] from_first_name = from['first_name'] from_last_name = from['last_name'] from_username = from['username'] message_text = message['text'] TelegramMessage.where(telegram_id: message_id) .first_or_create issue_id: issue_id, sent_at: sent_at, from_id: from_id, from_first_name: from_first_name, from_last_name: from_last_name, from_username: from_username, message: message_text end json_messages.size == CHAT_HISTORY_PAGE_SIZE else false end end end <file_sep>/Gemfile gem 'telegram-bot-ruby' gem 'pidfile', git: 'https://github.com/arturtr/pidfile.git' gem 'sidekiq-cron' gem 'sidekiq-rate-limiter', require: 'sidekiq-rate-limiter/server' gem 'byebug' group :test do gem 'timecop' gem 'spy' gem 'database_cleaner' gem 'minitest-around' gem 'minitest-reporters' end <file_sep>/README.ru.md # redmine_chat_telegram [English version](https://github.com/centosadmin/redmine_chat_telegram/blob/master/README.md) Плагин разработан в компании [Centos-admin.ru](https://centos-admin.ru) [Описание плагина на habrahabr.ru](https://habrahabr.ru/company/centosadmin/blog/281044/) Плагин для Redmine для создания групповых чатов в Telegram. Плагин `redmine_chat_telegram` используется для создания группового чата, связанного с тикетом, и записи его логов в архиве Redmine. Связанные групповые чаты могут легко быть созданы с помощью ссылки "Создать чат Telegram", которая появится на странице тикета. Вы сможете скопировать ссылку и передать её любому, кого Вы захотите подключить к этому чату. ![Create telegram chat](https://github.com/centosadmin/redmine_chat_telegram/raw/master/assets/images/create-link.png) ![Chat links](https://github.com/centosadmin/redmine_chat_telegram/raw/master/assets/images/chat-links.png) Пожалуйста помогите нам сделать этот плагин лучше, сообщая во вкладке [Issues](https://github.com/centosadmin/redmine_chat_telegram/issues) обо всех проблемах, с которыми Вы столкнётесь при его использовании. Мы готовы ответить на Все ваши вопросы, касающиеся этого плагина. ## Установка ### Требования * **Ruby 2.3+** * [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common) * [Telegram CLI](https://github.com/vysheng/tg) **рекомендуемая версия 1.3.3**<br> с версией 1.4.1 не работает синхронизация архивов сообщений * У Вас должен быть аккаунт пользователя Telegram * У Вас должен быть аккаунт для создания ботов в Telegram * Плагин [redmine_sidekiq](https://github.com/ogom/redmine_sidekiq) должен быть установлен * Sidekiq должен обрабатывать очереди `default` и `telegram`. [Пример конфига](https://github.com/centosadmin/redmine_chat_telegram/blob/master/extras/sidekiq.yml) - разместите его в папке `redmine/config` * Не забудьте запустить миграции `bundle exec rake redmine:plugins:migrate RAILS_ENV=production` ### Конфигурация в Telegram CLI **!!! ВНИМАНИЕ !!!** Начиная с версии 1.4.5, в плагине используется обращение к Telegram CLI как к службе. В связи с этим `telegram-cli` должен быть запущен как служба. В каталоге `extras` вы можете найти: * пример скрипта `init.d` * пример конфига для `monit` ### Первый запуск Запустите `telegram-cli` на Вашем сервере Redmine и залогиньтесь через него в Telegram. После этого Вы сможете создавать групповые чаты. ### Создание бота в Telegram Необходимо создать нового бота и получить его токен. Для этого в Telegram используется [@BotFather](https://telegram.me/botfather). Наберите `start` для получения полного списка предоставляемых им команд. Наберите `/newbot` для регистрации нового бота. @BotFather спросит у Вас имя нового бота. Имя бота должно оканчиваться на "bot". При успешной регистрации @BotFather даст вам токен Вашего нового бота, а также ссылку для того, чтобы Вы могли быстро добавить его в Ваш список контактов. Вам придётся придумать новое имя если регистрация не удастся. Установите Privacy mode в disabled с помощью команды `/setprivacy`. Это позволит боту слушать групповой чат и добавлять его логи в архив чатов Redmine. Введите токен бота на странице Plugin Settings для того чтобы добавить бота в ваш чат. Чтобы добавить подсказки команд для бота, используйте команду `/setcommands`. Нужно написать боту список команд с описанием. Этот список вы можете получить из команды `/help` ### Добавление бота в список контактов Наберите `/start` для вашего бота под своим аккаунтом. Это позволит пользователю добавить бота в групповой чат. ### Запуск бота Запустите `telegram-cli` используя скрип `init-telegram-cli`. Пример можно посмотреть в папке `extras`. Для запуска бота выполните следующее rake задание: ```shell RAILS_ENV=production bundle exec rake chat_telegram:bot PID_DIR='/pid/dir' ``` Или запустите `init-telegram-bot` скрипт из `extras`. ### Синхронизация архива Плагие не записывает сообщения чата в архив когда он остановлен. Во избежание потери сообщений плагин выполяет синхноризацию сообщений из чата в архив при следующем запуске с задержкой в 5 минут. ## Использование Откройте тикет. Справа на странице Вы увидите ссылку `создать чат Telegram`. Щёлкните по ней и Вы создадите групповой чат в Telegram, который будет связан с этим тикетом. Ссылка изменится на `Войти в чат Telegram`. Щёлкните на ней чтобы присоединиться к чату, открыв его в своём клиенте Telegram. Вы сможете скопировать и передать ссылку любому кому захотите для того, чтобы он смог присоединиться к этому групповому чату. ### Доступные команды в чате с ботом - `/connect <EMAIL>` - связать аккаунт Telegram и Redmine - `/new` - команда для создания новой задачи - `/cancel` - отмена текущей команды ### Доступные команды в чате задачи - `/task`, `/link`, `/url` - получение ссылки задачи - `/log` - сохраняет сообщение в задачу #### Подсказки для команд бота Чтобы добавить подсказки команд для бота, используйте команду `/setcommands` в беседе с [@BotFather](https://telegram.me/botfather). Нужно написать боту список команд с описанием: ``` start - начало работы с ботом. connect - связать аккаунты Telegram и Redmine. new - создать новую задачу. hot - Назначенные вам задачи, обновленные за последние сутки. me - Назначенные вам задачи. deadline - Назначенные вам задачи с просроченным дедлайном. spent - Количество проставленного времени за текущие сутки. yspent - Количество проставленного времени за вчерашние сутки. last - Последние 5 задач с последними комментариями. help - Помощь по командам. chat - Управления чатами задач. help - Справка по командам. task - Получить ссылку на задачу. link - Получить ссылку на задачу. url - Получить ссылку на задачу. log - Сохранить сообщение в задачу (укажите команду в любом месте сообщения). issue - Редактирование задач. ``` ### Автоматическое закрытие чата при закрытии задачи После закрытия задачи, чат закроется через 2 недели автоматически. За 1 неделю до закрытия каждые 12 часов в чат будет приходить сообщение: "Задача по этому чату закрыта. Чат будет автоматически расформирован через XX дней." По истечении времени все участники чата будут удалены из него. ## Возможные проблемы ### При создании чата ссылка на чат содержит FAILED Попробуйте сменить `telegram_cli_mode` в `telegram.yml` на `1`. ### Couldn't open public key file: tg-server.pub Это баг в Telegram CLI. Мы направили [pull request](https://github.com/Rondoozle/tg/pull/4) с решением. Временное решение: расположите файл `tg-server.pub` в корневом каталоге Redmine. <file_sep>/app/workers/telegram_group_close_worker.rb class TelegramGroupCloseWorker include Sidekiq::Worker def perform(telegram_id, user_id = nil) RedmineChatTelegram.set_locale find_user(user_id) return if telegram_id.nil? store_chat_name(telegram_id) reset_chat_link # Old link will not work after it. send_chat_notification(telegram_id) remove_users_from_chat end private attr_reader :user, :chat_name def find_user(user_id) @user = User.find_by(id: user_id) || User.anonymous logger.debug user.inspect end def store_chat_name(telegram_id) @chat_name = "chat##{telegram_id.abs}" logger.debug chat_name end def reset_chat_link cmd = "export_chat_link #{chat_name}" RedmineChatTelegram.socket_cli_command(cmd, logger) end def send_chat_notification(telegram_id) TelegramMessageSenderWorker.perform_async(telegram_id, close_message_text) end def close_message_text user.anonymous? ? I18n.t('redmine_chat_telegram.messages.closed_automaticaly') : I18n.t('redmine_chat_telegram.messages.closed_from_issue') end def remove_users_from_chat cmd = "chat_info #{chat_name}" json = RedmineChatTelegram.socket_cli_command(cmd, logger) admin = json['admin'] members = json['members'] return unless members.present? members_without_admin = members.select { |member| member['id'] != admin['id'] } members_without_admin.each do |member| telegram_user_id = "user##{member['id']}" cmd = "chat_del_user #{chat_name} #{telegram_user_id}" RedmineChatTelegram.socket_cli_command(cmd, logger) end telegram_user_id = "user##{admin['id']}" cmd = "chat_del_user #{chat_name} #{telegram_user_id}" RedmineChatTelegram.socket_cli_command(cmd, logger) end def logger @logger ||= Logger.new(Rails.root.join('log/chat_telegram', 'telegram-group-close.log')) end end <file_sep>/lib/redmine_chat_telegram/group_chat_creator.rb module RedmineChatTelegram class GroupChatCreator attr_reader :issue, :user def initialize(issue, user) @issue = issue @user = user end def run subject = "#{issue.project.name} #{issue.id}" bot_name = Setting.plugin_redmine_chat_telegram['bot_name'] cmd = "create_group_chat \"#{subject}\" #{bot_name}" json = RedmineChatTelegram.socket_cli_command(cmd, TELEGRAM_CLI_LOG) subject_for_cli = if RedmineChatTelegram.mode.zero? subject.tr(' ', '_').tr('#', '@') else subject.tr(' ', '_').tr('#', '_') end sleep 1 # TODO: 1. replace it by waiting message from bot and getting chat_id from DB # TODO: 2. remove RedmineChatTelegram.mode (telegram_cli_mode) cmd = "chat_info #{subject_for_cli}" json = RedmineChatTelegram.socket_cli_command(cmd, TELEGRAM_CLI_LOG) telegram_id = json['peer_id'] || json['id'] # get chat_id from DB # # cmd = "export_chat_link chat##{chat_id.abs}" cmd = "export_chat_link #{subject_for_cli}" json = RedmineChatTelegram.socket_cli_command(cmd, TELEGRAM_CLI_LOG) telegram_chat_url = json['result'] if issue.telegram_group.present? issue.telegram_group.update telegram_id: telegram_id, shared_url: telegram_chat_url else issue.create_telegram_group telegram_id: telegram_id, shared_url: telegram_chat_url end journal_text = I18n.t('redmine_chat_telegram.journal.chat_was_created', telegram_chat_url: telegram_chat_url) begin issue.init_journal(user, journal_text) issue.save rescue ActiveRecord::StaleObjectError issue.reload retry end end end end <file_sep>/README.md [![Code Climate](https://codeclimate.com/github/centosadmin/redmine_chat_telegram/badges/gpa.svg)](https://codeclimate.com/github/centosadmin/redmine_chat_telegram) [![Build Status](https://travis-ci.org/centosadmin/redmine_chat_telegram.svg?branch=master)](https://travis-ci.org/centosadmin/redmine_chat_telegram) # redmine_chat_telegram [Русская версия](https://github.com/centosadmin/redmine_chat_telegram/blob/master/README.ru.md) Plugin is developed by [Centos-admin.ru](https://centos-admin.ru) Redmine plugin is used to create Telegram group chats. The `redmine_chat_telegram` can be used to create a group chat associated with a ticket and record its logs to the Redmine archive. Associated group chats can be easily created via the `Create Telegram chat` link on the ticket page. You can copy the link and pass it to anyone you want to join this Telegram chat. ![Create telegram chat](https://github.com/centosadmin/redmine_chat_telegram/raw/master/assets/images/create-link.png) ![Chat links](https://github.com/centosadmin/redmine_chat_telegram/raw/master/assets/images/chat-links.png) Please help us make this plugin better telling us of any [issues](https://github.com/centosadmin/redmine_chat_telegram/issues) you'll face using it. We are ready to answer all your questions regarding this plugin. ## Installation ### Requirements * **Ruby 2.3+** * [redmine_telegram_common](https://github.com/centosadmin/redmine_telegram_common) * [Telegram CLI](https://github.com/vysheng/tg) **version 1.3.3 recommended**<br> version 1.4.1 has problems with archive sync. * You should have Telegram user account * You should have Telegram bot account * Install the [redmine_sidekiq](https://github.com/ogom/redmine_sidekiq) plugin * You need to configure Sidekiq queues `default` and `telegram`. [Config example](https://github.com/centosadmin/redmine_chat_telegram/blob/master/extras/sidekiq.yml) - place it to `redmine/config` directory * Don't forget to run migrations `bundle exec rake redmine:plugins:migrate RAILS_ENV=production` ### Telegram CLI configuration **!!! ATTENTION !!!** Since 1.4.5 version plugin needs Telegram CLI as system daemon. You need to run `telegram-cli` as daemon. In `extras` folder you can find: * `init.d` script example * `monit` config example ### First time run Start `telegram-cli` on your Redmine server and login to Telegram with it. You'll be able to create group chats after that. ### Create Telegram Bot It is necessary to register a bot and get its token. There is a [@BotFather](https://telegram.me/botfather) bot used in Telegram for this purpose. Type `/start` to get a complete list of available commands. Type `/newbot` command to register a new bot. [@BotFather](https://telegram.me/botfather) will ask you to name the new bot. The bot's name must end with the "bot" word. On success @BotFather will give you a token for your new bot and a link so you could quickly add the bot to the contact list. You'll have to come up with a new name if registration fails. Set the Privacy mode to disabled with `/setprivacy`. This will let the bot listen to all group chats and write its logs to Redmine chat archive. Enter the bot's token on the Plugin Settings page to add the bot to your chat. To add hints for commands for the bot, use command `/setcommands`. You need to send list of commands with descriptions. You can get this list from command `/help`. ### Add bot to user contacts Type `/start` command to your bot from your user account. This allows the user to add a Bot to group chats. ### Bot launch Run `telegram-cli` using `init-telegram-cli` script. See example in folder `extras`. Execute the following rake task to launch the bot: ```shell RAILS_ENV=production bundle exec rake chat_telegram:bot PID_DIR='/pid/dir' ``` Or `init-telegram-bot` script from `extras`. ### Archive synchronization Plugin can't log chat messages into the archive when stopped. To avoid loss of messages plugin performs chat - archive synchronization on the next run with 5 minute delay from the start. ## Usage Open the ticket. You'll see the new link `Create Telegram chat` on the right side of the ticket. Click on it and the Telegram group chat associated with this ticket will be created. The link will change to `Enter Telegram chat`. Click on it to join the chat in your Telegram client. You'll be able to copy and pass the link to anyone you want to invite to the Group Chat. ### Available commands in bot chat - `/connect <EMAIL>` - connect Telegram account to Redmine account - `/new` - create new issue - `/cancel` - cancel current command ### Available commands in issue chat - `/task`, `/link`, `/url` - get link to the issue - `/log` - save message to the issue #### Hints for bot commands Use command `/setcommands` with [@BotFather](https://telegram.me/botfather). Send this list for setup hints: ``` start - Start work with bot. connect - Connect account to Redmine. new - Create new issue. hot - Assigned to you issues updated today. me - Assigned to you issues. deadline - Assigned to you issues with expired deadline. spent - Number of hours set today. yspent - Number of hours set yesterday. last - Last 5 issues with comments. help - Help. chat - Manage issues chats. task - Get link to the issue. link - Get link to the issue. url - Get link to the issue. log - Save message to the issue. issue - Change issues. ``` ## Troubleshooting ### FAILED in the chat link Try to change `telegram_cli_mode` in `telegram.yml` to `1`. ### Couldn't open public key file: tg-server.pub This is CLI bug. We have [pull request](https://github.com/Rondoozle/tg/pull/4) to fix it. Temporary solution: place `tg-server.pub` into root of Redmine. <file_sep>/lib/tasks/chat_telegram.rake def chat_telegram_bot_init Process.daemon(true, true) if Rails.env.production? tries = 0 begin tries += 1 if ENV['PID_DIR'] pid_dir = ENV['PID_DIR'] PidFile.new(piddir: pid_dir, pidfile: 'telegram-chat-bot.pid') else PidFile.new(pidfile: 'telegram-chat-bot.pid') end rescue PidFile::DuplicateProcessError => e LOG.error "#{e.class}: #{e.message}" pid = e.message.match(/Process \(.+ - (\d+)\) is already running./)[1].to_i LOG.info "Kill process with pid: #{pid}" Process.kill('HUP', pid) if tries < 4 LOG.info 'Waiting for 5 seconds...' sleep 5 LOG.info 'Retry...' retry end end Signal.trap('TERM') do at_exit { LOG.error 'Aborted with TERM signal' } abort end LOG.info 'Start daemon...' token = Setting.plugin_redmine_chat_telegram['bot_token'] unless token.present? LOG.error 'Telegram Bot Token not found. Please set it in the plugin config web-interface.' exit end LOG.info 'Get Robot info' cmd = 'get_self' begin json = RedmineChatTelegram.socket_cli_command(cmd, LOG) LOG.debug json robot_id = json['peer_id'] || json['id'] rescue NoMethodError => e LOG.error "TELEGRAM get_self #{e.class}: #{e.message} \n#{e.backtrace.join("\n")}" LOG.info 'May be problem with Telegram service. I will retry after 15 seconds' sleep 15 retry end LOG.info 'Telegram Bot: Connecting to telegram...' require 'telegram/bot' bot = Telegram::Bot::Client.new(token) bot_info = bot.api.get_me["result"] bot_name = bot_info["username"] until bot_name.present? LOG.error 'Telegram Bot Token is invalid or Telegram API is in downtime. I will try again after minute' sleep 60 LOG.info 'Telegram Bot: Connecting to telegram...' bot = Telegram::Bot::Client.new(token) bot_info = bot.api.get_me["result"] bot_name = bot_info["username"] end plugin_settings = Setting.find_by(name: 'plugin_redmine_chat_telegram') plugin_settings_hash = plugin_settings.value plugin_settings_hash['bot_name'] = "user##{bot_info["id"]}" plugin_settings_hash['bot_id'] = bot_info["id"] plugin_settings_hash['robot_id'] = robot_id plugin_settings.value = plugin_settings_hash plugin_settings.save LOG.info "#{bot_name}: connected" LOG.info 'Scheduling history update rake task...' Thread.new do sleep 5 * 60 Rake::Task['chat_telegram:history_update'].invoke end LOG.info 'Task will start after 5 minutes' LOG.info "#{bot_name}: waiting for new messages in group chats..." bot end namespace :chat_telegram do task history_update: :environment do begin RedmineChatTelegram.set_locale RedmineChatTelegram::TelegramGroup.find_each do |telegram_group| issue = telegram_group.issue unless issue.closed? present_message_ids = issue.telegram_messages.pluck(:telegram_id) bot_ids = [Setting.plugin_redmine_chat_telegram['bot_id'].to_i, Setting.plugin_redmine_chat_telegram['robot_id'].to_i] telegram_group = issue.telegram_group telegram_id = telegram_group.telegram_id.abs RedmineChatTelegram::HISTORY_UPDATE_LOG.debug "chat##{telegram_id}" chat_name = "chat##{telegram_id.abs}" page = 0 has_more_messages = RedmineChatTelegram.create_new_messages(issue.id, chat_name, bot_ids, present_message_ids, page) while has_more_messages page += 1 has_more_messages = RedmineChatTelegram.create_new_messages(issue.id, chat_name, bot_ids, present_message_ids, page) end end end rescue ActiveRecord::RecordNotFound => e # ignore end end # bundle exec rake chat_telegram:bot PID_DIR='/tmp' desc "Runs telegram bot process (options: PID_DIR='/pid/dir')" task bot: :environment do LOG = Rails.env.production? ? Logger.new(Rails.root.join('log/chat_telegram', 'bot.log')) : Logger.new(STDOUT) RedmineChatTelegram.set_locale bot = chat_telegram_bot_init begin bot.listen do |command| next unless command.is_a?(Telegram::Bot::Types::Message) RedmineChatTelegram::Bot.new(command).call end rescue HTTPClient::ConnectTimeoutError, HTTPClient::KeepAliveDisconnected, Faraday::ConnectionFailed => e LOG.error "GLOBAL ERROR WITH RESTART #{e.class}: #{e.message}\n#{e.backtrace.join("\n")}" LOG.info 'Restarting...' retry rescue Telegram::Bot::Exceptions::ResponseError => e if e.error_code.to_s == '502' LOG.info 'Telegram raised 502 error. Pretty normal, ignore that' LOG.info 'Restarting...' retry end ExceptionNotifier.notify_exception(e) if defined?(ExceptionNotifier) LOG.error "GLOBAL TELEGRAM BOT #{e.class}: #{e.message}\n#{e.backtrace.join("\n")}" rescue => e ExceptionNotifier.notify_exception(e) if defined?(ExceptionNotifier) LOG.error "GLOBAL #{e.class}: #{e.message}\n#{e.backtrace.join("\n")}" end end end
129cab9de09fc637332e4d70a58eafaac2b7acd0
[ "Markdown", "Ruby", "Shell" ]
8
Shell
rahmatov/redmine_chat_telegram
6224e4edea7dbe1ab25e4945fa558221be751d91
ee8758ac319113b0a4c829f606e01e58cc5e3864
refs/heads/master
<repo_name>Sarcasticmani/get-weather<file_sep>/src/App.js import React from "react"; import Appcontainer from "./Appcontainer.js" import "./index.css" class App extends React.Component { constructor(){ super() { this.state = { city_name : "london", temp : [], city : [], icon : [], desc : [], humidity : [], pressure : [], wind : [], visibility : [] } } this.city=this.city.bind(this) this.submit=this.submit.bind(this) this.componentWillMount=this.componentWillMount.bind(this) } city(event){ const {value} = event.target; this.setState({ city_name : value } ) } submit(){ this.componentWillMount(); } componentWillMount(){ const city = this.state.city_name const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=0861a5029ae242c98d1f8edcbf54215c` fetch(url) .then(response => response.json()) .then(response => ( this.setState( { temp : response.main.temp, city : response.name, icon : response.weather[0].icon, desc : response.weather[0].description, humidity : response.main.humidity, pressure : response.main.pressure, wind : response.wind.speed, visibility : response.visibility } ) )) } render(){ return( <div> <div className="container form"> <input className="input-box" name="t1" type="text" onChange={this.city}></input> <button className="submit-button" onClick={this.submit}><p className="p-submit">SUBMIT</p></button> </div> <Appcontainer temp = {this.state.temp} city = {this.state.city} icon = {this.state.icon} desc = {this.state.desc} humidity = {this.state.humidity} pressure = {this.state.pressure} wind = {this.state.wind} visibility = {this.state.visibility} /> </div> ) } } export default App<file_sep>/src/Footer.js import React from "react" import "./index.css" function Footer(){ return( <footer> <div className="container"> <center> <p className="p-footer">Made with ❤️ by <a href="https://github.com/surajsrv11"><NAME></a></p> <p className="p-footer">Source <a href="https://openweathermap.org/">OpenWeather</a></p> </center> </div> </footer> ) } export default Footer <file_sep>/src/Appcontainer.js import React from "react" import "./index.css" function Appcontainer(props){ return( <main className="container"> <div className="row"> <div className="container-medium main"> <img alt={"Weather Condition and City"} src={`https://s3-us-west-2.amazonaws.com/s.cdpn.io/162656/${props.icon}.svg`}></img> <div> <h1 align="right">{Math.round(props.temp-273.15)}<sup>°</sup>C</h1> <h2 align="right">{props.city} </h2> <p align="right">{props.desc}</p> </div> </div> <div className="container-small"> <center> <img alt={"Humidity"} src="https://image.flaticon.com/icons/png/512/219/219816.png"></img> <p>Humidity</p> <h1>{props.humidity}%</h1> </center> </div> </div> <div className="row"> <div className="container-small"> <center> <img alt={"Air Pressure"} src="https://img.icons8.com/ios/452/pressure.png"></img> <p>Pressure</p> <h1>{props.pressure} pascal</h1> </center> </div> <div className="container-small"> <center> <img alt={"Wind Speed"} src="https://img.icons8.com/ios/452/wind.png"></img> <p>Wind Speed</p> <h1>{props.wind} km/h</h1> </center> </div> <div className="container-small"> <center> <img alt={"Visibility Range"} src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_visibility_48px-512.png"></img> <p>Visibility</p> <h1>{props.visibility} meters</h1> </center> </div> </div> </main> ) } export default Appcontainer
785abdd426cbbfdb1873011e7ee24779697b6751
[ "JavaScript" ]
3
JavaScript
Sarcasticmani/get-weather
23c7047a6b3e3b32a38672077de30315002cf5c0
88f095b46393ba32e148ebee92130b2309e468ca
refs/heads/main
<repo_name>upcheezy/highChartsTesting_server<file_sep>/src/config.js module.exports = { PORT: process.env.PORT || 8000, NODE_ENV: process.env.NODE_ENV || 'development', DATABASE_USER: process.env.DATABASE_USER, DATABASE_PASS: process.env.DATABASE_PASS, DATABASE: process.env.DATABASE }<file_sep>/src/router.js const express = require('express'); const chartService = require('./service'); const fs = require('fs'); const highchartRouter = express.Router(); const bodyParser = express.json(); highchartRouter .route('/memberdamage') .get((req, res, next) => { const {year} = req.query; console.log(year) chartService.memberDamageLine(req.app.get('db'), year) .then(info => { res.json(info) }) }) highchartRouter .route('/excavatordamage') .get((req, res, next) => { chartService.excavatorDamage(req.app.get('db')) .then(info => { res.json(info) }) }) module.exports = highchartRouter;<file_sep>/README.md # Highcharts API Testing This is the backend for my first project with highcharts
4b9127f41ecd95f848d2266b67925b8cb9714d39
[ "JavaScript", "Markdown" ]
3
JavaScript
upcheezy/highChartsTesting_server
ce41f0e4e82d7dd22160b44b1c732fd8d357b9cf
4dbe1fd581e6a76d74ecb450c8ca21acc5124a57
refs/heads/master
<repo_name>arvinesmaeily/SentimentAnalysis<file_sep>/Sentiment_Analysis.py # pandas is used for reading and writing csv files import pandas # CountVectorizer is used for converting a collection of text documents to a matrix of token counts from sklearn.feature_extraction.text import CountVectorizer # MultinomialNB is a Naive Bayes classifier used for multinomial models from sklearn.naive_bayes import MultinomialNB # Imported methods are used for statistics about performance of ML from sklearn.metrics import accuracy_score, classification_report, confusion_matrix print("Step 3 of 3") # import train and test dataframes train_dataframe = pandas.read_csv("Train_DataFrame.csv", encoding='latin-1') test_dataframe = pandas.read_csv("Test_DataFrame.csv", encoding='latin-1') # separation of dataset items by labels print("Separating train and test datasets...") x_train = train_dataframe["Comment"].tolist() x_test = test_dataframe["Comment"].tolist() y_train = train_dataframe["State"].tolist() y_test = test_dataframe["State"].tolist() # vectoring comment string to a matrix of token counts print("Vectoring comments...") cvectorizer = CountVectorizer() x_train_vector = cvectorizer.fit_transform(x_train) x_test_vector = cvectorizer.transform(x_test) # classifying multinomial models using Naive Bayes classifier print("Classifying multinomial models using Naive Bayes classifier...") MNB = MultinomialNB() MNB.fit(x_train_vector, y_train) # prediction for test dataset print("Predicting results...") predict = MNB.predict(x_test_vector) # printing performance statistics print("Calculating statistics...") Accuracy = accuracy_score(predict, y_test) Classification_Report = classification_report(predict, y_test) Confusion_Matrix = confusion_matrix(predict, y_test) print("Accuracy: ", Accuracy) print("Classification Report: \n", Classification_Report) print("Confusion Matrix: \n", Confusion_Matrix) <file_sep>/DataSet_Cleaner.py # csv is used for reading and writing csv files and their rows import csv # Imported method is a natural language processor for English language from spacy.lang.en import English # Imported Set is a set of stop words which decrease performance of Sentiment Analysis from spacy.lang.en.stop_words import STOP_WORDS print("Step 1 of 3") # Initialize an instance for English Natural Language Processor nlp = English() # Initialize a List of redundant symbols filter_symbols = ['.', '..', '...', ',', '!', '?', '"', '\'', '@', '#', '$', '%', '^', '*', '(', ')', '-', '_', '=', '+', '/', '\\', ';', ':', '[', ']', '{', '}', '|', ' '] # Open given raw file in read-only mode raw_input = open("Raw_DataFile.csv", 'r') # Create and open a datafile for output writer of cleaned up dataset clean_output = open("Clean_Datafile.csv", 'w', newline="") print("Importing data in \"Raw_DataFile.csv\"...") # Read raw datafile as csv and load it to raw_dataset object raw_dataset = csv.reader(raw_input) # Initialize a csv writer for clean dataset which gives the ability of # writing desired rows into clean datafile clean_dataset = csv.writer(clean_output) print("Processing comments for stop words and characters...") print("This process may take a while. Please wait...") # Iteration through rows of raw dataset in order to filter redundant columns of data, # clean up comment column, recombine new columns and write generated row into clean dataset for row in raw_dataset: # first column of data is assigned to state column state = str(row[0]) # second column of data is assigned to comment object # which is first tokenized by imported NLP comment = nlp(str(row[5])) # Initializing a list of tokens which contains tokens from comment column token_list = [] for token in comment: token_list.append(token.text) # Initialize an empty filtered comment list filtered_comment = [] # Iteration through tokens in token list, in order to assign the selected token # to lexeme if token is in vocab list in NLP, checking if lexeme is not a stop word or reduntant symbol # and appending it to the list of filtered comments for selected_token in token_list: lexeme = nlp.vocab[selected_token] if lexeme.is_stop == False and lexeme not in filter_symbols: filtered_comment.append(selected_token) clean_dataset.writerow([state, filtered_comment]) print("\"Clean_Datafile\" created successfully!") <file_sep>/Execute.py import DataSet_Cleaner import DataSet_Splitter import Sentiment_Analysis exec("DataSet_Cleaner.py") exec("DataSet_Splitter.py") exec("Sentiment_Analysis.py") <file_sep>/DataSet_Splitter.py # csv is used for reading and writing csv files and their rows import csv # This method splits positive dataset rows from negative dataset rows # and puts each in a separate datafile respectively def pos_neg_splitter(): # Open cleaned up datafile in read-only mode clean_input = open('Clean_Datafile.csv', 'r') # Read cleaned up datafile as csv and load it to loaded_clean_dataset object loaded_clean_dataset = csv.reader(clean_input) # Create and open a datafile for output writers of each positive and negative dataset positive_output = open('Positive_DataSet.csv', 'w', newline="") negative_output = open('Negative_DataSet.csv', 'w', newline="") # Initialize a csv writer for each datafile which gives the ability of # writing desired rows into datafiles positive_output_writer = csv.writer(positive_output) negative_output_writer = csv.writer(negative_output) print("Splitting dataset to negative and positive datasets...") # Iterating through loaded_clean_dataset and separating rows by their first column value # then adding them to their relative csv.writer to be written on relative datafile for selected_row in loaded_clean_dataset: if str(selected_row[0]) != "0": positive_output_writer.writerow(selected_row) else: negative_output_writer.writerow(selected_row) # This method splits positive and negative datasets into given ranges # so train and test data sets will be generated by combining these split ranges def train_test_splitter(): # Open each positive and negative dataset in read-only mode positive_input = open('Positive_DataSet.csv', 'r') negative_input = open('Negative_DataSet.csv', 'r') # Create and Open train and test dataframes for train and test dataset writers train_output = open('Train_DataFrame.csv', 'w', newline="") test_output = open('Test_DataFrame.csv', 'w', newline="") # Read positive and negative datafiles as csv and load them to their relative datasets positive_dataset = csv.reader(positive_input) negative_dataset = csv.reader(negative_input) # Initialize a csv writer for each train and test datafile which gives the ability of # writing desired rows into datafiles dataset_train_writer = csv.writer(train_output) dataset_test_writer = csv.writer(test_output) # Add label rows for each file which is required by pandas dataset_train_writer.writerow(["State", "Comment"]) dataset_test_writer.writerow(["State", "Comment"]) print("Splitting positive and negative datasets to train and test datasets...") # Iterating through positive_dataset and separating rows by the given range (hard coded range) # then adding them to their relative csv.writer to be written on relative train or test datafile index = 0 for row in positive_dataset: if 0 <= index < 640000: dataset_train_writer.writerow(["positive", row[1]]) index += 1 elif 640000 <= index < 800000: dataset_test_writer.writerow(["positive", row[1]]) index += 1 else: index += 1 # Iterating through negative_dataset and separating rows by the given range (hard coded range) # then adding them to their relative csv.writer to be written on relative train or test datafile index = 0 for row in negative_dataset: if 0 <= index < 640000: dataset_train_writer.writerow(["negative", row[1]]) index += 1 elif 640000 <= index < 800000: dataset_test_writer.writerow(["negative", row[1]]) index += 1 else: index += 1 # Entry point of python file execution print("Step 2 of 3") print("Beginning split process...") pos_neg_splitter() train_test_splitter() print("Split process completed successfully!")
613d9f9926da25209ba23362519873a07d9aea99
[ "Python" ]
4
Python
arvinesmaeily/SentimentAnalysis
f8ace651b287274ac5412ef03f23ef005d6cd51f
f4d9c74737f661c5ce470c1fb2ca242e6e468466
refs/heads/main
<repo_name>lethanhdat12/quanlycf-reactjs<file_sep>/src/Component/Admin/MainAdmin/Banhang/BanhangItem.js import React, { Component } from 'react' import TableItems from './TableItems' export default class BanhangItem extends Component { render() { const {listItem} = this.props; return ( <div className="row"> { listItem.map((value,index) => { return <TableItems numberTable={value + 1} key={index}></TableItems>; }) } </div> ) } } <file_sep>/src/Component/Admin/Admin.js import React, { Component } from 'react' import {BrowserRouter as Router,Switch,Route,Link} from "react-router-dom"; import DirectRouter from '../../DirectRouter'; import HeaderAdmin from './HeaderAdmin/HeaderAdmin' import SlideBar from './SlideBar/SlideBar' export default class Admin extends Component { render() { return ( <Router> <div id="wrapper"> <SlideBar></SlideBar> <div id="content-wrapper" className="d-flex flex-column"> <div id="content"> <HeaderAdmin></HeaderAdmin> <div className="container-fluid"> <DirectRouter></DirectRouter> </div> </div> </div> </div> </Router> ) } } <file_sep>/src/Component/Admin/MainAdmin/Banhang/ShowProduct/ProductItemInBill.js import React, { Component } from 'react' export default class ProductItemInBill extends Component { render() { return ( <tr> <th scope="row"> {this.props.sttProductItemInBill} </th> <td> {this.props.nameProductItemInBill} </td> <td>{this.props.soluongProductItemInBill} </td> <td>{this.props.giaProductItemInBill}</td> </tr> ) } } <file_sep>/src/Reducers/RootReducers.js import {combineReducers} from 'redux'; import BillReducer from './BillReducer'; const RootReducers = combineReducers({ Bill : BillReducer, }); export default RootReducers; <file_sep>/src/Component/Admin/MainAdmin/Banhang/Banhang.js import React, { Component } from 'react' import { useSelector } from 'react-redux'; import BanhangItem from './BanhangItem'; function Banhang() { const billReducers = useSelector(state => state.Bill.productList); return ( <BanhangItem listItem = {billReducers}></BanhangItem> ) } export default Banhang; <file_sep>/src/Base.js import Rebase from "re-base"; import firebase from "firebase"; const firebaseApp = firebase.initializeApp({ apiKey: process.env.REACT_APP_API_KEY, authDomain: process.env.REACT_APP_AUTHDOMAIN, databaseURL: process.env.REACT_APP_DATABASE_URL }); const base = Rebase.createClass(firebase.database()); export { firebaseApp }; export default base; <file_sep>/src/Login.js import React, { Component } from 'react' import firebase from 'firebase'; import { firebaseApp } from './Base'; import FormLogin from './FormLogin'; import Admin from './Component/Admin/Admin'; export default class Login extends Component { constructor(props) { super(props); this.state = { status:false, email: null, displayName: null, } } // xác thực provider authenticate = provider => { console.log(provider); const authProvider = new firebase.auth[`${provider}AuthProvider`](); firebaseApp .auth() .signInWithPopup(authProvider) .then(this.authHandler); }; // xử lý sau khi xác thực authHandler = async authData => { const user = authData.user; console.log(user); this.setState({ status : true, email: user.email, displayName: user.displayName }); }; logout = async () => { await firebase.auth().signOut(); this.setState({status:false ,email: null, displayName: null }); }; render() { let renderUi = null; if(!this.state.status){ renderUi = <> <FormLogin loginWithface={()=>this.authenticate('Facebook')}></FormLogin> </> }else{ renderUi = <> <Admin logoutWithface = {()=>this.logout()}></Admin> </> } return ( renderUi ) }; } <file_sep>/src/Action/BillAction.js export const AddProductBill = (product)=>{ return { type : "ADD_ProductBill", payload : product, } } export const DeleteProductBill = (product)=>{ return { type : "DELETE_ProductBill", payload : product, } }<file_sep>/src/Component/Admin/MainAdmin/MainItemDashboard.js import React, { Component } from 'react' export default class MainItemDashboard extends Component { render() { return ( <> <div className="col-xl-3 col-md-6 mb-4"> <div className={"card border-left-"+this.props.colorBorder+" shadow h-100 py-2"}> <div className="card-body"> <div className="row no-gutters align-items-center"> <div className="col mr-2"> <div className="text-xs font-weight-bold text-primary text-uppercase mb-1"> {this.props.title} </div> <div className="h5 mb-0 font-weight-bold text-gray-800"> {this.props.titleItems} </div> </div> <div className="col-auto"> <i className="fas fa-calendar fa-2x text-gray-300" /> </div> </div> </div> </div> </div> </> ) } } <file_sep>/src/Component/Admin/MainAdmin/Banhang/RouterTable.js import React, { Component } from 'react' import { BrowserRouter as Router, Switch, Route, useParams } from "react-router-dom"; import BanhangItem from './BanhangItem'; import ShowProduct from './ShowProduct/ShowProduct'; export default class RouterTable extends Component { render() { return ( <Switch> <Route exact path="/banhang" component={BanhangItem} /> <Route path="/banhang/ban/:id" component={ShowProduct} /> </Switch> ) } } <file_sep>/src/Component/Admin/SlideBar/SlideBarItem.js import React, { Component } from 'react' import { BrowserRouter as Router, Switch, Route, NavLink } from "react-router-dom"; export default class SlideBarItem extends Component { render() { return ( <li className="nav-item navDirect"> <NavLink to={this.props.changeContent} activeStyle={{ backgroundColor: "white", color: "blue" }}> <img src={this.props.icon} alt="" className="img img-fluid img-iconSlide" /> <span>{this.props.nameItem}</span> </NavLink> </li> ) } } <file_sep>/src/Store.js const { createStore } = require("redux"); const { default: RootReducers } = require("./Reducers/RootReducers"); const Store = createStore(RootReducers); export default Store;<file_sep>/src/Component/Admin/SlideBar/SlideBar.js import React, { Component } from 'react' import {BrowserRouter as Router,Switch,Route,Link} from "react-router-dom"; import SlideBarItem from './SlideBarItem' export default class SlideBar extends Component { render() { return ( <ul className="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <a className="sidebar-brand d-flex align-items-center justify-content-center" href> <div className="sidebar-brand-text mx-3">Coffee T&#38;T</div> </a> <hr className="sidebar-divider my-0" /> <hr className="sidebar-divider" /> <SlideBarItem nameItem="Bán Hàng" changeContent="/banhang" icon="/src/img/banhang.png"></SlideBarItem> <SlideBarItem nameItem="Tổng Quan" changeContent="/tongquan" icon="/src/img/tongquan.png"></SlideBarItem> <SlideBarItem nameItem="Sản phẩm" changeContent="/sanpham" icon="/src/img/sanpham.png"></SlideBarItem> <SlideBarItem nameItem="Bài viết" changeContent="/baiviet" icon="/src/img/baiviet.png"></SlideBarItem> <SlideBarItem nameItem="Thống kê" changeContent="/thongke" icon="/src/img/thongke.png"></SlideBarItem> </ul> ) } } <file_sep>/src/Component/Admin/MainAdmin/Banhang/ShowProduct/TypeProduct.js import React, { Component } from 'react' export default class TypeProduct extends Component { render() { return ( <li className="typeProductItem "> <div className="productItemBox shadow"> <img src={this.props.imgProductItem} alt="" className="img img-fluid imgTypeProduct" /> <p className="nameProductItems">{this.props.nameProductItem}</p> </div> </li> ) } } <file_sep>/src/Component/Admin/MainAdmin/CommentItems.js import React, { Component } from 'react' export default class CommentItems extends Component { render() { return ( <div className="commentItems"> <div className="iUser"> <img src={this.props.imgUserComment} alt="" className="img img-fluid img-Avar" /> <h5 className="nameUserComment">{this.props.nameUserComment}</h5> </div> <p className="ct_comment"> {this.props.commentContent} </p> </div> ) } } <file_sep>/src/Component/Admin/MainAdmin/Banhang/TableItems.js import React, { Component } from 'react' import { BrowserRouter as Router, Switch, Route, NavLink ,useParams} from "react-router-dom"; export default class TableItems extends Component { render() { return ( <> <div className="col-md-3 col-sm-6 col-lg-3 colTableName"> <NavLink to={"/banhang/ban/"+this.props.numberTable}> <div className="tableCell shadow" onClick={()=>this.props.showTable()}> <img src="/src/img/table.png" alt="" className="img img-fluid imgTable" /> <p className="tableName"> Bàn {this.props.numberTable} </p> </div> </NavLink> </div> </> ) } }
a1870df4aa455ea34f1a82c9640115f489fdf29e
[ "JavaScript" ]
16
JavaScript
lethanhdat12/quanlycf-reactjs
add284c8cc00ec093791080459fef7f83d508250
e1a55070f56b948a7a35779b44d2b00ee01833b9
refs/heads/master
<file_sep>""" <NAME> CS Introduction into Computation Laboratory 5""" import random products = input("What is items do you have? ") product_list = products.split(", ") location = input("What is your location? ") # Setting the second input def output(location, product_list): print("SALES TAX CALCULATION PROGRAM") if get_sales_tax(location) == 0.08: print("You are in Birmingham so the sales tax is 0.08") else: print("You are outside Birmingham so the sales tax is 0.04") i = 1 total = 0 for product in product_list: print("The price of product " + str(i) + " is " + str(get_price(product))) if get_excise_tax(product) > 0: print(" The excise tax is " + str(get_excise_tax(product))) else: print(" There are no excise taxes on this product") total = (total + get_total(location, product)) print(" The total price is " + str(get_total(location, product))) print("The overall price is " + str(total)) print("") i = i + 1 def get_price(product): if product.lower() == "gasoline": price = 20 elif product.lower() == "tobacco": price = 10 elif product.lower() == "alcohol": price = 15 else: price = int(input("What is the price?")) return price def get_excise_tax(product): """ Parameters: product Input: product output:product of get_price return:price""" if get_price(product) == 20: tax = 1.60 elif get_price(product) == 10: tax = 5.00 elif get_price(product) == 15: tax = 2.00 else: tax = 0 return tax def get_sales_tax(location): #Defining the parameter for get_loc function """ Parameters: Location Input: location/input output: salestax of the location return: salestax""" if location.lower() == "birmingham": #IF BIRMINGHAM is the city, it will return a higher tax sales_tax = 0.08 else: sales_tax = 0.04 return sales_tax def get_total(location,product): """ Parameters: Location and Product input: all of the functions previously made output: total price of the three functions listed return: None""" return price + get_excise_tax(product) + (price * get_sales_tax()) #Calling each function so that it will provide the total output(location, product_list)
9cf46d3a4c7f31acfdb958930d85036b9bfdd843
[ "Python" ]
1
Python
Awingo/Taxes
333f3f37ceca0bd72d6875523d8add85a871e5c2
f1f84e58f88452902c59a627f6ee47703290dbf9
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>管理ページ</title> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="/css/import.css?<?=mt_rand()?>"> <style> @media (min-width: 1200px) { .l-main { max-width: none; margin: 0 0 0 250px; } } </style> </head> <body id="top" class="l-body--manage"> <header class="l-header d-n"> <h1>管理ページ</h1> </header> <nav class="l-nav"> <h2 class="d-n">管理メニュー</h2> <input id="j-nav__checkbox" class="l-nav__checkbox" type="checkbox" /> <div class="l-nav__bar"> <a class="l-nav__bar-icon-box" href="#top" title="ページトップ"> <i class="material-icons">home</i> </a> <label for="j-nav__checkbox" class="l-nav__bar-icon-box"> <i class="material-icons"></i> </label> </div> <div class="l-nav__menu"> <ul class="l-nav__menu-ul"> <li><a href="/manage/" title="お知らせ"><i class="material-icons">info</i>お知らせ</a> <li><a href="/manage/contents" title="コンテンツ管理"><i class="material-icons">edit</i>コンテンツ管理</a> <li><a href="/manage/category" title="カテゴリー管理"><i class="material-icons">view_list</i>カテゴリー管理</a> <li><a href="/manage/color" title="カラー管理"><i class="material-icons">color_lens</i>カラー管理</a> <li><a href="/manage/setting" title="アカウント設定"><i class="material-icons">account_circle</i>アカウント設定</a> <li><a href="/manage/setting" title="サイト設定"><i class="material-icons">settings</i>サイト設定</a> </ul> </div> <label for="j-nav__checkbox" class="l-nav__overlay"></label> </nav> <main class="l-main"> <?=$this->session->flashdata('flash');?> <ul> <li><a href="/manage/create_table/admins_table">/manage/create_table/admins_table</a></li> <li><a href="/manage/drop_table/admins_table">/manage/drop_table/admins_table</a></li> <li><a href="/manage/create_table/categories_table">/manage/create_table/categories_table</a></li> <li><a href="/manage/drop_table/categories_table">/manage/drop_table/categories_table</a></li> <li><a href="/manage/create_table/contents_table">/manage/create_table/contents_table</a></li> <li><a href="/manage/drop_table/contents_table">/manage/drop_table/contents_table</a></li> </ul> </main> <? include_once(__DIR__.'/../_parts/_footer.php') ?> </body> </html><file_sep><?php class Common_Model extends CI_Model { function __construct() { parent::__construct(); $this->load->database(); $this->load->dbforge(); date_default_timezone_set('Asia/Tokyo'); } function create_table_model($table_name = '') { if(!$this->db->table_exists($table_name)) { if ($table_name === 'admins_table') { $this->dbforge->add_field( array( 'id' => array( 'type' => 'INT', 'constraint' => 9, 'unsigned' => TRUE, 'auto_increment' => TRUE, ), 'created_at' => array( 'type' => 'DATETIME', ), 'updated_at' => array( 'type' =>'DATETIME', ), 'login_at' => array( 'type' =>'DATETIME', ), 'name' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'email' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'pass' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'is_alive' => array( 'type' => 'INT', 'constraint' => 1, 'unsigned' => TRUE, 'default' => 1, ), ) ); } elseif ($table_name === 'categories_table') { $this->dbforge->add_field( array( 'id' => array( 'type' => 'INT', 'constraint' => 9, 'unsigned' => TRUE, 'auto_increment' => TRUE, ), 'created_at' => array( 'type' => 'DATETIME', ), 'updated_at' => array( 'type' =>'DATETIME', ), 'content_updated_at' => array( 'type' =>'DATETIME', ), 'name_en' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'name_ja' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'css' => array( 'type' => 'TEXT', 'null' => TRUE, ), 'is_nav' => array( 'type' => 'INT', 'constraint' => 1, 'unsigned' => TRUE, 'default' => 0, ), 'is_top' => array( 'type' => 'INT', 'constraint' => 1, 'unsigned' => TRUE, 'default' => 0, ), 'is_single' => array( 'type' => 'INT', 'constraint' => 1, 'unsigned' => TRUE, 'default' => 0, ), 'list_type' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), ) ); } elseif ($table_name === 'contents_table') { $this->dbforge->add_field( array( 'id' => array( 'type' => 'INT', 'constraint' => 9, 'unsigned' => TRUE, 'auto_increment' => TRUE, ), 'created_at' => array( 'type' => 'DATETIME', ), 'updated_at' => array( 'type' =>'DATETIME', ), 'category_id' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'title' => array( 'type' => 'VARCHAR', 'constraint' => 255, ), 'text' => array( 'type' => 'TEXT', 'null' => TRUE, ), 'img' => array( 'type' => 'TEXT', 'null' => TRUE, ), 'css' => array( 'type' => 'TEXT', 'null' => TRUE, ), ) ); } else { $message = $table_name ? $table_name.'は' : '' ; $message =+ '定義されていません'; return $message; } $this->dbforge->add_key('id', TRUE); if($this->dbforge->create_table($table_name)) { $message = $table_name.'の作成に成功しました'; } else { $message = $table_name.'の作成に失敗しました'; } } else { $message = $table_name.'はすでに存在します'; } return $message; } function drop_table_model($table_name) { if($this->db->table_exists($table_name)) { if($this->dbforge->drop_table($table_name)) { $message = $table_name.'の削除に成功しました'; } else { $message = $table_name.'の削除に失敗しました'; } } else { $message = $table_name.'は存在しません'; } return $message; } function insert_model($table_name = '', $array = array()) { $array['created'] = date('Y-m-d H:i:s'); if($table_name === 'temp_user_table') { $insert_string = array( 'key' => $array['key'], 'email' => $_POST['email'], 'pass' => $_POST['pass'], 'created' => $array['created'], ); } elseif ($table_name === 'user_table') { $this->db->where('key', $array['key']); $temp_user = $this->db->get('temp_user_table'); if($temp_user){ $row = $temp_user->row(); $insert_string = array( 'name' => substr($row->email, 0, strpos($row->email, '@')), 'email' => $row->email, 'pass' => $row->pass, 'created' => $array['created'], ); } } elseif ($table_name === 'task_table') { $insert_string = array( 'user_id' => $_SESSION['user_id'], 'title' => $array['title'], 'time_limit' => $array['time_limit']?:0, 'time_total' => $array['time_total'], 'start' => $array['start'], 'stop' => $array['stop'], 'created' => $array['created'], ); } else { return false; } $query = $this->db->insert_string($table_name, $insert_string); if($this->db->query($query)) { return $this->db->insert_id(); } else { return false; } } function update_model($table_name = '', $array = array()) { if($table_name === 'temp_user_table') { $update_string = array( 'pass' => $_POST['pass'], ); $where = array( 'email' => $_POST['email'], 'status' => 1, ); } elseif ($table_name === 'user_table') { } elseif ($table_name === 'task_table') { } else { return false; } $query = $this->db->update_string($table_name, $update_string, $where); if($this->db->query($query)) { return true; } else { return false; } } public function delete_model($table_name = '', $array) { $array['deleted'] = date('Y-m-d H:i:s'); if($table_name === 'temp_user_table') { $update_string = array( 'deleted' => $array['deleted'], 'status' => 0, ); $this->db->where('key', $array['key']); } if($this->db->update($table_name, $update_string)) { return true; } else { return false; } } }<file_sep><footer class="l-footer"> <i class="material-icons l-footer-i">copyright</i>2018 <NAME> </footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> /*global $*/ // ページ内スムーズスクロール $('a[href^="#"]').click(function(){ var speed = 800; var href= $(this).attr("href"); var target = $(href == '#' || href == '' ? 'html' : href); var position = target.offset().top; $('html, body').animate({scrollTop:position}, speed, 'swing'); return false; }); // SP版メニューをクリックした時の挙動 $('#j-nav__menu a').click(function(){ $('#j-nav__checkbox').prop('checked',false); }); </script><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Manage extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('Common_Model'); } public function index() { $this->load->view('manage/index'); } function create_table($table_name) { $_SESSION['flash'] = $this->Common_Model->create_table_model($table_name); $this->session->mark_as_flash('flash'); redirect('manage/'); } function drop_table($table_name) { $_SESSION['flash'] = $this->Common_Model->drop_table_model($table_name); $this->session->mark_as_flash('flash'); redirect('manage/'); } } <file_sep># 説明 ほしさきひとみのポートフォリオサイト # HTML/CSSコーディング規約 + [こちらの記事](https://qiita.com/pugiemonn/items/964203782e1fcb3d02c3) の考え方をベースにする + [Google HTML/CSS Style Guide](https://google.github.io/styleguide/htmlcssguide.html) に準じる + CSS構成は [FLOCSS(フロックス)](https://github.com/hiloki/flocss) を採用する + utilityは [emma.css](https://github.com/ruedap/emma.css/blob/master/emma.css) を拝借する # 命名規則マイルール + 命名規則は [BEM](https://qiita.com/pugiemonn/items/964203782e1fcb3d02c3) を採用する + CSSにはclassを使う + layoutもclassを使い、接頭辞"l-"をつける + JSにはできるだけidを使い、接頭辞"j-"をつける + .Block(そのまとまりで一番上の親要素)__Element(部品)--Modifier(状態) + 単語区切りはハイフン「-」 + 特定の要素にのみ使用させたいクラスは、Element(部品)の末尾に「-要素名」 + 特定の何かを囲みたいクラスは、Element(部品)の末尾に「-box」 + Modifier(状態)のキーとバリューの区切りにはアンダーバー「_」 ## HTMLマイルール + ひとかたまりとして見せたい場合(目安は5行以上)は、前後に1行だけ空ける + 1行はできるだけ80文字以内におさめる + セレクタを書く順番は、for → id → class → その他 ## CSSマイルール + 基本的にフォントやmargin/padding等のサイズはrem単位で指定する + ブレイクポイント @media (min-width: 1200px) { Tablets + Desktops } + メディアクエリはその場その場で書き込んじゃう + 色は https://www.materialui.co/colors の 偶数を基本的に使う ## CSSコメントルール ``` /* ************************************************************ * 大見出し(前後に空行) * ************************************************************ */ ``` ``` /* 中見出し(前後に空行) ************************************__**** */ ``` ``` /* 小見出し(前だけ空行) */ ``` <file_sep><!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>スタンダードレイアウト</title> <link rel="stylesheet" href="/css/import.css?<?=mt_rand()?>"> </head> <body> <header class="l-header"> </header> <nav class="l-nav"> </nav> <main class="l-main"> </main> <footer class="l-footer"> </footer> </body> </html><file_sep><!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="description" content="Webエンジニア・ほしさきひとみのポートフォリオサイト。主にPHP/Rails/HTML5/CSS3/jQueryを使う。"> <meta name="keywords" content="ほしさきひとみ,Webエンジニア,プログラマー,コーダー,ディレクター,デザイナー,就職活動,転職活動,フリーランス,ポートフォリオ,制作実績,Web制作,自己PR,職務経歴"> <title>ほしさきひとみポートフォリオサイト</title> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="/css/import.css?<?=mt_rand()?>"> </head> <body id="top" class="l-body--public"> <header class="l-header"> <h1> <a href="#top" title="サイトTOP"> <div class="l-header__role">Webエンジニア</div> <div class="l-header__name">ほしさき ひとみ</div> <div class="l-header__roman">Hitomi Hoshisaki</div> <span class="d-n">ポートフォリオサイト</span> </a> <img class="l-header__face" src="/img/my/face.png" alt="私の顔写真" /> </h1> </header> <nav class="l-nav"> <h2 class="d-n">サイトメニュー</h2> <input id="j-nav__checkbox" class="l-nav__checkbox" type="checkbox" /> <div class="l-nav__bar"> <a class="l-nav__bar-icon-box" href="#top" title="ページトップ"> <i class="material-icons">home</i> </a> <label for="j-nav__checkbox" class="l-nav__bar-icon-box"> <i class="material-icons"></i> </label> </div> <div id="j-nav__menu" class="l-nav__menu"> <ul class="l-nav__menu-ul"> <li><a href="#portfolio" title="ポートフォリオ"><i class="material-icons">developer_board</i>ポートフォリオ</a> <li><a href="#works" title="職務経歴"><i class="material-icons">description</i>職務経歴</a> <li><a href="#profile" title="自己紹介"><i class="material-icons">face</i>自己紹介</a> <li><a href="#introduction" title="他己紹介"><i class="material-icons">textsms</i>他己紹介</a> <li><a href="#contact" title="お問い合わせ"><i class="material-icons">send</i>お問い合わせ</a> </ul> </div> <label for="j-nav__checkbox" class="l-nav__overlay u-d-n-pc"></label> </nav> <address class="l-address"> <ul class="l-address__icon-ul"> <li><a href="mailto:hitomi[あっとまーく]hoshisaki.net" title="mail"><img src="/img/social/mail.png" alt="mail" /></a></li> <!--<li><a href="" title="LINE"><img src="/img/social/line.png" alt="LINE" /></a></li>--> <li><a href="https://twitter.com/HitomiHoshisaki" title="Twitter" target="_blank"><img src="/img/social/twitter.png" alt="Twitter" /></a></li> <li><a href="https://www.facebook.com/HitomiHoshisaki" title="facebook" target="_blank"><img src="/img/social/facebook.png" alt="facebook" /></a></li> <li><a href="https://qiita.com/HitomiHoshisaki" title="Qiita" target="_blank"><img src="/img/social/qiita.png" alt="Qiita" /></a></li> <li><a href="https://github.com/HitomiHoshisaki" title="GitHub" target="_blank"><img src="/img/social/github.png" alt="GitHub" /></a></li> </ul> <ul class="l-address__text-ul"> <li><a href="mailto:hitomi[あっとまーく]hoshisaki.net" title="mail">hitomi@hoshisaki.net</a></li> <li><a href="<?= $_SERVER['REQUEST_SCHEME'] ?>://<?= $_SERVER['HTTP_HOST'] ?>" title="URL"><?= $_SERVER['REQUEST_SCHEME'] ?>://<?= $_SERVER['HTTP_HOST'] ?></a></li> </ul> </address> <main class="l-main"> <article id="portfolio"> <h2>ポートフォリオ</h2> </article> <article id="works"> <h2>職務経歴</h2> <p>新卒で、大手中古本販売チェーンに入社。店長、新店の立ち上げ店長を経験後、社員教育の研修インストラクターに抜擢されました。その後、大手求人広告サイトの運営会社にコピーライターとして転職。Excelスキルを認められ、大量のCSVデータを扱う部署に異動しました。Excel関数やマクロを使った時間短縮・応募効果の向上に貢献。現在は職業訓練校でWEBを勉強中です。</p> <h3>大手中古本販売チェーン</h3> <h4>[業務内容]</h4> <p>店長として、スタッフの採用・教育、売場作り、宣伝広告、売上管理、損益計画などを経験しました。研修インストラクターとしては、既存社員・新入社員・FC向けの研修講師、研修のカリュラム作成、アルバイトスタッフ海外研修の引率、マニュアル作成、売上不振店の短期立て直しなどを行ないました。</p> <h4>[マネジメント経験]</h4> <p>店⻑として、アルバイト7〜15名のマネジメントを行ないました。コミュニケーションを重視し、会社の理念や店舗の売上目標、ひとつひとつのオペレーションの意味を伝え続けました。考え方を共有する事でチームがまとまり、業績も向上しました。</p> <h4>[アピールポイント]</h4> <p>売上不振店の業務改善では、「店⻑のコミュニケーションの質の向上」と「カウンター内の作業効率の向上」に力を入れました。するとスタッフのモチベーションが上がり、店に活気が戻ります。その後の売場レイアウト変更などもスムーズに進みます。1日当たりの売上ベースが目に見えて上がりました。</p> <h3>大手求人広告サイトの運営会社</h3> <h4>[業務内容]</h4> <p>初めは主に、アルバイト求人サイトのコピーライティングを担当。その後Excelスキルを認められ、CSVを使ったサイト運用代行を任されました。大手派遣会社が持つ数千件の求人データの中から効果的な案件を数百件選び、最適な形にデータを加工してサイトに掲載するという業務です。</p> <h4>[アピールポイント]</h4> <p>作業手順の見直しやマニュアルの修正、秀丸・Excelのマクロ活用などを行ない、作業時間を半減させました。Excelでの効果分析を通じて応募効果が上がり、派遣会社に感謝されて売上も伸びました。チームメンバー向けにExcel勉強会を開催し、チーム全体の作業効率・応募効率の向上にも貢献しました。</p> </article> <article id="profile"> <h2>自己紹介</h2> <h3>1.コミュニケーション能力</h3> <p>研修インストラクターを経験し、目的や行動の意味、具体的なオペレーションを相手に伝える力が身につきました。相手に受け入れてもらうためには、まず自分が相手を受け入れることが重要だと考えます。将来はWEB制作ディレクターとして、この能力を活かしたいです。</p> <h3>2.問題発見解決能力</h3> <p>「“面倒くさい”は改善のチャンス」だと考えています。例えばテープカッターの配置を変えるだけで、ぐんと作業効率があがることがあります。すでにある方法に満足せず、もっといい方法がないかを考え、実行します。この能力により、店⻑職でもデスクワークでも、作業効率と売上を伸ばしてきました。</p> <h3>3.学ぶ力</h3> <p>学ぶことが好きです。分からないことがあるとすぐに調べたり、本を読んだりする習慣があります。Excel関数・マクロ・ピボットテーブル、秀丸マクロなども、ほぼ独学で使ってきました。未経験ではありますが、WEB制作の現場でも学ぶ力を発揮し、早期にお役に立てるよう努めます。</p> </article> <article id="introduction"> <h2>他己紹介</h2> <p>WEB設計科のクラスメイト20人に聞いた、私の印象です。プレゼンテーションの授業でいただいたものを流用しました。</p> <ol> <li>しっかりしている。コミュニケーションに気を使う。クラスの雰囲気作りがとてもよい。</li> <li>サザエさんのうきえさんを思い浮かべる。安心感。あこがれ。</li> <li>リーダーシップがある。とてもしっかりしていて頼れる人です。</li> <li>頼れる人。</li> <li>しっかりしていて、頼もしい姉さんです。</li> <li>しっかりしている。人をうまくまとめられる。</li> <li>明るいしっかり者。</li> <li>しっかり者の芸術肌もってる人。周りへの配慮・調整がうまい。</li> <li>天才!がんばんなくても何でもわかっちゃうタイプ?</li> <li>リーダー!!</li> <li>何事もソツがないと思います。</li> <li>思考の回転が早い。仕事が早い。細かい事に気がつく。常に周囲を見ている。気がつかえる。</li> <li>人の上に立つのが合いそう。</li> <li>明るい。しきるのが上手。どりょく家。</li> <li>プレゼン能力と、周囲の状況把握能力が高い。人間好き。自信あり。</li> <li>リーダーシップがある。常に周囲に気を配っている。理解力が高い。</li> <li>明るくリーダーシップがある。人に気を使える。超いい人。みんなで遊ぶのが好きな人。</li> <li>頭の回転が速い。物事を整理して捉えることができる。アイディアがほうふ。</li> <li>しっかりしていてとても優しい人。人に気を使わせないようにするのが上手な気づかいの人。</li> <li>いつも大変お世話になっております。優しすぎ!</li> </ol> </article> <section id="contact"> <h2>お問い合わせ</h2> <form method="post" action="check.php"> <dl> <dt>御社名</dt> <dd> <input type="text" name="company" value="" class="input_half"> <small><span class="span_option">任意</span></small> </dd> <dt>お名前</dt> <dd> <input type="text" name="name" value="" required class="input_half"> <small><span class="span_required">必須</span></small> </dd> <dt>返信用メールアドレス</dt> <dd> <input type="email" name="mail" value="" required class="input_half"> <small><span class="span_required">必須</span></small> </dd> <dt>お電話番号</dt> <dd> <input type="tel" name="tel" value="" class="input_half"> <small><span class="span_option">任意</span></small> </dd> <dt>ご用件</dt> <dd> <select name="title" class="input_half" required> <option value="面接へのお誘い">面接へのお誘い</option> <option value="会社見学へのお誘い">会社見学へのお誘い</option> <option value="おすすめ求人情報">おすすめ求人情報</option> <option value="その他お問い合わせ">その他お問い合わせ</option> </select> <small><span class="span_required">必須</span>&nbsp;選択してください</small> </dd> <dt>お問い合わせ内容&nbsp;<span class="span_required">必須</span></dt> <dd><textarea name="body" value="" required></textarea></dd> </dl> <div> <button type="reset" class="button_back">リセット</button> <button type="submit">入力内容を確認する</button> </div> </form> </section> </main> <? include_once(__DIR__.'/../_parts/_footer.php') ?> </body> </html>
8ba5d0737cc04c5b19ef2f9a077bd7239530157a
[ "Markdown", "PHP" ]
7
PHP
HitomiHoshisaki/portfolio
17e1ac9a51c56f9462f40ec3ac73c76221f76e19
471f15fd32dbef65fe82a6f1ec5394a23978be44
refs/heads/master
<file_sep>autopep8==1.4.4 certifi==2022.12.7 chardet==3.0.4 Deprecated==1.2.6 entrypoints==0.3 flake8==3.7.8 idna==2.8 mccabe==0.6.1 pycodestyle==2.5.0 pyflakes==2.1.1 PyGithub==1.43.8 PyJWT==2.4.0 requests==2.22.0 six==1.10.0 spotipy==2.22.1 urllib3==1.26.5 wrapt==1.11.2<file_sep>import subprocess from github import Github from github.InputFileContent import InputFileContent from credentials import CREDS from driver import main subprocess.call(["python", "driver.py"]) g = Github(CREDS['TOKEN']) spotify_gist = g.get_gist(CREDS['GIST_ID']) f = InputFileContent(main()) spotify_gist.edit('🎧 My music over 4 weeks', {'🎧 My music over 4 weeks': f}) <file_sep># Spotify Pin ## About repo This repo contains necessary script for updating the GitHub Gist with your top Spotify artists over 4 weeks. Inspired by the profile of [Jack](https://github.com/jacc). Look at his profile, he's got an awesome pin collection on his profile. ![Pin Screenshot](Screenshots/PinScreenshot.PNG) Desi at Heart ❤️(Moosewala on top) ## Usage 1. Clone the repository ```bash git clone https://github.com/puneet29/SpotifyPin.git cd SpotifyPin ``` 2. Create new virtual environment - On windows: ```bash python -m venv venv ``` - On Linux: ```bash python3 -m venv venv ``` 3. Activate virtual environment - On windows: ```bash venv\Scripts\activate ``` - On Linux: ```bash . venv/bin/activate ``` 4. Install all the dependencies ```bash pip3 install -r requirements ``` 5. Update ```credentials.py```. Generate new token for Gist privileges from Settings->Developer Options. 6. Update ```driver.py```. Change the username to your own username. 7. Update ```run.bat```. Update the path to cloned directory. 8. (For windows only) Setup a new task in task scheduler. Setup a time at which the run.bat file will run in background. <file_sep># Imports import math import spotipy import spotipy.util as util from credentials import CREDS # Global variables CLIENT_ID = CREDS['CLIENT_ID'] CLIENT_SECRET = CREDS['CLIENT_SECRET'] USERNAME = 'Your username' SCOPE = 'user-top-read' # user-read-recently-played def generateBarChart(fraction, size): syms = " ▏▎▍▌▋▊▉█" frac = size * 8 * fraction barsFull = frac // 8 semi = round(frac % 8) barsEmpty = size - barsFull - 1 return('|' + (syms[8] * int(barsFull)) + syms[semi:semi+1] + (syms[0] * int(barsEmpty)) + '|') def main(): # Token generation token = util.prompt_for_user_token(USERNAME, scope=SCOPE, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri='http://localhost/') # Driver code if token: sp = spotipy.Spotify(auth=token) artists = {} final = '' results = sp.current_user_top_tracks(50, time_range='short_term') for t, res in enumerate(reversed(results['items']), start=1): for r in res['artists']: if(r['name'] in artists): artists[r['name']][0] += math.log2(t) artists[r['name']][1] = res['name'] else: artists[r['name']] = [math.log2(t), res['name']] artists = sorted(artists.items(), key=lambda x: (x[1][0], x[0]), reverse=True)[:10] freq = sum(x[1][0] for x in artists) for i, j in artists: bar = generateBarChart(j[0]/freq, 20) final += '{:<25} {:<10} {:>10.2f}% {:>35}\n'.format( i, bar, j[0]/freq*100, j[1]) return final else: return("Can't get token for", USERNAME) <file_sep>CLIENT_ID = None CLIENT_SECRET = None TOKEN = None GIST_ID = None CREDS = {'CLIENT_ID': CLIENT_ID, 'CLIENT_SECRET': CLIENT_SECRET, 'GIST_ID': GIST_ID, 'TOKEN': TOKEN}
e57ae20582c62c030af2b918f5b61d2ce1c2c30f
[ "Markdown", "Python", "Text" ]
5
Text
puneet29/SpotifyPin
c88f27225a0a5c5f9dc828193e97a67677f8d227
b13fbe2b9ead86d563cfd97ab0e358d3ef18991d
refs/heads/master
<repo_name>Davidvalecillo/api-laravel-con-dingo<file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ /** RUTAS DE MI API **/ $api = app('Dingo\Api\Routing\Router'); /** GRUPO DE RUTAS PARA VERSION 1 DE MI API**/ $api->version('v1', function ($api) { $api->group(['namespace' => 'App\Http\Controllers'], function($api){ $api->resource('users', 'UsersController'); }); }); <file_sep>/readme.md # api-laravel-con-dingo Proyecto de pruebas para la creacion de apis haciendo uso de laravel + paquetes Dingo y OAuth2 Guia de Ayuda: http://hechoenlaravel.com/w/api-con-dingo-y-oauth2 https://github.com/lucadegasperi/oauth2-server-laravel
9df06fb945f5a6487efebf944eeff221d112c853
[ "Markdown", "PHP" ]
2
PHP
Davidvalecillo/api-laravel-con-dingo
a505e78c6b65a4ded99731cd275dc49304795106
bf2321066169b35dc45cd810a0e557543990457d
refs/heads/master
<file_sep>package com.heyy.study.springbootstudycentral.constants; /** * @Classname RegExpConstants * @Description TODO * @Date 2019/5/9 20:49 * @Created by Breeze */ public class RegExpConstants { public static final String REGEX_NAME = "([A-Za-z0-9\\u4e00-\\u9fa5]|-){1,}"; public static final String REGEX_STAFF_ID = "\\d+"; public static final String REGEX_STAFF_NAME = "^[A-Za-z]+$"; public static final String REGEX_FROM_DB = "(TRUE|FALSE)"; public static final String REGEX_ADDRESS_TYPE = "[123]{1}"; public static final String REGEX_ID_TYPE = "[01]{1}"; } <file_sep>package com.heyy.study.springbootstudycentral.config; import lombok.extern.slf4j.Slf4j; import org.springframework.http.client.SimpleClientHttpRequestFactory; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.HttpURLConnection; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * @Classname TrustAllClientRequestFactory * @Description trust all certs * @Date 2019/5/11 10:01 * @Created by Breeze */ @Slf4j public class TrustAllClientRequestFactory extends SimpleClientHttpRequestFactory{ @Override protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if(!(connection instanceof HttpsURLConnection)){ throw new RuntimeException("an instance of HttpsURLConnection required"); } HttpsURLConnection httpsURLConnection = (HttpsURLConnection)connection; TrustManager[] trustManagers = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { // return new X509Certificate[0]; return null; } } }; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null,trustManagers , new SecureRandom()); httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory()); httpsURLConnection.setHostnameVerifier((hostname,session) -> true); } catch (Exception e) { log.error("prepareConnection occur exception",e); } } } <file_sep>package com.heyy.study.springbootstudycentral.utility; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.heyy.study.springbootstudycentral.exception.CustomException; import com.heyy.study.springbootstudycentral.exception.ExceptionEnum; import java.io.IOException; import java.util.Objects; /** * @Classname ObjectUtil * @Description TODO * @Date 2019/5/10 20:01 * @Created by Breeze */ public class ObjectUtil { private static ObjectMapper mapper = new ObjectMapper(); static { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false ); } public static <T> JavaType getType(Class<T> simpleClass){ return mapper.getTypeFactory().constructType(simpleClass); } public static <T,V> JavaType getParametricType(Class<T> wrapper,Class<V> dataClass){ return mapper.getTypeFactory().constructParametricType(wrapper,dataClass); } public static <T,V> JavaType getParametricType(Class<T> wrapper,JavaType dataType){ return mapper.getTypeFactory().constructParametricType(wrapper,dataType); } public static <T> T jsonToObject(String jsonStr,JavaType type,ObjectMapper customMapper) { Objects.requireNonNull(jsonStr,"json string is null" ); try { return customMapper.readValue(jsonStr,type ); } catch (IOException e) { throw new CustomException(ExceptionEnum.SSC_0003,e.getMessage()); } } public static <T> T jsonToObject(String jsonStr,JavaType type){ return jsonToObject(jsonStr,type,mapper); } public static <T,W,I> T jsonToObject(String jsonStr,Class<W> wClass,Class<I> iClass){ return jsonToObject(jsonStr,getParametricType(wClass, iClass)); } public static <T> T jsonToObject(String jsonStr,Class<T> cls){ return jsonToObject(jsonStr,getType(cls)); } public static String objectToJson(Object obj,ObjectMapper customMapper){ Objects.requireNonNull(obj,"obj is null"); Objects.requireNonNull(customMapper,"customMapper is null"); try { return customMapper.writeValueAsString(obj); } catch (JsonProcessingException e) { throw new CustomException(ExceptionEnum.SSC_0004,e.getMessage()); } } public static String objectToJson(Object obj){ return objectToJson(obj,mapper ); } } <file_sep>http.proxy.host=aaaa http.proxy.port=8888<file_sep>package com.heyy.study.springbootstudycentral.service; import java.util.Map; /** * @Classname RestTemplateService * @Description TODO * @Date 2019/5/11 09:04 * @Created by Breeze */ public interface RestTemplateService { public String postWithHttps(String url,String requestBody,Map<String,String> custHeaders); public String getUrl(String protocal,String host,String port,String api); } <file_sep>package com.heyy.study.springbootstudycentral.been; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.fasterxml.jackson.databind.ser.std.StringSerializer; import com.heyy.study.springbootstudycentral.annotation.SensitiveFieldAnnotation; import com.heyy.study.springbootstudycentral.utility.EncryptUtil; import java.io.IOException; /** * @Classname EncryptSensitiveDataSerializer * @Description TODO * @Date 2019/5/10 21:23 * @Created by Breeze */ public class EncryptSensitiveDataSerializer extends StdSerializer<String> implements ContextualSerializer { private static final long serialVersionUID = -1897422003712932300L; public EncryptSensitiveDataSerializer(){ super(String.class); } @Override public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException { if(beanProperty!=null){ SensitiveFieldAnnotation sensitiveFieldAnnotation = (SensitiveFieldAnnotation)beanProperty.getAnnotation(SensitiveFieldAnnotation.class); if(sensitiveFieldAnnotation !=null){ return new EncryptSensitiveDataSerializer(); } } return new StringSerializer(); } @Override public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(EncryptUtil.encrypt(s)); } } <file_sep>name.not.blank=name should not be blank! idType.not.blank=idType should not be blank! idNo.not.blank=idNo should not be blank! province.not.blank=province should not be blank! city.not.blank=city should not be blank! addressType.not.blank=addressType should not be blank! detailAddress.not.blank=detailAddress should not be blank! idType.format.wrong=idType format is wrong! addressType.format.wrong=addressType format is wrong!<file_sep>package com.heyy.study.datasource.utility; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * @Classname PropertiesLoadUtility * @Description TODO * @Date 2019/5/11 09:16 * @Created by Breeze */ @Slf4j public class PropertiesLoadUtility { private Properties properties = new Properties(); public String getValueByKey(String path,String fileName,String key){ String result = ""; InputStream inputStream = this.getClass().getResourceAsStream(path.concat(fileName)); try { properties.load(inputStream); result = properties.getProperty(key); } catch (IOException e) { e.printStackTrace(); } return result; } } <file_sep>package com.heyy.study.springbootstudycentral.controller; import com.heyy.study.springbootstudycentral.been.CustResponseBody; import com.heyy.study.springbootstudycentral.been.Person; import com.heyy.study.springbootstudycentral.constants.RegExpConstants; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.Pattern; @RestController @RequestMapping(value = "/api/${application.api_version}/heyy") @Slf4j @Validated public class RequestBeanValidController { @PostMapping(value = "/valid/request",consumes = "application/json",produces = "application/json") public ResponseEntity requestValid(@RequestHeader(value = "staffId",required = true) @Pattern(regexp = RegExpConstants.REGEX_STAFF_ID) String staffId, @RequestHeader(value = "staffName") @Pattern(regexp = RegExpConstants.REGEX_STAFF_NAME) String staffName, @RequestParam(value = "fromDB",required = false) @Pattern(regexp = RegExpConstants.REGEX_FROM_DB) String formDB, @RequestBody @Validated Person person){ log.info("RequestBeanValidController.requestValid request data is:{}",person.toString()); CustResponseBody responseBody = new CustResponseBody(); responseBody.setResponseCode("000"); responseBody.setDescription("valid request data successful"); ResponseEntity<CustResponseBody> response = new ResponseEntity<>(responseBody,HttpStatus.OK); return response; } } <file_sep>package com.heyy.study.springbootstudycentral.config; import com.heyy.study.springbootstudycentral.filter.RequestBodyCacheFilter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @Classname FilterConfig * @Description config filter * @Date 2019/5/13 20:14 * @Created by Breeze */ @Configuration @Slf4j public class FilterConfig { @Bean public RequestBodyCacheFilter requestBodyCacheFilter(){ log.info("Registering Request body caching filter"); return new RequestBodyCacheFilter(); } } <file_sep>package com.heyy.study.springbootstudycentral.controller; import com.heyy.study.springbootstudycentral.been.CustResponseBody; import com.heyy.study.springbootstudycentral.been.Person; import com.heyy.study.springbootstudycentral.constants.RegExpConstants; import com.heyy.study.springbootstudycentral.utility.EncryptUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.Pattern; @RestController @RequestMapping(value = "/api/${application.api_version}/heyy") @Slf4j public class RequestBeanEncryptController { @PostMapping(value = "/encrypt/request",consumes = "application/json",produces = "application/json") public ResponseEntity requestValid(@RequestBody Person person){ log.info("RequestBeanValidController.requestValid request data is:{}", EncryptUtil.encryptToLog(person)); Person encryptPerson = EncryptUtil.encrypt(person); Person decryptPerson = EncryptUtil.dencrypt(encryptPerson); String responseCode = "008"; String description = "encrypt method test is not ok"; if(!encryptPerson.getIdNo().equals(person.getIdNo())&&decryptPerson.getIdNo().equals(person.getIdNo())){ responseCode = "000"; description = "encrypt method test is ok"; } CustResponseBody responseBody = new CustResponseBody(); responseBody.setResponseCode(responseCode); responseBody.setDescription(description); ResponseEntity<CustResponseBody> response = new ResponseEntity<>(responseBody,HttpStatus.OK); return response; } } <file_sep>package com.heyy.study.datasource.controller; import com.heyy.study.datasource.utility.PropertiesLoadUtility; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Classname PersonCheckResultController * @Description return person check result * @Date 2019/5/10 23:35 * @Created by Breeze */ @RestController @RequestMapping(value = "/api/${application.api_version}/datasource") @Slf4j public class PersonCheckResultController { @PostMapping(value = "/person/check",consumes = "application/json",produces = "application/json") public ResponseEntity personCheck(Object person){ log.info("PersonCheckResultController.personCheck method in"); String path = "/datasource/dummy/"; String fileName = "dummy-response.properties"; String key = "person.check.result"; String checkResult = new PropertiesLoadUtility().getValueByKey(path, fileName, key); ResponseEntity<Object> response = new ResponseEntity<>(checkResult, HttpStatus.OK); return response; } /*public static void main(String[] args) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String result = mapper.writeValueAsString(responseBody); System.out.println(result); }*/ } <file_sep>package com.heyy.study.springbootstudycentral.config; import com.heyy.study.springbootstudycentral.constants.CommonConstants; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.integration.http.converter.SerializingHttpMessageConverter; import org.springframework.web.client.RestTemplate; import javax.net.ssl.SSLContext; import java.net.InetSocketAddress; import java.net.Proxy; import java.nio.charset.Charset; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; /** * @Classname RestemplateConfig * @Description create Restemplate instance * @Date 2019/5/11 09:26 * @Created by Breeze */ @Configuration public class RestemplateConfig { @Value("${http.proxy.host}") private String proxyHost; @Value("${http.proxy.port}") private int proxyPort; private static List<HttpMessageConverter<?>> messageConverterList = new ArrayList<>(); static { messageConverterList.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); messageConverterList.add(new SerializingHttpMessageConverter()); messageConverterList.add(new FormHttpMessageConverter()); messageConverterList.add(new MappingJackson2HttpMessageConverter()); messageConverterList.add(new MappingJackson2XmlHttpMessageConverter()); } @Bean(name = "simpleRequestFactory") public SimpleClientHttpRequestFactory simpleRequestFactory(){ SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory(); simpleClientHttpRequestFactory.setConnectTimeout(CommonConstants.RESTEMPLATE_CONNECT_TIMEOUT); simpleClientHttpRequestFactory.setReadTimeout(CommonConstants.RESTEMPLATE_READ_TIMEOUT); return simpleClientHttpRequestFactory; } @Bean(name = "proxyRequestFactory") public SimpleClientHttpRequestFactory proxyRequestFactory(){ SimpleClientHttpRequestFactory simpleClientHttpRequestFactory = new SimpleClientHttpRequestFactory(); simpleClientHttpRequestFactory.setConnectTimeout(CommonConstants.RESTEMPLATE_CONNECT_TIMEOUT); simpleClientHttpRequestFactory.setReadTimeout(CommonConstants.RESTEMPLATE_READ_TIMEOUT); InetSocketAddress inetSocketAddress = new InetSocketAddress(this.proxyHost,this.proxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP,inetSocketAddress); simpleClientHttpRequestFactory.setProxy(proxy); return simpleClientHttpRequestFactory; } @Bean(name = "igonreSSLandProxyReuqestFactory") public HttpComponentsClientHttpRequestFactory igonreSSLandProxyReuqestFactory() throws Exception{ TrustStrategy trustStrategy = (final X509Certificate[] chain,final String authType) -> true; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null,trustStrategy).build(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient closeableHttpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build(); HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); httpComponentsClientHttpRequestFactory.setHttpClient(closeableHttpClient); httpComponentsClientHttpRequestFactory.setConnectTimeout(CommonConstants.RESTEMPLATE_CONNECT_TIMEOUT); httpComponentsClientHttpRequestFactory.setReadTimeout(CommonConstants.RESTEMPLATE_READ_TIMEOUT); return httpComponentsClientHttpRequestFactory; } @Bean(name = "ignoreSSLRequestFactory") public TrustAllClientRequestFactory ignoreSSLRequestFactory(){ TrustAllClientRequestFactory trustAllClientRequestFactory = new TrustAllClientRequestFactory(); trustAllClientRequestFactory.setConnectTimeout(CommonConstants.RESTEMPLATE_CONNECT_TIMEOUT); trustAllClientRequestFactory.setReadTimeout(CommonConstants.RESTEMPLATE_READ_TIMEOUT); InetSocketAddress inetSocketAddress = new InetSocketAddress(this.proxyHost,this.proxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP,inetSocketAddress); trustAllClientRequestFactory.setProxy(proxy); return trustAllClientRequestFactory; } @Bean(name = "ignoreSSLRestTemplate") public RestTemplate ignoreSSLRestTemplate(final TrustAllClientRequestFactory trustAllClientRequestFactory){ RestTemplate restTemplate = new RestTemplate(messageConverterList); restTemplate.setRequestFactory(trustAllClientRequestFactory); return restTemplate; } @Bean(name = "simpleRestTemplate") public RestTemplate simpleRestTemplate(final SimpleClientHttpRequestFactory simpleRequestFactory){ RestTemplate restTemplate = new RestTemplate(messageConverterList); restTemplate.setRequestFactory(simpleRequestFactory); return restTemplate; } } <file_sep>package com.heyy.study.springbootstudycentral.been; import lombok.Data; /** * @Classname CustResponseBody * @Description response body for request * @Date 2019/5/8 21:46 * @Created by Breeze */ @Data public class CustResponseBody { private String responseCode; private String description; } <file_sep>person.check.result={"idNoIsMatch":"false","nameIsMatch":"true","addressIsMatch":"false"}<file_sep>package com.heyy.study.springbootstudycentral.utility; import org.junit.Test; import java.util.Date; import static org.junit.Assert.*; /** * @Classname DateTimeUtilTest * @Description TODO * @Date 2019/5/12 20:44 * @Created by Breeze */ public class DateTimeUtilTest { @Test public void string2LocalDateTime() { String dateTime = "2019-05-12 20:45:45"; String pattern = "yyyy-MM-dd HH:mm:ss"; String timeZoneId = "GMT+8"; System.out.println(DateTimeUtil.string2DateTime(dateTime,pattern ,timeZoneId )); } @Test public void string2Date() { String dateTime = "2019-05-12"; String pattern = "yyyy-MM-dd"; String timeZoneId = "GMT+8"; System.out.println(DateTimeUtil.string2DateStartOfDay(dateTime,pattern ,timeZoneId )); } @Test public void timestamp2String() { Long time = System.currentTimeMillis(); System.out.println(DateTimeUtil.timestamp2String(time,DateTimeUtil.ZONEID_CHINA ,DateTimeUtil.PATTERN_DATETIME )); } @Test public void dateToString() { Date date = new Date(); System.out.println(DateTimeUtil.dateToString(date, DateTimeUtil.PATTERN_DATETIME, DateTimeUtil.ZONEID_CHINA)); } }<file_sep>package com.heyy.study.springbootstudycentral.controller; import com.heyy.study.springbootstudycentral.been.Person; import com.heyy.study.springbootstudycentral.exception.CustomException; import com.heyy.study.springbootstudycentral.exception.ExceptionEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/api/${application.api_version}/heyy") @Slf4j public class CustomerExceptionTestController { @PostMapping(value = "/customer/exception",consumes = "application/json",produces = "application/json") public ResponseEntity requestValid(@RequestBody Person person){ throw new CustomException(ExceptionEnum.SSC_0002,"customer exception test controller"); } } <file_sep># heyy-study-springboot-study springboot releative knowadge for applying; ## project content description ### request body validte,request header validate,request param validate; ### encryUtil.encrypt and encryptUtil.decrypt for sensitive field; ### 限流RateLimiter ### RestTemplate retry ### RestTemplate request factory config ### properties load by inputStream ### @PostConstruct ### customer exception and exception handler ### DatetimeManager ### swagger ### ValidationMessages.properties ### object transform to string ### schedule test in springboot ### request body cache,and we can get request body anywhere ### interceptor <file_sep>package heyy.study.common.constants; /** * @Classname RegExpConstants * @Description TODO * @Date 2019/5/9 20:49 * @Created by Breeze */ public class RegExpConstants { public static final String REGEX_NAME = "([A-Za-z0-9\\u4e00-\\u9fa5]|-){1,}"; } <file_sep>package com.heyy.study.springbootstudycentral.utility; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @Classname KeyUtil * @Description TODO * @Date 2019/5/10 19:18 * @Created by Breeze */ @Component public class KeyUtil { private static String key1; private static String key2; private static String key3; @Value("${heyy.spingboot.study.encrypt.key1}") public static void setKey1(String key1) { KeyUtil.key1 = key1; } @Value("${heyy.spingboot.study.encrypt.key2}") public static void setKey2(String key2) { KeyUtil.key2 = key2; } @Value("${heyy.spingboot.study.encrypt.key3}") public static void setKey3(String key3) { KeyUtil.key3 = key3; } public String getEncryptKey(){ String unEncryptPwd = key1+key2+key3; String encryptedPwd = DigestUtils.md2Hex(unEncryptPwd); return encryptedPwd; } @PostConstruct public void init(){ String encryptedPwd = new KeyUtil().getEncryptKey(); EncryptUtil.init(encryptedPwd); } } <file_sep>package com.heyy.study.springbootstudycentral.utility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.heyy.study.springbootstudycentral.been.DencryptSensitiveDataSerializer; import com.heyy.study.springbootstudycentral.been.EncryptSensitiveDataSerializer; import com.heyy.study.springbootstudycentral.exception.CustomException; import com.heyy.study.springbootstudycentral.exception.ExceptionEnum; import java.util.Objects; /** * @Classname EncryptUtil * @Description TODO * @Date 2019/5/10 13:51 * @Created by Breeze */ public class EncryptUtil { private static String encryptKey; private static AesUtil aesUtil; public static void init(String key){ encryptKey = key; aesUtil = new AesUtil(encryptKey); } public static <T> T encrypt(T obj){ Objects.requireNonNull(obj, "obj must not be null"); return encrypt(obj,ObjectUtil.getType(obj.getClass())); } public static <T,W,I> T encrypt(T obj,Class<W> wClass,Class<I> iClass){ Objects.requireNonNull(obj, "obj must not be null"); return encrypt(obj,ObjectUtil.getParametricType(wClass,iClass)); } public static <T> String encryptToLog(T obj){ return ObjectUtil.objectToJson(encrypt(obj)); } public static <T> T encrypt(T obj,JavaType type){ Objects.requireNonNull(obj, "obj must not be null"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false ); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(String.class,new EncryptSensitiveDataSerializer()); mapper.registerModule(simpleModule); T result = ObjectUtil.jsonToObject(ObjectUtil.objectToJson(obj,mapper),type,mapper ); return result; } public static <T> T dencrypt(T obj){ Objects.requireNonNull(obj, "obj must not be null"); return dencrypt(obj,ObjectUtil.getType(obj.getClass())); } public static <T,W,I> T dencrypt(T obj,Class<W> wClass,Class<I> iClass){ Objects.requireNonNull(obj, "obj must not be null"); return dencrypt(obj,ObjectUtil.getParametricType(wClass,iClass)); } public static <T> T dencrypt(T obj,JavaType type){ Objects.requireNonNull(obj, "obj must not be null"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false ); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule simpleModule = new SimpleModule(); simpleModule.addSerializer(String.class,new DencryptSensitiveDataSerializer()); mapper.registerModule(simpleModule); T result = ObjectUtil.jsonToObject(ObjectUtil.objectToJson(obj,mapper),type,mapper ); return result; } public static String encrypt(String plainText){ try { return aesUtil.encrypt(plainText); } catch (Exception e) { throw new CustomException(ExceptionEnum.SSC_0005,e.getMessage()); } } public static String dencrypt(String encryptedValue){ try { return aesUtil.dencrypt(encryptedValue); } catch (Exception e) { throw new CustomException(ExceptionEnum.SSC_0006,e.getMessage()); } } } <file_sep>package com.heyy.study.springbootstudycentral.config; import com.heyy.study.springbootstudycentral.interceptor.MyInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * @Classname InterceptorConfig * @Description config interceptor * @Date 2019/5/13 20:42 * @Created by Breeze */ @Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter{ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getMyInterceptor()).addPathPatterns("/api/v1/heyy/valid/request"); super.addInterceptors(registry); } @Bean public HandlerInterceptor getMyInterceptor(){ return new MyInterceptor(); } } <file_sep>server.port=8082 application.api_version=v1 <file_sep>package com.heyy.study.springbootstudycentral.been; import com.heyy.study.springbootstudycentral.annotation.SensitiveFieldAnnotation; import com.heyy.study.springbootstudycentral.constants.RegExpConstants; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import javax.validation.Valid; import javax.validation.constraints.*; @Data @AllArgsConstructor @NoArgsConstructor public class Person { @SensitiveFieldAnnotation @NotBlank(message = "{name.not.blank}") @Pattern(regexp = RegExpConstants.REGEX_NAME) private String name; /** * idType = 1 idCard * idType = 0 temporary idCard */ @NotBlank(message = "{idType.not.blank}") @Pattern(regexp = RegExpConstants.REGEX_ID_TYPE,message = "{idType.format.wrong}") private String idType; @SensitiveFieldAnnotation @NotBlank(message = "{idNo.not.blank}") private String idNo; @NotNull @Min(value = 18,message = "age should not less than 18") private int age; private String sex; @Email private String email; @NotNull(message = "address should not be null") @Valid private Address address; @Override public String toString() { return ToStringBuilder.reflectionToString(this,ToStringStyle.JSON_STYLE); } } <file_sep>package com.heyy.study.springbootstudycentral.exception; import com.heyy.study.springbootstudycentral.constants.CommonConstants; import heyy.study.common.been.ErrorDetails; import heyy.study.common.utility.SysDateManager; import org.apache.commons.codec.binary.Base64; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.util.ContentCachingRequestWrapper; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * @Classname CustomizedErrorHandler * @Description TODO * @Date 2019/5/9 13:45 * @Created by Breeze */ @ControllerAdvice public class CustomizedErrorHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public final ResponseEntity<ErrorDetails> handleMethodArgumentNotValidException (MethodArgumentNotValidException ex){ BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); String errorDetails = fieldErrors.get(0).getDefaultMessage(); String responseCode = CommonConstants.NEGATIVE_RESPONSE_CODE; String errorCode = ExceptionEnum.SSC_0001.getErrorCode(); MultiValueMap<String, String> headers = getExceptionResponseHeaders(responseCode,errorCode); ErrorDetails responseBody = new ErrorDetails(SysDateManager.getCurrentTime(),errorDetails,""); return new ResponseEntity<>(responseBody, headers, HttpStatus.OK); } @ExceptionHandler(CustomException.class) public final ResponseEntity<ErrorDetails> handleCustomException (CustomException ex, HttpServletRequest httpServletRequest){ String errorCode = ex.getExceptionEnum().getErrorCode(); String responseCode = CommonConstants.NEGATIVE_RESPONSE_CODE; MultiValueMap<String, String> headers = getExceptionResponseHeaders(responseCode,errorCode); String requestBodyValue = getRequestBody(httpServletRequest); ErrorDetails responseBody = new ErrorDetails(SysDateManager.getCurrentTime(),ex.getMessage(),requestBodyValue); return new ResponseEntity<>(responseBody, headers, HttpStatus.OK); } private MultiValueMap<String, String> getExceptionResponseHeaders(String responseCode,String errorCode){ MultiValueMap<String, String> headers = new LinkedMultiValueMap<String,String>(); headers.set("responseCode",responseCode); headers.set("errorCode",errorCode); return headers; } public String getRequestBody(HttpServletRequest httpServletRequest){ if(ContentCachingRequestWrapper.class.isAssignableFrom(httpServletRequest.getClass())){ ContentCachingRequestWrapper contentCachingRequestWrapper = (ContentCachingRequestWrapper)httpServletRequest; String body = Base64.encodeBase64String(contentCachingRequestWrapper.getContentAsByteArray()); return body; } return ""; } }
9a2cebe2db6872b44db859f016f8de99c1a5b7d4
[ "Markdown", "Java", "INI" ]
25
Java
1091524653/heyy-study-springboot-study
40bbc9560e2c17df5c4060611f1c493e3bb46c8d
15efc2bf2a01cdf1c8db7fefe0dfe9d1443d420c
refs/heads/master
<repo_name>JasonMacKeigan/adventofcode-2019<file_sep>/src/main/java/adventofcode/day/impl/day_six/DaySix.java package adventofcode.day.impl.day_six; import adventofcode.day.Day; import adventofcode.day.DayUtils; import org.apache.commons.lang3.builder.ToStringStyle; /** * Created by <NAME> on 2019-12-12 at 11:08 p.m. */ public class DaySix implements Day<Integer, Integer> { public static void main(String[] args) { DaySix daySix = new DaySix(); daySix.print(ToStringStyle.JSON_STYLE); } @Override public Integer partOneAnswer() { OrbitMap orbitMap = OrbitMap.valueOf(DayUtils.lines("day/day6.txt")); return orbitMap.getAllIndirect() + orbitMap.getAllDirect(); } @Override public Integer partTwoAnswer() { OrbitMap orbitMap = OrbitMap.valueOf(DayUtils.lines("day/day6.txt")); Orbit santa = orbitMap.get("SAN"); Orbit you = orbitMap.get("YOU"); return orbitMap.getMinimumTransfers(santa, you); } } <file_sep>/src/main/java/adventofcode/day/impl/DayFour.java package adventofcode.day.impl; import adventofcode.day.Day; import org.apache.commons.lang3.builder.ToStringStyle; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Created by <NAME> on 2019-12-04 at 10:07 p.m. */ public class DayFour implements Day<Integer, Integer> { public static void main(String[] args) { DayFour dayFour = new DayFour(); dayFour.print(ToStringStyle.JSON_STYLE); } public static List<PasswordCriteria> createPartOneCriteria(int minInclusive, int maxInclusive) { return Arrays.asList( new AdjacentNumberPasswordCriteria(), new NeverDecreasePasswordCriteria(), new SixDigitPasswordCriteria(), new WithinRangePasswordCriteria(minInclusive, maxInclusive)); } public static List<PasswordCriteria> createPartTwoCriteria(int minInclusive, int maxInclusive) { return Arrays.asList( new NoLargeGroupPasswordCriteria(), new NeverDecreasePasswordCriteria(), new SixDigitPasswordCriteria(), new WithinRangePasswordCriteria(minInclusive, maxInclusive)); } @Override public Integer partOneAnswer() { int min = 353096; int max = 843212; return new PasswordFinder(min, max, createPartOneCriteria(min, max)).eligible(); } @Override public Integer partTwoAnswer() { int min = 353096; int max = 843212; return new PasswordFinder(min, max, createPartTwoCriteria(min, max)).eligible(); } public static class PasswordFinder { private final int minimumInclusive; private final int maximumInclusive; private final List<PasswordCriteria> criteria; public PasswordFinder(int minimumInclusive, int maximumInclusive, List<PasswordCriteria> criteria) { this.minimumInclusive = minimumInclusive; this.maximumInclusive = maximumInclusive; this.criteria = criteria; } public int eligible() { return (int) IntStream.range(minimumInclusive, maximumInclusive + 1) .filter(number -> criteria.stream().allMatch(criteria -> criteria.acceptable(number))).count(); } } public interface PasswordCriteria { boolean acceptable(int password); } public static class NoLargeGroupPasswordCriteria implements PasswordCriteria { @Override public boolean acceptable(int password) { List<Integer> digits = Integer.toString(password).chars().boxed().collect(Collectors.toList()); int singlePairs = 0; for (int index = 0; index < digits.size() - 1; index++) { int digit = digits.get(index); int digitAtNext = digits.get(index + 1); if (digit != digitAtNext) { continue; } if (index < digits.size() - 2) { int digitAfterNext = digits.get(index + 2); if (digitAfterNext == digitAtNext) { continue; } } if (index > 0) { int digitAtPrevious = digits.get(index - 1); if (digitAtPrevious == digit) { continue; } } singlePairs++; } return singlePairs > 0; } } public static class SixDigitPasswordCriteria implements PasswordCriteria { private static final int LOWER_BOUND = 99_999; private static final int UPPER_BOUND = 999_999; @Override public boolean acceptable(int password) { return password > LOWER_BOUND && password < UPPER_BOUND; } } public static class WithinRangePasswordCriteria implements PasswordCriteria { private final int minimumInclusive; private final int maximumInclusive; public WithinRangePasswordCriteria(int minimumInclusive, int maximumInclusive) { this.minimumInclusive = minimumInclusive; this.maximumInclusive = maximumInclusive; } @Override public boolean acceptable(int password) { return password >= minimumInclusive && password <= maximumInclusive; } } public static class AdjacentNumberPasswordCriteria implements PasswordCriteria { @Override public boolean acceptable(int password) { List<Integer> digits = Integer.toString(password).chars().boxed().collect(Collectors.toList()); for (int index = 0; index < digits.size(); index++) { int digit = digits.get(index); if (index + 1 > digits.size() - 1) { break; } int nextDigit = digits.get(index + 1); if (digit == nextDigit) { return true; } } return false; } } public static class NeverDecreasePasswordCriteria implements PasswordCriteria { @Override public boolean acceptable(int password) { List<Integer> digits = Integer.toString(password).chars().boxed().collect(Collectors.toList()); if (digits.isEmpty()) { throw new IllegalStateException("Password is unacceptable, there are no digits."); } for (int index = 0; index < digits.size() - 1; index++) { int digit = digits.get(index); if (index + 1 > digits.size() - 1) { break; } int nextDigit = digits.get(index + 1); if (nextDigit < digit) { return false; } } return true; } } } <file_sep>/src/main/java/adventofcode/day/intcode/opcode/amplifier/AmplifierInputOpcode.java package adventofcode.day.intcode.opcode.amplifier; import adventofcode.day.intcode.IntcodeComputer; import adventofcode.day.intcode.Parameter; import adventofcode.day.intcode.opcode.InputOpcode; /** * Created by <NAME> on 2019-12-14 at 2:00 p.m. */ public class AmplifierInputOpcode extends InputOpcode { @Override public void execute(IntcodeComputer computer, Parameter... parameters) { computer.set(parameters[0].getValue(), computer.getInput()); } } <file_sep>/src/main/java/adventofcode/day/impl/day_six/Orbit.java package adventofcode.day.impl.day_six; import java.util.HashSet; import java.util.Objects; import java.util.Set; /** * Created by <NAME> on 2019-12-12 at 11:10 p.m. */ public class Orbit { private final String identifier; private Orbit direct; private final int hashCode; public Orbit(String identifier, Orbit direct) { this.identifier = identifier; this.direct = direct; this.hashCode = Objects.hash(identifier); } public Orbit(String identifier) { this(identifier, null); } public int direct() { return direct == null ? 0 : 1; } public int indirect() { int orbiting = orbiting(); if (orbiting == 0) { return 0; } return orbiting - 1; } public int orbiting() { int indirect = direct == null ? 0 : 1; if (direct != null) { indirect += direct.orbiting(); } return indirect; } public Orbit getDirectOrbit() { return direct; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof Orbit) { Orbit orbit = (Orbit) other; return identifier.equals(orbit.identifier); } return false; } public void setDirect(Orbit direct) { this.direct = direct; } } <file_sep>/src/test/java/adventofcode/day/impl/DayFourTest.java package adventofcode.day.impl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Created by <NAME> on 2019-12-04 at 10:25 p.m. */ @RunWith(JUnit4.class) public class DayFourTest { @Test public void assertPartOne() { DayFour.PasswordFinder correct = new DayFour.PasswordFinder(111111, 111111, DayFour.createPartOneCriteria(111111, 111111)); DayFour.PasswordFinder firstIncorrect = new DayFour.PasswordFinder(223450, 223450, DayFour.createPartOneCriteria(223450, 223450)); DayFour.PasswordFinder secondIncorrect = new DayFour.PasswordFinder(123789, 123789, DayFour.createPartOneCriteria(123789, 123789)); Assert.assertEquals(1, correct.eligible()); Assert.assertEquals(0, firstIncorrect.eligible()); Assert.assertEquals(0, secondIncorrect.eligible()); } @Test public void assertPartTwo() { DayFour.PasswordFinder correct = new DayFour.PasswordFinder(112233, 112233, DayFour.createPartTwoCriteria(112233, 112233)); DayFour.PasswordFinder firstIncorrect = new DayFour.PasswordFinder(123444, 123444, DayFour.createPartTwoCriteria(123444, 123444)); DayFour.PasswordFinder secondIncorrect = new DayFour.PasswordFinder(111122, 111122, DayFour.createPartTwoCriteria(111122, 111122)); Assert.assertEquals(1, correct.eligible()); Assert.assertEquals(0, firstIncorrect.eligible()); Assert.assertEquals(1, secondIncorrect.eligible()); } @Test public void assertPartOneAnswer() { DayFour.PasswordFinder passwordFinder = new DayFour.PasswordFinder(353096, 843212, DayFour.createPartOneCriteria(353096, 843212)); Assert.assertEquals(579, passwordFinder.eligible()); } } <file_sep>/src/main/java/adventofcode/day/intcode/opcode/JumpIfTrueOpcode.java package adventofcode.day.intcode.opcode; import adventofcode.day.intcode.IntcodeComputer; import adventofcode.day.intcode.Opcode; import adventofcode.day.intcode.Parameter; /** * Created by <NAME> on 2019-12-11 at 11:42 a.m. */ public class JumpIfTrueOpcode implements Opcode { @Override public int id() { return 5; } @Override public void execute(IntcodeComputer computer, Parameter... parameters) { int value = computer.readParameter(parameters[0]); if (value != 0) { int position = computer.readParameter(parameters[1]); computer.setPosition(position); } } @Override public int parameters() { return 2; } } <file_sep>/src/main/java/adventofcode/day/intcode/FeedbackLoopMode.java package adventofcode.day.intcode; /** * Created by <NAME> on 2019-12-14 at 8:50 p.m. */ public enum FeedbackLoopMode { DISABLED(0, 5), ENABLED(5, 10); private final int minPhaseInclusive; private final int maxPhaseExclusive; FeedbackLoopMode(int minPhaseInclusive, int maxPhaseExclusive) { this.minPhaseInclusive = minPhaseInclusive; this.maxPhaseExclusive = maxPhaseExclusive; } public int getMinPhaseInclusive() { return minPhaseInclusive; } public int getMaxPhaseExclusive() { return maxPhaseExclusive; } } <file_sep>/src/main/java/adventofcode/day/intcode/AmplifierSeries.java package adventofcode.day.intcode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * Created by <NAME> on 2019-12-14 at 10:43 a.m. */ public class AmplifierSeries { private final List<Integer> memory; private final FeedbackLoopMode loopMode; public AmplifierSeries(List<Integer> memory, FeedbackLoopMode loopMode) { this.memory = memory; this.loopMode = loopMode; } public AmplifierCombination max() { AmplifierCombination max = null; for (int first = loopMode.getMinPhaseInclusive(); first < loopMode.getMaxPhaseExclusive(); first++) { for (int second = loopMode.getMinPhaseInclusive(); second < loopMode.getMaxPhaseExclusive(); second++) { for (int third = loopMode.getMinPhaseInclusive(); third < loopMode.getMaxPhaseExclusive(); third++) { for (int fourth = loopMode.getMinPhaseInclusive(); fourth < loopMode.getMaxPhaseExclusive(); fourth++) { for (int fifth = loopMode.getMinPhaseInclusive(); fifth < loopMode.getMaxPhaseExclusive(); fifth++) { if (Stream.of(first, second, third, fourth, fifth).distinct().count() < 5) { continue; } Amplifier secondAmplifier = new Amplifier(new AmplifierIntcodeComputer(new ArrayList<>(memory), Opcodes.getDaySeven(), firstAmplifier.outputSignal(), second)); secondAmplifier.read(); Amplifier thirdAmplifier = new Amplifier(new AmplifierIntcodeComputer(new ArrayList<>(memory), Opcodes.getDaySeven(), secondAmplifier.outputSignal(), third)); thirdAmplifier.read(); Amplifier fourthAmplifier = new Amplifier(new AmplifierIntcodeComputer(new ArrayList<>(memory), Opcodes.getDaySeven(), thirdAmplifier.outputSignal(), fourth)); fourthAmplifier.read(); Amplifier fifthAmplifier = new Amplifier(new AmplifierIntcodeComputer(new ArrayList<>(memory), Opcodes.getDaySeven(), fourthAmplifier.outputSignal(), fifth)); fifthAmplifier.read(); if (loopMode == FeedbackLoopMode.ENABLED) { } int signal = fifthAmplifier.outputSignal(); if (max == null || signal > max.getSignal()) { max = new AmplifierCombination(Arrays.asList(first, second, third, fourth, fifth), signal); } } } } } } return max; } private int amplify() { } private int amplify(int input, int phase) { Amplifier amplifier = new Amplifier(new AmplifierIntcodeComputer(memory, Opcodes.getDaySeven(), input, phase)); amplifier.read(); return amplifier.outputSignal(); } } <file_sep>/src/main/java/adventofcode/day/intcode/opcode/InputOpcode.java package adventofcode.day.intcode.opcode; import adventofcode.day.intcode.IntcodeComputer; import adventofcode.day.intcode.Opcode; import adventofcode.day.intcode.Parameter; /** * Created by <NAME> on 2019-12-11 at 9:13 a.m. */ public class InputOpcode implements Opcode { @Override public int id() { return 3; } @Override public void execute(IntcodeComputer computer, Parameter... parameters) { computer.set(parameters[0].getValue(), computer.getInput()); } @Override public int parameters() { return 1; } } <file_sep>/src/main/java/adventofcode/day/impl/DayOne.java package adventofcode.day.impl; import adventofcode.day.Day; import adventofcode.day.DayUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * Created by <NAME> on 2019-12-01 at 4:05 p.m. */ public class DayOne implements Day<Integer, Integer> { private final List<Module> modules; public static void main(String[] args) { List<Module> modules = DayUtils.lines("day/1.txt").stream().mapToInt(Integer::parseInt).mapToObj(Module::new).collect(Collectors.toList()); DayOne dayOne = new DayOne(modules); System.out.println("part 1: " + dayOne.partOneAnswer()); System.out.println("part 2: " + dayOne.partTwoAnswer()); } public DayOne(Module... module) { this(Arrays.asList(module)); } public DayOne(List<Module> modules) { this.modules = modules; } @Override public Integer partOneAnswer() { return modules.stream().mapToInt(Module::getFuelRequired).sum(); } @Override public Integer partTwoAnswer() { return modules.stream().mapToInt(module -> partTwoFuel(module, 0)).sum(); } private int partTwoFuel(Module module, int totalFuel) { int fuelRequired = module.getFuelRequired(); if (fuelRequired <= 0) { return totalFuel; } totalFuel += fuelRequired; return partTwoFuel(new Module(fuelRequired), totalFuel); } public static class Module { private final int mass; private final int fuelRequired; public Module(int mass) { this.mass = mass; this.fuelRequired = Math.floorDiv(mass, 3) - 2; } public int getMass() { return mass; } public int getFuelRequired() { return fuelRequired; } } } <file_sep>/src/main/java/adventofcode/day/intcode/Amplifier.java package adventofcode.day.intcode; import org.checkerframework.checker.units.qual.A; /** * Created by <NAME> on 2019-12-14 at 10:36 a.m. */ public class Amplifier { private final AmplifierIntcodeComputer intcodeComputer; public Amplifier(AmplifierIntcodeComputer intcodeComputer) { this.intcodeComputer = intcodeComputer; } public void read() { intcodeComputer.read(); } public int outputSignal() { return intcodeComputer.getDiagnostic(); } } <file_sep>/src/main/java/adventofcode/day/impl/DayThree.java package adventofcode.day.impl; import adventofcode.day.Day; import adventofcode.day.DayUtils; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Created by <NAME> on 2019-12-03 at 1:55 p.m. */ public class DayThree implements Day<Integer, Integer> { public static void main(String[] args) { DayThree dayThree = new DayThree(); System.out.println("part one: " + dayThree.partOneAnswer()); System.out.println("part two: " + dayThree.partTwoAnswer()); } @Override public Integer partOneAnswer() { List<String> lines = DayUtils.lines("day/3.txt"); String first = lines.get(0); String second = lines.get(1); Wire centralPort = new Wire(0, 0); Grid firstGrid = Grid.valueOfStepped(first, centralPort); Grid secondGrid = Grid.valueOfStepped(second, centralPort); Heuristic heuristic = new ManhattanHeuristic(); GridIntersection gridIntersection = new GridIntersection(firstGrid, secondGrid, heuristic); Wire maxPointFromStart = gridIntersection.minFromStart(); if (maxPointFromStart == null) { throw new IllegalStateException("No point can be found that intersects on both grids."); } return heuristic.distance(centralPort, maxPointFromStart); } @Override public Integer partTwoAnswer() { List<String> lines = DayUtils.lines("day/3.txt"); String first = lines.get(0); String second = lines.get(1); Wire centralPort = new Wire(0, 0); Grid firstGrid = Grid.valueOfStepped(first, centralPort); Grid secondGrid = Grid.valueOfStepped(second, centralPort); Heuristic heuristic = new ManhattanHeuristic(); GridIntersection gridIntersection = new GridIntersection(firstGrid, secondGrid, heuristic); return gridIntersection.fewestStepsForIntersection(); } public static class Wire { private final int x; private final int y; private final int hashCode; public Wire(int x, int y) { this.x = x; this.y = y; this.hashCode = Objects.hash(x, y); } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof Wire) { Wire other = (Wire) object; return other.x == x && other.y == y; } return false; } } public static class Step { private final Direction direction; private final int amount; public Step(Direction direction, int amount) { this.direction = direction; this.amount = amount; } } public static class GridIntersection { private final Grid first; private final Grid second; private final Heuristic heuristic; public GridIntersection(Grid first, Grid second, Heuristic heuristic) { this.first = first; this.second = second; this.heuristic = heuristic; } public List<Wire> intersections() { List<Wire> intersections = new ArrayList<>(); for (Map.Entry<Wire, Integer> entry : first.marked.entrySet()) { Wire firstWire = entry.getKey(); if (!second.marked.containsKey(firstWire)) { continue; } intersections.add(firstWire); } return intersections; } public int fewestStepsForIntersection() { return intersections().stream().mapToInt((wire -> first.marked.getOrDefault(wire, 0) + second.marked.getOrDefault(wire, 0))).min().orElseThrow(IllegalStateException::new); } public Wire minFromStart() { return intersections().stream().min(Comparator.comparingInt(point -> heuristic.distance(point, first.centralPort))).orElse(null); } } public static class ManhattanHeuristic implements Heuristic { @Override public int distance(Wire first, Wire second) { return Math.abs(first.x - second.x) + Math.abs(first.y - second.y); } } public interface Heuristic { int distance(Wire first, Wire second); } public enum Direction { U(0, 1), R(1, 0), D(0, -1), L(-1, 0); private final int xOffset; private final int yOffset; Direction(int xOffset, int yOffset) { this.xOffset = xOffset; this.yOffset = yOffset; } } public static class Grid { private final Map<Wire, Integer> marked = new HashMap<>(); private final Wire centralPort; private Wire marker; private int steps; public Grid(Wire centralPort) { this.centralPort = centralPort; this.marker = centralPort; } public static Grid valueOfStepped(String input, Wire centralPort) { String[] values = input.split(","); List<Step> steps = Stream.of(values).map(value -> new Step( Direction.valueOf(value.substring(0, 1)), Integer.parseInt(value.substring(1))) ).collect(Collectors.toList()); Grid grid = new Grid(centralPort); steps.forEach(grid::walk); return grid; } public void walk(Step... steps) { Stream.of(steps).forEach(this::walk); } public void walk(Step step) { for (int index = 0; index < step.amount; index++) { if (step.direction == Direction.U) { marker = new Wire(marker.x, marker.y + step.direction.yOffset); } else if (step.direction == Direction.D) { marker = new Wire(marker.x, marker.y + step.direction.yOffset); } else if (step.direction == Direction.R) { marker = new Wire(marker.x + step.direction.xOffset, marker.y); } else if (step.direction == Direction.L) { marker = new Wire(marker.x + step.direction.xOffset, marker.y); } marked.put(marker, ++steps); } } } } <file_sep>/README.MD # Advent of Code 2019 A collection of solutions for the challenges presented by the [Advent of Code][aoc_website]. ## Solutions * [Day 1](src/main/java/adventofcode/day/impl/DayOne.java) [(Unit Test)](src/test/java/adventofcode/day/impl/DayOneTest.java) * [Day 2](src/main/java/adventofcode/day/impl/DayTwo.java) [(Unit Test)](src/test/java/adventofcode/day/impl/DayTwoTest.java) * [Day 3](src/main/java/adventofcode/day/impl/DayThree.java) [(Unit Test)](src/test/java/adventofcode/day/impl/DayThreeTest.java) * [Day 4](src/main/java/adventofcode/day/impl/DayFour.java) [(Unit Test)](src/test/java/adventofcode/day/impl/DayFourTest.java) * [Day 5](src/main/java/adventofcode/day/impl/DayFive.java) [(Unit Test)](src/test/java/adventofcode/day/impl/DayFiveTest.java) [aoc_website]: [https://adventofcode.com/] <file_sep>/src/main/java/adventofcode/day/impl/DayTwo.java package adventofcode.day.impl; import adventofcode.day.Day; import adventofcode.day.DayUtils; import java.util.*; import java.util.function.IntBinaryOperator; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Created by <NAME> on 2019-12-02 at 1:28 p.m. */ public class DayTwo implements Day<Integer, Integer> { private final List<Integer> values; public DayTwo(List<Integer> values) { this.values = values; } public static void main(String[] args) { String line = DayUtils.lines("day/2.txt").get(0); String[] values = line.split(","); List<Integer> integerValues = Stream.of(values).mapToInt(Integer::parseInt).boxed().collect(Collectors.toList()); DayTwo dayTwo = new DayTwo(integerValues); System.out.println("first answer: " + dayTwo.partOneAnswer()); System.out.println("second answer: " + dayTwo.partTwoAnswer()); } public static class Result { private final int noun; private final int verb; public Result(int noun, int verb) { this.noun = noun; this.verb = verb; } public int getNoun() { return noun; } public int getVerb() { return verb; } } private Result findNounAndVerbForValue(int value, int rangeInclusive) { for (int noun = 0; noun < rangeInclusive; noun++) { for (int verb = 0; verb < rangeInclusive; verb++) { int valueAtIndex = valueAtIndex(0, noun, verb); if (valueAtIndex == value) { return new Result(noun, verb); } } } throw new IllegalArgumentException("No noun and verb combination can be found for this value."); } private Integer valueAtIndex(int index, int noun, int verb) { List<Integer> values = new ArrayList<>(this.values); values.set(1, noun); values.set(2, verb); IntcodeProgramReader reader = new IntcodeProgramReader(); IntcodeProgram program = new IntcodeProgram(values); List<Integer> results = reader.results(program); return results.get(index); } @Override public Integer partOneAnswer() { List<Integer> values = new ArrayList<>(this.values); values.set(1, 12); values.set(2, 2); IntcodeProgramReader reader = new IntcodeProgramReader(); IntcodeProgram program = new IntcodeProgram(values); List<Integer> results = reader.results(program); return results.get(0); } @Override public Integer partTwoAnswer() { Result result = findNounAndVerbForValue(19690720, 99); return 100 * result.noun + result.verb; } public enum Opcode { ONE(1, Integer::sum), TWO(2, (first, second) -> first * second), THREE(3, (first, second) -> { return first; }), NINETY_NINE(99, null); private final int id; private final IntBinaryOperator function; //TODO replace with ImmutableSet since this is not immutable private static final Map<Integer, Opcode> OPCODE_BY_ID = EnumSet.allOf(Opcode.class).stream().collect(Collectors.toMap(e -> e.id, e -> e)); Opcode(int id, IntBinaryOperator function) { this.id = id; this.function = function; } public static Opcode valueOf(int id) { return OPCODE_BY_ID.get(id); } public IntBinaryOperator getFunction() { return function; } } public static class IntcodeProgramReader { List<Integer> results(IntcodeProgram program) { List<Integer> values = new ArrayList<>(program.values); for (int index = 0; index < values.size();) { int opcodeId = values.get(index); Opcode opcode = Opcode.valueOf(opcodeId); if (opcode == null) { throw new IllegalStateException(String.format("No opcode exist for the following id: %s", opcodeId)); } if (opcode == Opcode.NINETY_NINE) { break; } int indexOfFirst = values.get(index + 1); int indexOfSecond = values.get(index + 2); int updateIndex = values.get(index + 3); Integer valueAtFirst = values.get(indexOfFirst); Integer valueOfSecond = values.get(indexOfSecond); values.set(updateIndex, opcode.function.applyAsInt(valueAtFirst, valueOfSecond)); index += 4; } return values; } } public static class IntcodeProgram { private final List<Integer> values; public IntcodeProgram(List<Integer> values) { this.values = values; } public List<Integer> getValues() { return values; } } }
1a221086ac212d0ae05fd8eed3103778517068bd
[ "Markdown", "Java" ]
14
Java
JasonMacKeigan/adventofcode-2019
ad5b5a7969bb71a740c4b4cb6b705524e1d39e56
79cb5370eb261b4bc1ddbbf6df2de59bc537032b
refs/heads/master
<repo_name>Pidly/Praktis<file_sep>/src/Game/Combat.java package Game; /** * Created with IntelliJ IDEA. * User: devinsmythe * Date: 10/19/14 * Time: 5:08 PM * To change this template use File | Settings | File Templates. */ public interface Combat { public void takeDamage(int damage); public int dealDamage(); } <file_sep>/src/Characters/Character.java package Characters; import Game.BattleItems.StatusEffect; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public abstract class Character { protected int hp; protected int mp; protected boolean enemy = true; protected int str; protected int spirit; protected int currentHp; protected int x, y; protected int width, height; protected int currentClassResource = 0; protected int maxClassResource = 100; protected List<Ability> abilities = new ArrayList<Ability>(); String name; public Stats stats; private List<StatusEffect> statusEffects; public Character(int x, int y, int width, int height){ this.x = x; this.y = y; this.width = width; this.height = height; statusEffects = new ArrayList<StatusEffect>(); } public int getHp(){ return currentHp; } public int getMaxHp(){return hp;} abstract public void draw(); abstract public void update(); abstract public void takeDamage(int damage); public void updateStatusEffect(){ Iterator<StatusEffect> statusIterator = statusEffects.iterator(); while(statusIterator.hasNext()){ StatusEffect statusEffect = statusIterator.next(); if(statusEffect.ready()){ statusEffect.update(this); } if(statusEffect.finished()) statusIterator.remove(); } } public List<StatusEffect> getStatusEffects(){ return statusEffects; } public void addStatusEffect(StatusEffect statusEffect){ statusEffects.add(statusEffect); } public void resetTimer(){ stats.resetProgressBar(); } public List<Ability> getAbilities(){ return abilities; } public void healDamage(int healAmount){ currentHp += healAmount; if(currentHp > hp) currentHp = hp; } public boolean ready(){ return stats.ready; } public void increaseCurrentResourceBy(int amount){ currentClassResource += amount; if(currentClassResource > maxClassResource) currentClassResource = maxClassResource; stats.setCurrentResourceProgressX(currentClassResource); } public int getMaxClassResource(){ return maxClassResource; } public int getCurrentClassResource(){return currentClassResource;} public int getX(){ return x; } public int getY(){ return y; } public int getWidth(){ return width; } public int getHeight(){ return height; } public boolean isEnemy(){ return enemy; } } <file_sep>/src/Characters/Player.java package Characters; import Game.Combat; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: devinsmythe * Date: 10/11/14 * Time: 2:54 PM * To change this template use File | Settings | File Templates. */ public abstract class Player extends Character implements Combat { public static boolean activePlayer = false; private boolean selected = false; public Player(int x, int y, int width, int height) { super(x, y, width, height); enemy = false; } @Override public void takeDamage(int damage) { currentHp -= damage; if(currentHp < 0){ currentHp = 0; } } public boolean isSelected(){ return selected; } public void setSelected(boolean selected){ this.selected = selected; } @Override public int dealDamage() { return str; } public void checkIfSelected(){ if(ready()){ if(!Player.activePlayer){ activePlayer = true; setSelected(true); } } } } <file_sep>/src/Game/Input.java package Game; import org.lwjgl.input.Keyboard; import java.security.Key; import java.util.HashMap; import java.util.Map; public class Input { private static boolean exitGame = false; int rightAbility = Keyboard.KEY_B; public static synchronized boolean getExitState(){ return exitGame; } public static synchronized void setExitState(boolean exit){ exitGame = exit; } public static void getInput(InputHandler inputHandler){ while(Keyboard.next()){ if(Keyboard.getEventKeyState()){ if(Keyboard.getEventKey() == Keyboard.KEY_A){ //Maybe add stuff here later. } }else{ int keyCode = Keyboard.getEventKey(); if(keyCode == Keyboard.KEY_A || keyCode == Keyboard.KEY_W){ inputHandler.confirm(keyCode); } else if(Keyboard.getEventKey() == Keyboard.KEY_B) { setExitState(true); } else if(Keyboard.getEventKey() == Keyboard.KEY_DOWN){ inputHandler.down(); } else if(Keyboard.getEventKey() == Keyboard.KEY_UP){ inputHandler.up(); } } } /* if(Keyboard.isKeyDown(Keyboard.KEY_A)){ inputHandler.confirm(); } */ } } <file_sep>/src/Characters/AttackAbility.java package Characters; import java.util.List; /** * Created with IntelliJ IDEA. * User: devinsmythe * Date: 10/28/14 * Time: 5:47 PM * To change this template use File | Settings | File Templates. */ public class AttackAbility extends Ability { @Override public void useAbility(List<? extends Character> targets) { targets.get(0).takeDamage(5); } @Override public boolean offensiveMove() { return true; //To change body of implemented methods use File | Settings | File Templates. } @Override public int numberOfHits() { return 1; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean allTargets() { return false; //To change body of implemented methods use File | Settings | File Templates. } } <file_sep>/src/Game/Main.java package Game; import Characters.Caster.Caster; import Characters.Enemy; import Characters.Healer.Healer; import Characters.Player; import Characters.Warrior.Warrior; import Game.BattleItems.Battle; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.newdawn.slick.*; import Display.ScreenDisplay; import Display.BattleDisplay; import java.awt.Font; import java.util.ArrayList; import java.util.List; public class Main { public final static int FRAME_RATE = 17; int x = 300; int y = 0; int width = 200; private boolean antiAlias = true; Font font = new Font("Times New Roman", Font.BOLD, 24); private TrueTypeFont ttFont; Main(){ } public void start(){ ScreenDisplay screenDisplay = null; try { screenDisplay = new ScreenDisplay(); Display.setDisplayMode(screenDisplay.getDisplayMode()); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); System.exit(0); } BattleDisplay battleDisplay = screenDisplay.getBattleDisplay(); int pX = battleDisplay.px; int pY = battleDisplay.py; int pW = ScreenDisplay.tileSize; int pH = ScreenDisplay.tileSize; Warrior warrior = new Warrior(pX, pY, pW, pH); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glShadeModel(GL11.GL_SMOOTH); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_LIGHTING); GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); GL11.glClearDepth(1); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glViewport(0, 0, screenDisplay.screenWidth, screenDisplay.screenHeight); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0, screenDisplay.screenWidth, screenDisplay.screenHeight, 0, 1, -1); GL11.glMatrixMode(GL11.GL_MODELVIEW); ttFont = new TrueTypeFont(font, antiAlias); // init openGL here List<Player> players = new ArrayList<Player>(); List<Enemy> enemies = new ArrayList<Enemy>(); Healer healer = new Healer(battleDisplay.p2x, battleDisplay.p2y, ScreenDisplay.tileSize, ScreenDisplay.tileSize); Caster caster = new Caster(battleDisplay.p3x, battleDisplay.p3y, ScreenDisplay.tileSize, ScreenDisplay.tileSize); //players.add(warrior); //players.add(healer); //players.add(caster); players.add(caster); players.add(healer); players.add(warrior); Enemy enemy = new Enemy(ScreenDisplay.tileSize + battleDisplay.getLeftDisplay(), ScreenDisplay.tileSize*2 + battleDisplay.getBottomDisplay(), ScreenDisplay.tileSize, ScreenDisplay.tileSize, players); Enemy enemy2 = new Enemy(ScreenDisplay.tileSize + battleDisplay.getLeftDisplay(), ScreenDisplay.tileSize*4 + battleDisplay.getBottomDisplay(), ScreenDisplay.tileSize, ScreenDisplay.tileSize, players); enemies.add(enemy); enemies.add(enemy2); Battle battle = new Battle(players, enemies, healer, battleDisplay); while(!Display.isCloseRequested() && !Input.getExitState()){ long currentMillis = System.currentTimeMillis(); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); GL11.glDisable(GL11.GL_TEXTURE_2D); battle.draw(); for(Enemy enemy1 : enemies){ enemy1.draw(); enemy1.update(); enemy1.updateStatusEffect(); } for(Player player1 : players){ player1.draw(); player1.update(); player1.updateStatusEffect(); } Input.getInput(battle); Display.update(); try { Thread.sleep(getLoopSleeptime(currentMillis)); } catch (InterruptedException e) { e.printStackTrace(); } } Display.destroy(); } private long getLoopSleeptime(long milliseconds){ long millis = System.currentTimeMillis(); millis = millis - milliseconds; millis = FRAME_RATE - millis; if(millis < 0) millis = 0; return millis; } public static void main(String args[]){ Main main = new Main(); main.start(); } } <file_sep>/src/Game/InputHandler.java package Game; /** * Created with IntelliJ IDEA. * User: devinsmythe * Date: 10/18/14 * Time: 5:32 PM * To change this template use File | Settings | File Templates. */ public interface InputHandler { public void up(); public void down(); public void left(); public void right(); public void confirm(int keyCode); public void cancel(); } <file_sep>/src/Characters/Warrior/Warrior.java package Characters.Warrior; import Characters.*; import Characters.Character; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; public class Warrior extends Player { private boolean selected = false; AttackAbility attackAbility; WarriorPrimaryAbility primaryAbility; public Warrior(int x, int y, int width, int height){ super(x, y, width, height); //attackAbility = new AttackAbility(); primaryAbility = new WarriorPrimaryAbility(this); abilities.add(primaryAbility); abilities.add(new AttackAbility()); maxClassResource = 100; currentClassResource = 10; str = 20; spirit = 10; this.currentHp = 40; hp = 50; mp = 20; stats = new Stats(hp, mp, width, height, this.x, this.y, this.currentHp, maxClassResource, currentClassResource); } @Override public void draw() { GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(0.2f, 0.5f, 1.0f, 1.0f); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(x, y); GL11.glVertex2f(x+width, y); GL11.glVertex2f(x+width, y - height); GL11.glVertex2f(x, y - height); GL11.glEnd(); stats.draw(); } @Override public void update() { if(this.currentHp < 0) this.currentHp = 0; stats.upDate(0.01f, this.currentHp); checkIfSelected(); } }
d20049b52268bab6139f936d2bff619d623085bf
[ "Java" ]
8
Java
Pidly/Praktis
d5dd11c4af78aefdf89628b90d661028e0266d29
aef270fcbf9b9af516d517ddfa63b73a38c56972
refs/heads/master
<repo_name>debbbbie/dchen<file_sep>/restart_sinatra.sh killall -9 ruby ruby app.rb<file_sep>/public/restart_nginx.sh #!/bin/bash #sudo killall -9 nginx kill -WINCH `cat /home/aliyun/dichen/log/nginx.pid` && kill -9 `cat /home/aliyun/dichen/log/nginx.pid` sudo nginx -c /home/aliyun/dichen/nginx.conf <file_sep>/test.rb require 'sinatra' require 'active_support/all' require 'redis_pagination' redis_config = { 'host' => '127.0.0.1', 'port' => '6379' } $redis_write = Redis.new( redis_config ) $redis_write.select(0) author = 'admin' subject = 'a' content = 'aa' new_id = $redis_write.incr 'content_data_max_id' $redis_write.mapped_hmset "content_data:#{new_id}", { :id => new_id, :author => author, :created_at => Time.now.to_i, :created_at_str => Time.now.to_s(:db), :subject => subject, :content => content, :read_count => 0 } $redis_write.zadd "content_data_list", Time.now.to_i, new_id <file_sep>/Gemfile source 'https://rubygems.org' #source 'http://ruby.taobao.org' gem 'redis_pagination' gem 'sinatra' gem 'activesupport' gem 'redis' <file_sep>/README.md dchen ===== <file_sep>/app.rb require 'rubygems' require 'sinatra' require 'active_support/all' require 'redis_pagination' require './app' enable :sessions configure do set :host, '127.0.0.1' set :port, 86 end log = File.new(File.expand_path("../log/production.log", __FILE__), "a+") $stdout.reopen(log) $stderr.reopen(log) redis_config = { 'host' => '127.0.0.1', 'port' => '6379' } $redis_write = Redis.new( redis_config ) $redis_write.select(0) RedisPagination.configure do |configuration| configuration.redis = $redis_write configuration.page_size = 50 end get '/' do items_paginator = RedisPagination.paginate('content_data_list') @items = items_paginator.page(1) @top_data = [] @items[:items].map do|item| key = item[0] if @top_data.size < 5 d = $redis_write.mapped_hmget "content_data:#{key}", :id, :created_at_str, :subject, :type @top_data.push(d) if d[:type].blank? or d[:type] == 'xinwen' end end @top_data erb :index end get '/data_content' do id = params[:id] @ret = ($redis_write.hgetall "content_data:#{id}") @subject = @ret['subject'] @content = @ret['content'] erb :data_content end get '/data_list' do page_no = params[:page].to_i || 1 items_paginator = RedisPagination.paginate('content_data_list') @items = items_paginator.page(page_no) @ret = [] @items[:items].map do|item| key = item[0] d = $redis_write.mapped_hmget "content_data:#{key}", :id, :created_at_str, :subject, :type @ret.push(d) if d[:type].blank? or d[:type] == 'xinwen' end @items[:items] = @ret erb :data_list end get '/anli_list' do page_no = params[:page].to_i || 1 items_paginator = RedisPagination.paginate('content_data_list') @items = items_paginator.page(page_no) @ret = [] @items[:items].map do|item| key = item[0] d = $redis_write.mapped_hmget "content_data:#{key}", :id, :created_at_str, :subject, :type @ret.push(d) if d[:type] == 'anli' end @items[:items] = @ret erb :anli_list end get '/admin_login' do erb :admin_login end post'/admin_login' do password = params[:password] if password != '<PASSWORD>' redirect '/admin_login' else session[:admin] = true redirect '/data_list' end end post '/data_add' do author = params[:author ] subject = params[:subject] content = params[:content] id = params[:id ] type = params[:type ] if id.blank? new_id = $redis_write.incr 'content_data_max_id' else new_id = id end $redis_write.mapped_hmset "content_data:#{new_id}", { :id => new_id, :type => type, :author => author, :created_at => Time.now.to_i, :created_at_str => Time.now.to_s(:db), :subject => subject, :content => content, :read_count => 0 } $redis_write.zadd "content_data_list", Time.now.to_i, new_id if id.blank? "add success" else "update success" end end get '/data_add' do if params[:id] @ret = ($redis_write.hgetall "content_data:#{params[:id]}") else @ret = {} end erb :data_add end get '/data_delete' do if session[:admin] and params[:id] $redis_write.zrem "content_data_list", params[:id] "delete success" end end get '/env' do ips = "REMOTE_ADDR: #{request.env['REMOTE_ADDR']}<br/>" + "HTTP_VIA: #{request.env['HTTP_VIA']}<br/>" + "HTTP_X_FORWARDED_FOR: #{request.env['HTTP_X_FORWARDED_FOR']}<br/>" headers = request.env.inspect ips + headers end #run Sinatra::Application <file_sep>/restart_nginx.sh #!/bin/bash #sudo killall -9 nginx kill -WINCH `cat /home/aliyun/dchen/log/nginx.pid` && kill -9 `cat /home/aliyun/dchen/log/nginx.pid` sudo nginx -c /home/aliyun/dchen/nginx.conf
18b49608e17f1375e22b4c3b7387705247fb0956
[ "Markdown", "Ruby", "Shell" ]
7
Shell
debbbbie/dchen
cd79dac5c4a10faeebecd7afbe7237ed3a452f7f
0690f90573361738af9d44a4f32fb32673c31bd9
refs/heads/master
<repo_name>oozam/Reactivities<file_sep>/Persistence/ReactivitiesDbContext.cs namespace Persistence { using Domain; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; public class ReactivitiesDbContext : DbContext { public ReactivitiesDbContext(DbContextOptions<ReactivitiesDbContext> options) : base(options) { } public DbSet<Value> Values { get; set; } public DbSet<Activity> Activities { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Value>() .HasData( new Value { Id = 1, Name = "Value 1"}, new Value { Id = 2, Name = "Value 2"}, new Value { Id = 3, Name = "Value 3"} ); foreach (IMutableEntityType entity in modelBuilder.Model.GetEntityTypes()) entity.SetTableName(entity.DisplayName()); modelBuilder.ApplyConfigurationsFromAssembly(typeof(ReactivitiesDbContext).Assembly); } } } <file_sep>/Application/Activities/List.cs namespace Application.Activities { using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Domain; using MediatR; using Microsoft.EntityFrameworkCore; using Persistence; public class List { public class Query : IRequest<List<Activity>> { } public class Handler : IRequestHandler<Query, List<Activity>> { private readonly ReactivitiesDbContext context; public Handler(ReactivitiesDbContext context) { this.context = context; } public async Task<List<Activity>> Handle(Query request, CancellationToken cancellationToken) { var activites = await this.context.Activities.ToListAsync(cancellationToken); return activites; } } } } <file_sep>/Persistence/DbContextFactory.cs namespace Persistence { using System; using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore; public class DbContextFactory : DesignTimeDbContextFactoryBase<ReactivitiesDbContext> { protected override ReactivitiesDbContext CreateNewInstance(DbContextOptions<ReactivitiesDbContext> options) { return new ReactivitiesDbContext(options); } } } <file_sep>/Application/IReactivitiesDbContext.cs namespace Application { using System.Threading; using System.Threading.Tasks; using Domain; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; public interface IReactivitiesDbContext { DbSet<Value> Values{ get; set; } Task<int> SaveChangesAsync(CancellationToken cancellationToken); Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken); EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; DbSet<T> Set<T>() where T : class; } } <file_sep>/API/Controllers/ValueController.cs namespace API.Controllers { using System.Collections.Generic; using System.Threading.Tasks; using Domain; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Persistence; [Route("api/[controller]")] [ApiController] public class ValuesController : Controller { private readonly ReactivitiesDbContext context; public ValuesController(ReactivitiesDbContext context) { this.context = context; } [HttpGet] public async Task<ActionResult<IEnumerable<Value>>> Get() { var values = await context.Values.ToListAsync(); return Ok(values); } [HttpGet("{id}")] public async Task<ActionResult<Value>> Get(int id) { var value = await context.Values.FindAsync(id); return Ok(value); } // GET: /<controller>/ public IActionResult Index() { return View(); } } }
466f14fbde00eef64ab78cf7ab109abcf23c4e77
[ "C#" ]
5
C#
oozam/Reactivities
5ba4bd37c392e2535a8e630d87e2e74cf75afbd3
2760e63da9aa87edd78f2f356261c7beaf7a01f7
refs/heads/main
<repo_name>Ceryunus/Python-Oyun-Tas-Kagit-Makas<file_sep>/PythonTasKagitMakasOyunu.py import random class Oyun(): def userinputs(self): self.userinput = input("[ tas | kagit | makas ] : ") if self.userinput in self.myList: return self.userinput else: "gecersiz" def randomSelection(self): self.myList = myList = ["tas", "kagit", "makas"] self.randomList = random.choice(myList) return self.randomList def puanlama(self): pass def gameBrain(self): computerscore = 0 userscore = 0 self.computerscore = computerscore self.userscore = userscore def yazdir(): print(f"Computer : {self.randomList} [] Sen : {self.userinput}") print(f"{self.computerscore} - {self.userscore}") # __init methodu calısyor zaten o yüzden eklemedim while True: if self.computerscore == 3 or self.userscore == 3: if self.computerscore == 3: print(f"Kazanan Computer \n Skorlar : {self.computerscore} - {self.userscore}") else: print(f"Kazanan Sensin \n Skorlar : {self.computerscore} - {self.userscore}") a = input("tekrar oynamak ister misin (e/h)") if a == "e": self.computerscore = 0 self.userscore = 0 print("Oyun tekrar başlatıldı :) Bol şans\n\n") else: break self.randomSelection() self.userinputs() if self.randomList == self.userinput: print(f"{self.randomList} {self.userinput} Berabere") else: if self.userinput == "tas": if self.randomList == "kagit": self.computerscore += 1 yazdir() else: self.userscore += 1 yazdir() if self.userinput == "kagit": if self.randomList == "makas": self.computerscore += 1 yazdir() else: self.userscore += 1 yazdir() if self.userinput == "makas": if self.randomList == "tas": self.computerscore += 1 yazdir() else: self.userscore += 1 yazdir() s1 = Oyun() s1.gameBrain()
3f8f5011d39ee660c4641d0cbaaa19cbe53fc54f
[ "Python" ]
1
Python
Ceryunus/Python-Oyun-Tas-Kagit-Makas
eae59fed15852cc955a33b8fcf236052dc1093a9
d112a6cf0037ef3a40cea958aed0331a37b9cadd
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemPositions : MonoBehaviour { // Use this for initialization void Start () { //if item is 1 -> position 1 //else item is 2 -> position 2 if (this.gameObject.name == "First item") transform.position = new Vector3(100, 250, -44); if (this.gameObject.name == "Second item") transform.position = new Vector3(600, 250, -44); if (this.gameObject.name == "Third item") transform.position = new Vector3(100, 80, -44); if (this.gameObject.name == "Forth item") transform.position = new Vector3(600, 80, -44); } // Update is called once per frame void Update () { } } <file_sep># DragMatch A simple game by dragging words to match the question
8629265a36a69a818d5587fa93b34e37bb934597
[ "Markdown", "C#" ]
2
C#
rexwong4work/DragMatch
34327a078e3800e98732fc0bda4a16572c83cb3b
61643522426d936f9a5eb0a19be4b03a3cf1834c
refs/heads/main
<file_sep>package servidor; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.LinkedList; import javax.swing.JOptionPane; import mapa.Mapa; public class ServidorJuego { private final int puerto = 2028; private final int noConexiones = 20; private ServerSocket servidor; private Mapa map; private LinkedList<Socket> usuarios = new LinkedList<Socket>(); private HashMap<String, Socket> mapId = new HashMap<String, Socket>(); public void escuchar() throws IOException { try { servidor = new ServerSocket(puerto, noConexiones); map = new Mapa(); while (true) { Socket cliente = servidor.accept(); usuarios.add(cliente); Runnable run = new HiloServidor(cliente, usuarios, map, mapId); Thread hilo = new Thread(run); hilo.start(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error al conectar el cliente", "Error", JOptionPane.ERROR_MESSAGE); } finally { servidor.close(); } } public static void main(String[] args) { ServidorJuego servidor = new ServidorJuego(); try { servidor.escuchar(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Error al levantar el servidor", "Error", JOptionPane.ERROR_MESSAGE); } } }<file_sep>package gui; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLayeredPane; import javax.swing.JComboBox; public class PantallaBatalla extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; /** * Create the frame. */ public PantallaBatalla() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setBounds(5, 5, 422, 243); contentPane.add(layeredPane); JPanel panel = new JPanel(); panel.setBounds(0, 0, 422, 243); layeredPane.add(panel); JPanel panel_1 = new JPanel(); panel_1.setBackground(Color.BLUE); panel_1.setBounds(12, 196, 398, 34); layeredPane.add(panel_1); JComboBox<Integer> comboBox = new JComboBox<Integer>(); comboBox.setSize(100, 50); comboBox.setToolTipText("select"); panel_1.add(comboBox); } } <file_sep>package conexionSQL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class ConexionSQL { private static Connection conexion; private static String URL = "src/main/resources/WarLords.db"; private Statement consulta; public ConexionSQL() { } public void conectar() { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { } try { conexion = DriverManager.getConnection("jdbc:sqlite:" + URL); this.consulta = conexion.createStatement(); } catch (SQLException e) { } } public void desconectar() { try { if (conexion != null) { conexion.close(); this.consulta.close(); } } catch (SQLException sqle) { } } public Statement getConsulta() { return this.consulta; } public Connection getConexion() { return conexion; } }<file_sep>package batalla; import java.awt.Button; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.ImageObserver; import java.util.HashMap; import java.util.Map.Entry; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import mapa.BuscarImagen; import mapa.Dibujable; import personaje.Personaje; import personaje.PersonajeDibujable; public class BatallaDibujable { private String img; private String mensajeBatalla; private int ancho, alto; private int anchoCuadro = 800, altoCuadro = 600; private HashMap<String, Personaje> retador = new HashMap<String, Personaje>(); private HashMap<String, PersonajeDibujable> contrincante = new HashMap<String, PersonajeDibujable>(); private String turno; public BatallaDibujable(Personaje ataca, String bando, PersonajeDibujable enemigo) { BuscarImagen buscar = new BuscarImagen(); img = "batalla.png"; alto = buscar.altoMapa(img); ancho = buscar.anchoMapa(img); // this.colisionables = new HashMap<String, PersonajeDibujable>(); retador.put(ataca.getID(), ataca); contrincante.put(enemigo.getID(), enemigo); turno = ataca.getID(); bando = "R"; } public void agregarContrincante(PersonajeDibujable ataca, String bando) { contrincante.put(ataca.getID(), ataca); bando = "C"; } public void pintarBatalla(Graphics g, ImageObserver observer) { Graphics2D g2 = (Graphics2D) g; BuscarImagen buscar = new BuscarImagen(); g2.drawImage(buscar.subImgMapa(img, 0, 0, anchoCuadro, altoCuadro / 2), 0, 0, observer); PersonajeDibujable d; int x = 250; int y = 200; for (Entry<String, Personaje> dibujar : retador.entrySet()) { g2.drawImage(dibujar.getValue().getImagen(), x, y, observer); g2.drawString(dibujar.getKey(), x, y); y += 40; } x = 550; y = 200; for (Entry<String, PersonajeDibujable> dibujar : contrincante.entrySet()) { g2.drawImage(dibujar.getValue().getImagen(), x, y, observer); g2.drawString(dibujar.getKey(), x, y); y += 40; } Image menu = new ImageIcon("src/main/java/img/menu.png").getImage(); Image boton = new ImageIcon("src/main/java/img/botonMenu.png").getImage(); g2.drawImage(menu, 10, 400, observer); String opcion = null; g.drawImage(boton, 15, 400, observer); g.drawString("ATACAR", 15, 400); /*g.drawImage(boton, 15, 460, observer); g.drawString("defender", 18, 465);*/ } public void pintarMenu(Graphics g, Personaje pers, String grupo, ImageObserver observer, MouseListener ml) { Graphics2D g2 = (Graphics2D) g; BuscarImagen buscar = new BuscarImagen(); Image menu = new ImageIcon("src/main/java/img/menu.png").getImage(); Image boton = new ImageIcon("src/main/java/img/botonMenu.png").getImage(); g2.drawImage(menu, 10, 500, observer); String opcion = null; g2.drawImage(menu, 10, 500, observer); // String opcion = null; g2.drawImage(boton, 15, 490, observer); g2.drawString("atacar", 18, 495); g2.drawImage(boton, 15, 460, observer); g2.drawString("defender", 18, 465); int x; int y; g.dispose(); } public void actualizarBatalla(Dibujable d) { } public boolean esMiTurno(String id) { return turno.equals(id); } } <file_sep>package jugador; import java.awt.Image; import java.awt.event.KeyEvent; import java.net.Socket; import javax.swing.ImageIcon; import castas.Brujo; import castas.Guerrero; import castas.Paladin; import mapa.Punto; import personaje.Personaje; import razas.Humano; public class Jugador { private Personaje personaje; private String Nombre; private Socket conexionServer; private String estado; private String casta; private String raza; private Punto posicion; private String animacion; private int desplazamientoX; private int desplazamientoY; private Image imagen; // Constructores /*public Jugador(String nombre, String raza, String casta) { Nombre = nombre; this.casta = casta; this.raza = raza; posicion = new Punto(40, 60); desplazamientoX = 0; desplazamientoY = 0; switch (raza) { case "Humano": { switch (casta) { case "Brujo": personaje = new Humano(new Brujo(), casta, casta); break; case "Guerrero": personaje = new Humano(new Guerrero(), casta, casta); break; case "Paladin": personaje = new Humano(new Paladin(), casta, casta); break; } break; } case "Elfo": { switch (casta) { case "Brujo": personaje = new Humano(new Brujo(), casta, casta); break; case "Guerrero": personaje = new Humano(new Guerrero(), casta, casta); break; case "Paladin": personaje = new Humano(new Paladin(), casta, casta); break; } break; } case "Orco": { switch (casta) { case "Brujo": personaje = new Humano(new Brujo()); break; case "Guerrero": personaje = new Humano(new Guerrero()); break; case "Paladin": personaje = new Humano(new Paladin()); break; } break; } } ImageIcon img = new ImageIcon(this.getClass().getResource("/imagenes/ElfoGuerrero.gif")); imagen = img.getImage(); }*/ // Getters and Setters public Punto getPosicion() { return posicion; } public void setPosicion(Punto posicion) { this.posicion = posicion; } public String getNombre() { return Nombre; } public void setNombre(String nombre) { Nombre = nombre; } public String getCasta() { return casta; } public void setCasta(String casta) { this.casta = casta; } public String getRaza() { return raza; } public void setRaza(String raza) { this.raza = raza; } public Personaje getPersonaje() { return personaje; } public Image getImagen() { return imagen; } public void setImagen(Image imagen) { this.imagen = imagen; } // Metodos Adicionales public void mover() { posicion.desplazar(desplazamientoX, desplazamientoY); } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) desplazamientoX -= 1; if (key == KeyEvent.VK_RIGHT) desplazamientoX += 1; if (key == KeyEvent.VK_UP) desplazamientoY -= 1; if (key == KeyEvent.VK_DOWN) desplazamientoY += 1; } public void keyReleased(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) desplazamientoX = 0; if (key == KeyEvent.VK_RIGHT) desplazamientoX = 0; if (key == KeyEvent.VK_UP) desplazamientoY = 0; if (key == KeyEvent.VK_DOWN) desplazamientoY = 0; } }<file_sep>package mapa; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.ImageObserver; import java.util.HashMap; import java.util.Map.Entry; import personaje.Personaje; import personaje.PersonajeDibujable; public class Mapa { private String img; private int ancho, alto; private int anchoCuadro = 800, altoCuadro = 600; private HashMap<String, PersonajeDibujable> colisionables; public Mapa() { BuscarImagen buscar = new BuscarImagen(); img = "stage2.png"; alto = buscar.altoMapa(img); ancho = buscar.anchoMapa(img); this.colisionables = new HashMap<String, PersonajeDibujable>(); } public Mapa(Mapa map) { this.ancho = map.ancho; this.alto = map.alto; this.colisionables = map.colisionables; } public int xRespectoPersonajeMapa(PersonajeDibujable pers) { int xRealitivo = pers.getPosicionX() - (this.anchoCuadro / 2); if (xRealitivo < 0) { return 0; } if ((xRealitivo + this.anchoCuadro) > this.ancho) return this.ancho - this.anchoCuadro; return xRealitivo; } public int yRespectoPersonajeMapa(PersonajeDibujable pers) { int yRealitivo = pers.getPosicionY() - (this.altoCuadro / 2); if (yRealitivo < 0) { return 0; } if ((yRealitivo + this.altoCuadro) > this.alto) return this.alto - this.altoCuadro; return yRealitivo; } public boolean sePuedeUbicar(PersonajeDibujable pers, int x, int y) { return true; } public PersonajeDibujable hayBatalla(PersonajeDibujable pers) { PersonajeDibujable enemigo; for (Entry<String, PersonajeDibujable> contrincante : colisionables.entrySet()) { if (!(pers.getID().equals(contrincante.getKey())) && contrincante.getValue().enBatalla() == false && pers.seSuperPonen(contrincante.getValue())) { enemigo = contrincante.getValue(); return enemigo; } } return null; } public void pintarMapa(Graphics g, PersonajeDibujable pers, ImageObserver observer) { Graphics2D g2 = (Graphics2D) g; int xRelativo = this.xRespectoPersonajeMapa(pers); int yRelativo = this.yRespectoPersonajeMapa(pers); BuscarImagen buscar = new BuscarImagen(); g2.drawImage(buscar.subImgMapa(img, xRelativo, yRelativo, anchoCuadro, altoCuadro), 0, 0, observer); PersonajeDibujable d; for (Entry<String, PersonajeDibujable> dibujar : colisionables.entrySet()) { d = dibujar.getValue(); int x = d.getPosicionX(); int y = d.getPosicionY(); if (d.enBatalla() == false && x > xRelativo && x < (xRelativo + this.anchoCuadro) && y > yRelativo && y < (yRelativo + this.altoCuadro)) { g2.drawImage(d.getImagen(), d.getPosicionX() - xRelativo - (d.getAncho() / 2), d.getPosicionY() - yRelativo - d.getAlto(), observer); g2.drawString(d.getID(), d.getPosicionX() - xRelativo - (d.getAncho() / 2), d.getPosicionY() - yRelativo - d.getAlto()); } } } public void agregarDibujable(Dibujable d) { colisionables.put(d.getID(), (PersonajeDibujable) d); } public void quitar(String id) { colisionables.remove(id); } public synchronized void actualizarMapa(Dibujable d) { // colisionables.replace(d.getID(), (Personaje)d); colisionables.remove(d.getID()); colisionables.put(d.getID(), (PersonajeDibujable) d); } } <file_sep>package test; import org.junit.Assert; import org.junit.Test; import castas.Brujo; import castas.Paladin; import personaje.Personaje; import personajeEquipado.ConAnillo; import personajeEquipado.ConArmadura; import personajeEquipado.ConBastonAghanim; import personajeEquipado.ConCascoDeLaMuerte; import personajeEquipado.ConEspada; import razas.Elfo; import razas.Humano; import razas.Orco; public class ElfoTest { @Test public void quePuedoCrearUnPaladin() { Personaje paladin = new Elfo(new Brujo(),null,null); Assert.assertEquals(85, paladin.getSalud()); Assert.assertEquals(120, paladin.getEnergia()); Assert.assertEquals(1, paladin.getNivel()); Assert.assertEquals(0, paladin.getExp()); Assert.assertEquals(10, paladin.getAtaque()); Assert.assertEquals(2, paladin.getDefensa()); Assert.assertEquals(12, paladin.getInteligencia()); Assert.assertEquals(3, paladin.getMana()); Assert.assertEquals("Brujo", paladin.getCasta().nombreCastaElegida()); } @Test public void quePuedoEquiparlo() { Personaje paladin = new Elfo(new Brujo(),null,null); paladin = new ConAnillo(paladin); // aumenta el ataque 15 pts Assert.assertEquals(10 + 15, paladin.getAtaque()); paladin = new ConArmadura(paladin); // aumenta la defensa 13 pts Assert.assertEquals(2 + 13, paladin.getDefensa()); paladin = new ConBastonAghanim(paladin); // aumenta el poder de hechizo // 5 pts Assert.assertEquals(10, paladin.obtenerPuntosDeHechizos()); paladin = new ConEspada(paladin); // aumenta la defensa 13 pts Assert.assertEquals(10 + 15 + 5, paladin.getAtaque()); paladin = new ConCascoDeLaMuerte(paladin); // aumenta la defensa 13 pts Assert.assertEquals(2 + 13 + 4, paladin.getDefensa()); } @Test public void quePuedeAtacar() { Personaje paladin = new Elfo(new Brujo(),null,null); Personaje orco = new Orco(new Paladin(),null,null); paladin.atacar(orco); Assert.assertEquals(111, orco.getSalud()); Assert.assertEquals(110, paladin.getEnergia()); } @Test public void quePuedeSerAtacado() { Personaje paladin = new Elfo(new Brujo(),null,null); Personaje orco = new Orco(new Paladin(),null,null); orco.atacar(paladin); Assert.assertEquals(73, paladin.getSalud()); Assert.assertEquals(88, orco.getEnergia()); } @Test public void quePuedeHechizar() { Personaje paladin = new Elfo(new Brujo(),null,null); Personaje orco = new Orco(new Paladin(),null,null); Assert.assertFalse(paladin.aplicarHechizo("Bola de la oscuridad", orco)); paladin.setMana(37); Assert.assertTrue(paladin.aplicarHechizo("Bola de la oscuridad", orco)); Assert.assertEquals(81, orco.getSalud()); Assert.assertEquals(37 - 23, paladin.getMana()); Assert.assertFalse(paladin.aplicarHechizo("Disminuir ataque", orco)); paladin.setMana(37); Assert.assertTrue(paladin.aplicarHechizo("Disminuir ataque", orco)); Assert.assertEquals(6, orco.getAtaque()); Assert.assertEquals(37 - 15, paladin.getMana()); Assert.assertFalse(paladin.aplicarHechizo("Latigaso mortal", orco)); paladin.setMana(37); Assert.assertTrue(paladin.aplicarHechizo("Latigaso mortal", orco)); Assert.assertEquals(37, orco.getSalud()); Assert.assertEquals(37 - 30, paladin.getMana()); } } <file_sep>package castas; import hechizosYHabPaladin.GolpeHeroico; import hechizosYHabPaladin.Sanar; import hechizosYHabPaladin.TormentaDivina; public class Paladin extends Casta { public Paladin() { this.casta = "Paladin"; this.idCasta = 3; this.agregarHechizo("Sanar", new Sanar()); this.agregarHechizo("Golpe heroico", new GolpeHeroico()); this.agregarHechizo("Tormenta divina", new TormentaDivina()); } } <file_sep>package hechizosYHabPaladin; import personaje.HechizoOHab; import personaje.Personaje; public class GolpeHeroico extends HechizoOHab{ public GolpeHeroico(){ this.costo = 37; } @Override public void afectar(Personaje personaje,int poderDeHabilidad) { personaje.serAtacado(40); } } <file_sep>package servidorTest; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import castas.Guerrero; import conexionSQL.ConexionSQL; import conexionSQL.OperacionesBD; import personaje.Personaje; import personaje.PersonajeDibujable; import razas.Humano; public class ConexionSQLTest { @Ignore public void queConectaConLaBaseDeDatos() { ConexionSQL conexion = new ConexionSQL(); conexion.conectar(); } @Ignore public void queConsultaCorrectamente() { OperacionesBD conexion = new OperacionesBD(); conexion.conectar(); String usuario = "NICO"; Assert.assertEquals(true, conexion.existeUsuario(usuario)); usuario = "Mascherano"; Assert.assertEquals(false, conexion.existeUsuario(usuario)); conexion.desconectar(); } @Ignore public void queInsertaUnUsuario() { OperacionesBD conexion = new OperacionesBD(); conexion.conectar(); String usuario = "CIRO"; String contraseña = "<PASSWORD>"; Assert.assertEquals(false, conexion.existeUsuario(usuario)); conexion.insertarUsuario(usuario, contraseña); conexion.existeUsuario(usuario); Assert.assertEquals(true, conexion.existeUsuario(usuario)); conexion.desconectar(); } @Ignore public void queValidaLaContraseña() { OperacionesBD conexion = new OperacionesBD(); conexion.conectar(); String usuario = "CIRO"; String contraseña = "<PASSWORD>"; Assert.assertEquals(false, conexion.existeUsuario(usuario)); conexion.insertarUsuario(usuario, contraseña); Assert.assertEquals(true, conexion.existeUsuario(usuario)); Assert.assertEquals(true, conexion.validarCredenciales(usuario, contraseña)); Assert.assertEquals(false, conexion.validarCredenciales(usuario, "1<PASSWORD>")); conexion.desconectar(); } // @Test // public void queInsertaUnPersonaje() { // String nombrePersonaje = "NICO"; // Personaje personaje = new Humano(new Guerrero(), nombrePersonaje, "humanoG"); // OperacionesBD conexion = new OperacionesBD(); // conexion.conectar(); // Assert.assertEquals(true, conexion.insertarPersonaje(personaje, null)); // conexion.desconectar(); // } // @Test // public void queInsertaUnPersonajeDibujable() { // String nombrePersonaje = "NICO"; // String img = "orcoP"; // OperacionesBD conexion = new OperacionesBD(); // conexion.conectar(); // Assert.assertEquals(true, conexion.insertarPersonajeDibujable(nombrePersonaje, img)); // conexion.desconectar(); // } @Test public void queConsultaElPersonaje(){ String nombrePersonaje = "NICO"; OperacionesBD conexion = new OperacionesBD(); conexion.conectar(); Assert.assertEquals(true, conexion.consultarPersonaje(nombrePersonaje)); conexion.desconectar(); } @Test public void queObtieneElPersonaje(){ String nombrePersonaje = "NICO"; OperacionesBD conexion = new OperacionesBD(); conexion.conectar(); // Personaje personaje = conexion.obtenerPersonaje(nombrePersonaje); //Assert.assertEquals(personaje, personaje); conexion.desconectar(); } } <file_sep>package mapa; public class Rectangulo { int base; int altura; private Punto puntoInicial; // Constructores public Rectangulo(Punto puntoInicial, int base, int altura) { this.puntoInicial = puntoInicial; this.base = base; this.altura = altura; } // Getters and Setters public double getBase() { return base; } public void setBase(int base) { this.base = base; } public double getAltura() { return altura; } public void setAltura(int altura) { this.altura = altura; } // Metodos adicionales public double area() { return base * altura; } } <file_sep>package gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import cliente.Mensaje; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; public class Registro extends JFrame { private JPanel contentPane; private JTextField textFieldUsuario; private JPasswordField passwordField; private JPasswordField repetirPasswordField; private Login login; private JTextField textFieldIP; private JTextField textFieldPuerto; /** * Create the frame. */ public void run() { login.setMensaje(new Mensaje("", "")); setTitle("WarLords - Registro"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblUsuario = new JLabel("Usuario:"); lblUsuario.setBounds(81, 11, 62, 14); contentPane.add(lblUsuario); JLabel lblContraseña = new JLabel("Contrase\u00F1a:"); lblContraseña.setBounds(81, 67, 79, 14); contentPane.add(lblContraseña); textFieldUsuario = new JTextField(); textFieldUsuario.setBounds(91, 36, 257, 20); contentPane.add(textFieldUsuario); textFieldUsuario.setColumns(10); passwordField = new JPasswordField(); passwordField.setBounds(91, 92, 257, 20); contentPane.add(passwordField); JButton btnAceptar = new JButton("Aceptar"); btnAceptar.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { if (arg0.getKeyChar() == KeyEvent.VK_ENTER) { if (validarPuertoIP()) { textFieldUsuario.setText(textFieldUsuario.getText().toUpperCase()); if (validarDatosCompletos() && validarContraseñas()) { try { String respuestaValidacion = validarNombreDeUsuario(); if (respuestaValidacion.equals("false")) { if (registrarUsuario(textFieldUsuario.getText(), passwordField.getText()) == "false") { JOptionPane.showMessageDialog(null, "Error al registrar el usuario", "Error", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Registro exitoso!", null, JOptionPane.ERROR_MESSAGE); login.completarUsuario(textFieldUsuario.getText()); dispose(); } } else { JOptionPane.showMessageDialog(null, "Usuario existente", "Error", JOptionPane.ERROR_MESSAGE); } } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Error en el servidor", "Error", JOptionPane.ERROR_MESSAGE); } } } } } }); btnAceptar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textFieldUsuario.setText(textFieldUsuario.getText().toUpperCase()); if (validarPuertoIP()) { if (validarDatosCompletos() && validarContraseñas()) { try { String respuestaValidacion = validarNombreDeUsuario(); if (respuestaValidacion.equals("false")) { if (registrarUsuario(textFieldUsuario.getText(), passwordField.getText()) == "false") { JOptionPane.showMessageDialog(null, "Error al registrar el usuario", "Error", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Registro exitoso!", null, JOptionPane.ERROR_MESSAGE); login.completarIPYPuerto(textFieldIP.getText(), textFieldPuerto.getText()); login.completarUsuario(textFieldUsuario.getText()); dispose(); } } else { JOptionPane.showMessageDialog(null, "Usuario existente", "Error", JOptionPane.ERROR_MESSAGE); } } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Error en el servidor", "Error", JOptionPane.ERROR_MESSAGE); } } } } }); btnAceptar.setBounds(115, 227, 89, 23); contentPane.add(btnAceptar); repetirPasswordField = new JPasswordField(); repetirPasswordField.setBounds(91, 146, 257, 20); contentPane.add(repetirPasswordField); JLabel lblRepetirContraseña = new JLabel("Repetir contrase\u00F1a:"); lblRepetirContraseña.setBounds(81, 123, 96, 14); contentPane.add(lblRepetirContraseña); JButton btnCancelar = new JButton("Cancelar"); btnCancelar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { cancelarRegistro(); } }); btnCancelar.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { if (arg0.getKeyChar() == KeyEvent.VK_ENTER) { cancelarRegistro(); } } }); btnCancelar.setBounds(244, 227, 89, 23); contentPane.add(btnCancelar); JLabel labelIP = new JLabel("IP"); labelIP.setBounds(91, 182, 46, 14); contentPane.add(labelIP); textFieldIP = new JTextField(); textFieldIP.setColumns(10); textFieldIP.setBounds(91, 196, 86, 20); contentPane.add(textFieldIP); JLabel labelPuerto = new JLabel("Puerto"); labelPuerto.setBounds(248, 182, 46, 14); contentPane.add(labelPuerto); textFieldPuerto = new JTextField(); textFieldPuerto.setColumns(10); textFieldPuerto.setBounds(248, 196, 86, 20); contentPane.add(textFieldPuerto); } public void escribirUsuario() { login.completarUsuario(textFieldUsuario.getText()); } public Registro(Login login) { setResizable(false); this.login = login; run(); } private String validarNombreDeUsuario() throws IOException { login.getMensaje().cambiarMensaje("validarUsuario", this.textFieldUsuario.getText()); this.login.enviarMensaje(login.getMensaje()); this.login.leerRespuesta(); return login.getGson().fromJson(login.getMensaje().getJson(), String.class); } private String registrarUsuario(String usuario, String contraseña) throws IOException { String datosUsuario = usuario + ":" + contraseña; login.getMensaje().cambiarMensaje("registrarUsuario", datosUsuario); this.login.enviarMensaje(login.getMensaje()); this.login.leerRespuesta(); return login.getGson().fromJson(login.getMensaje().getJson(), String.class); } @SuppressWarnings("deprecation") public boolean validarContraseñas() { if (!this.passwordField.getText().equals(this.repetirPasswordField.getText())) { JOptionPane.showMessageDialog(null, "No coinciden las contraseñas", "Error", JOptionPane.ERROR_MESSAGE); return false; } return true; } @SuppressWarnings("deprecation") public boolean validarDatosCompletos() { if (this.passwordField.getText().length() > 0 && this.repetirPasswordField.getText().length() > 0 && this.textFieldUsuario.getText().length() > 0) { return true; } JOptionPane.showMessageDialog(null, "Faltan ingresar datos", "Error", JOptionPane.ERROR_MESSAGE); return false; } public void cancelarRegistro() { this.dispose(); login.setVisible(true); } protected boolean validarPuertoIP() { if (this.textFieldIP.getText().length() > 0 && this.textFieldPuerto.getText().length() > 0) { login.setIP(this.textFieldIP.getText()); login.setPuerto(Integer.parseInt(this.textFieldPuerto.getText())); login.conectarCliente(); return true; } JOptionPane.showMessageDialog(null, "Debe ingresar el puerto y la IP", "Error", JOptionPane.ERROR_MESSAGE); return false; } } <file_sep>package razas; import castas.Casta; import personaje.Personaje; public class Humano extends Personaje { public Humano(Casta castaElegida, String nombrePersonaje, String img) { this.maxSalud = 100; this.maxEnergia = 100; this.salud = 100; this.ataque = 10; this.defensa = 10; this.inteligencia = 10; this.casta = castaElegida; this.energia = 100; this.exp = 0; this.nivel = 1; this.mana = 0; this.expMax=100; this.id=nombrePersonaje; this.img=img; this.idRaza = 1; } public Humano(Casta casta, String id, String img, int salud, int ataque, int defensa, int energia, int experiencia, int nivel, int mana, int idRaza){ this.maxSalud = 100; this.maxEnergia = 100; this.salud = salud; this.ataque = ataque; this.defensa = defensa; this.inteligencia = 10; this.casta = casta; this.energia = energia; this.exp = experiencia; this.nivel = nivel; this.mana = mana; this.expMax=100; this.id=id; this.img=img; this.idRaza = idRaza; } @Override public void despuesDeAtacar() { mana += 10; } @Override public int calcularPuntosDeAtaque() { return ataque + this.ataqueAfectado; } @Override public boolean puedeAtacar() { return energia >= 10; } @Override public int obtenerPuntosDeDefensa() { return this.defensa; } } <file_sep>package hechizosYHabPaladin; import personaje.HechizoOHab; import personaje.Personaje; public class TormentaDivina extends HechizoOHab { public TormentaDivina(){ this.costo = 37; } @Override public void afectar(Personaje personaje,int poderDeHabilidad) { personaje.serAtacado(40); } } <file_sep>package hechizosDeBrujo; import personaje.HechizoOHab; import personaje.Personaje; public class LatigazoMortal extends HechizoOHab{ public LatigazoMortal(){ this.costo = 30; } @Override public void afectar(Personaje personaje,int poderDeHabilidad) { personaje.serAtacado(35+poderDeHabilidad); } } <file_sep># HISTORIAS DE USUARIO Warlords **1_** Como jugador quiero poder tener una cuenta con la cual, mediante nombre de usuario y contraseña para poder entrar al mundo. **Criterio de aceptacion:** 1. Dado una interface de inicio de sesion con una opcion crear usuario ,cuando se elija esa opcion ,entonces el sistema va a pedir un nombre de usuario no registrado y una contraseña. 2. Dado la creacion de un usuario ,cuando se ingrese un nombre de usuario registrado ,entonces el sistema va a pedir que se ingrese un nombre diferente. 3. Dado un nombre de usuario incorrecto ,cuando se intente iniciar una sesion ,entonces se muestra un mensaje de "usuario o contraseña incorrecta" y no inicia ninguna sesion . 4. Dado una contraseña de usuario incorrecto ,cuando se intente iniciar la sesion del usuario ,entonces se muestra un mensaje de "usuario o contraseña incorrecta" y no inicia ninguna sesion . **2_** Como jugador quiero poder crear un personaje pudiendo elegir la casta que prefiera y ponerle un nombre a mi personaje. **Criterio de aceptacion:** 1. Dado la creacion de un personaje para un jugador ,cuando se pida un nombre para ese personaje ,entonces se verifica que este disponible o no. 2. Dado la creacion de un personaje para un jugador ,cuando se pida un nombre para ese personaje ,entonces se verifica que este no sea mayor a 30 caracteres. **3_** Como jugador quiero que haya 3 razas para elegir, las cuales seran **orco,humano u elfo**, y 3 castas que seran **guerrerro, paladin y brujo**. **Criterio de aceptacion:** 1. Dada la creacion de un personaje, cuando se pide elegir una raza, entonces se puede elegir entre orco, humano u elfo. 2. Dada la creacion de un personaje, cuando se pide elegir una casta, entonces se puede elegir entre guerrerro, paladin o brujo. **4_** Como jugador quiero que cada raza tenga una potencia propia univoca que la hace diferente a las otras dos razas. **Criterio de aceptacion:** 1. Dadas las razas humano, orco y elfo, cuando un personaje humano sea creado inicialmente, entonces el humano tendra mas defensa que las otras razas. 2. Dadas las razas humano, orco y elfo, cuando un personaje orco sea creado inicialmente, entonces el orco tendra mas vida y poder de ataque que las otras razas. 3. Dadas las razas humano, orco y elfo, cuando un personaje elfo sea creado inicialmente, entonces el elfo tendra mas inteligencia y mana que las otras razas. **5_** Como jugador quiero que cada raza tenga su propia ciudad, y que no se comparta con las otras razas. **Criterio de aceptacion:** 1. Dado un personaje de una raza, cuando este entre en una ciudad de otra raza, entonces los habitantes de esa ciudad lo puedan atacar. **6_** Como jugador quiero poder explorar el mundo y encontrarme con criaturas y otros jugadores. **Criterio de aceptacion:** 1. Dado un personaje de un jugador ubicado en una pantalla del mundo, cuando el jugador hace click izquierdo sobre un punto de la pantalla, entonces el personaje del jugador se mueve hacia el punto seleccionado o hasta encontrarse con un obstaculo. 2. Dado un personaje de un jugador ubicado en una pantalla del mundo, cuando otro jugador conectado al mismo mundo se ubica sobre la misma pantalla, entonces ambos jugadores pueden ver al personaje del otro e interactuar a travez de sus personajes. 3. Dado un personaje de un jugador ubicado en una pantalla del mundo, cuando ese jugador entre a esa pantalla, entonces aparecera aleatoriamente hasta una cantidad maxima de criaturas enemigas sobre la misma pantalla. **7_** Como jugador quiero que al encontrarme con una criatuara enemiga u otro jugador que no sea mi aliado pueda entrar en una batalla con ellos. **Criterio de aceptacion:** 1. Dados dos personajes de jugadores no aliados, ubicados en la misma pantalla del mundo, cuando los personajes se encuentran dentro un radio maximo establecido respecto del otro, entonces cualquiera de los jugadores puede elegir entrar en batalla con el otro. 2. Dados un personaje de un jugador y una criatura enemiga, ambos ubicados en la misma pantalla del mundo, cuando el personaje se encuentran dentro un radio maximo establecido respecto de la criatura, entonces el jugador puede elegir entrar en batalla con esa criatura. **8_** Como jugador quiero que al entrar en batalla con una criatura, las criaturas cercanas a esa tambien entren en batalla. **Criterio de aceptacion:** 1. Dado un personaje de un jugador, cuando el jugador entra en batalla con una criatura, entonces las criaturas cercanas a esa dentro de un radio establecido tambien entran en la batalla. **9_** Como jugador quiero poder aliarme con otros jugadores para poder entrar en batallas juntos, y poder salir de una alianza cuando lo desee siempre y cuando yo no este en una batalla. **Criterio de aceptacion:** 1. Dados dos personajes de jugadores no aliados, ubicados en la misma pantalla del mundo, cuando los personajes se encuentran dentro un radio maximo establecido respecto del otro, entonces cualquiera de los jugadores puede elegir inivtar al otro a ser su aliado, o pedirle entrar en su alianza. 2. Dado un personaje de un jugador, cuando este entre en una batalla y tenga aliados cerca de el dentro de un radio maximo establecido, entonces esos aliados tambien entran en la batalla. 3. Dada una batalla en la que esta peleando una alianza, cuando un integrante de la alianza quiera salir de la alianza, entonces esa opcion no va a estar permitida. 4. Dados dos personajes de jugadores aliados, ubicados en la misma pantalla del mundo, cuando los personajes se encuentran dentro un radio maximo establecido respecto del otro y uno quiera atacar al otro, entonces el jugador no podra entrar en batalla con el otro mientras dure la alianza. **10_**Como jugador quiero que al matar a un monstruo o un jugador, este deje caer el item mas poderoso que tenga. **Criterio de aceptacion:** 1. Dado un jugador en una batalla contra una criatura, cuando el jugador mata a esa criatura, entonces la criatura deja caer un item para que sea tomado por el jugador. 2. Dado un jugador en una batalla contra otro jugador, cuando un jugador mata al otro, entonces el perdedor deja caer un item para que sea tomado por el ganador. **11_** Como jugador quiero que al matar una criatura con aliados, la criatura deje caer la misma cantidad de items, que la cantidad de aliados que haya en la alianza, pero de una calidad inferior, a la que si se hubiera matado sin estar en una alianza. **Criterio de aceptacion:** 1. Dada una batalla en la que participan una cantidad dada de aliados contra una criatura, cuando los aliados ganan la batalla, entonces la cantidad de items que deja caer este es igual a la cantidad de aliados que participaron en la batalla. 2. Dada una batalla en la que participa una alianza contra una criatura y otra batalla en la que participa un solo jugador, cuando los aliados y el jugador solitario ganan la batalla, entonces los items que deja caer la criatura a los aliados son de calidad inferior a los items que deja caer al jugador solitario. **12_** Como jugador quiero cuando mate a otro jugador, este reaparesca en un punto de resurreccion cercano. **Criterio de aceptacion:** 1. Dado un jugador, cuando este muera en una batalla, entonces el jugador reaparecera en un punto de resurreccion cercano preestablecido. **13_** Como jugador, quiero al ganar una batalla me sea dada una cantidad de puntos de experiencia para subir de nivel. 1. Dado un jugador, cuando este gana una batalla, entonces se le entregan una cantidad de puntos de experiencia dependiendo de la dificultad del adversario vencido. **Criterio de aceptacion:** **14_** Como jugador quiero que mi personaje obtenga habilidades o poderes especiales al subir de nivel, y pueda incrementar el nivel de algunas habilidades. **Criterio de aceptacion:** 1. Dado un jugador, cuando este suba de nivel, entonces se lo otorgan una cantidad de puntos de habilidades para que las reparta entre las habilidades que posea. 2. Dado un jugador, cuando este suba a un nivel multiplo de 5, entonces se le otorga una habilidad nueva. <file_sep>package habDeGuerrero; import personaje.HechizoOHab; import personaje.Personaje; public class Desgarrar extends HechizoOHab{ public Desgarrar(){ this.costo = 30; } @Override public void afectar(Personaje personaje,int poderDeHabilidad) { personaje.serAtacado(36); } }<file_sep>package test; import org.junit.Assert; import org.junit.Test; import batalla.Batalla; import castas.Brujo; import castas.Guerrero; import castas.Paladin; import habDeGuerrero.AumentarAtaque; import habDeGuerrero.Desgarrar; import habDeGuerrero.Ejecutar; import hechizosDeBrujo.BolaDeLaOscuridad; import hechizosDeBrujo.DisminuirAtaque; import hechizosDeBrujo.LatigazoMortal; import hechizosYHabPaladin.GolpeHeroico; import hechizosYHabPaladin.Sanar; import hechizosYHabPaladin.TormentaDivina; import mapa.BuscarImagen; //import login.Login; import personaje.Alianza; import personaje.Personaje; import personaje.PersonajeDibujable; import personajeEquipado.ConAnillo; import personajeEquipado.ConArmadura; import personajeEquipado.ConCascoDeLaMuerte; import personajeEquipado.ConEspada; import personajeEquipado.PersonajeEquipado; import razas.Elfo; import razas.Humano; import razas.Orco; public class PersonajeTest { /** * Como jugador quiero poder tener una cuenta con la cual, mediante nombre * de usuario y contraseña para poder entrar al mundo. * * @throws InterruptedException */ // @Test // public void historiaDeUsuarioNº1() { // // Login login = new Login(); // login.main(null); // } /** * 2_** Como jugador quiero poder crear un personaje pudiendo elegir la * casta que prefiera y ponerle un nombre a mi personaje. */ // @Test // public void historiaDeUsuarioNº2() { // // Jugador jugador = new Jugador("pepe", "Humano", "Brujo"); // Assert.assertEquals("pepe", jugador.getNombre()); // Assert.assertEquals(100, jugador.getPersonaje().obtenerPuntosDeSalud()); // } /** * Como jugador quiero que haya 3 razas para elegir, las cuales seran * **orco,humano u elfo**, y 3 castas que seran **guerrerro, paladin y * brujo**. */ @Test public void historiaDeUsuarioNº3() { Humano humano = new Humano(new Guerrero(), null, null); Elfo elfo = new Elfo(new Brujo(), null, null); Orco orco = new Orco(new Paladin(), null, null); Assert.assertEquals(10, elfo.calcularPuntosDeAtaque()); humano.atacar(elfo); Assert.assertEquals(75, elfo.getSalud()); orco.atacar(elfo); Assert.assertEquals(63, elfo.getSalud()); } /** * Como jugador quiero que cada raza tenga una potencia propia univoca que * la hace diferente a las otras dos razas. */ @Test public void historiaDeUsuarioNº4() { Humano humano = new Humano(new Guerrero(), null, null); Orco orco = new Orco(new Guerrero(), null, null); Elfo elfo = new Elfo(new Guerrero(), null, null); // El humano tendrá mas defensa que las otras razas Assert.assertTrue(humano.obtenerPuntosDeDefensa() > orco.obtenerPuntosDeDefensa() && humano.obtenerPuntosDeDefensa() > elfo.obtenerPuntosDeDefensa()); // El Orco tendrá mas vida que las otras razas Assert.assertTrue(orco.getSalud() > humano.getSalud() && orco.getSalud() > elfo.getSalud()); // El Orco tendrá mas poder de ataque que las otras razas Assert.assertTrue(orco.obtenerPuntosDeAtaque() > humano.obtenerPuntosDeAtaque() && orco.obtenerPuntosDeAtaque() > elfo.obtenerPuntosDeAtaque()); // El Elfo tendra mas inteligencia que las otras razas Assert.assertTrue(elfo.obtenerPuntosDeInteligencia() > humano.obtenerPuntosDeInteligencia() && elfo.obtenerPuntosDeInteligencia() > orco.obtenerPuntosDeInteligencia()); // El Elfo tendrá mas mana que las otras razas Assert.assertTrue(elfo.obtenerPuntosDeMana() > humano.obtenerPuntosDeMana() && elfo.obtenerPuntosDeMana() > orco.obtenerPuntosDeMana()); } /** * Como jugador quiero que al matar a un monstruo o un jugador, este deje * caer el item mas poderoso que tenga. */ @Test public void historiaDeUsuarioNº10() { Personaje humano = new Humano(new Guerrero(), null, null); Personaje humanoAtacado = new Humano(new Brujo(), null, null); humanoAtacado = new ConCascoDeLaMuerte(humanoAtacado); humanoAtacado = new ConEspada(humanoAtacado); humanoAtacado = new ConAnillo(humanoAtacado); while (humanoAtacado.getSalud() != 0) { humano.atacar(humanoAtacado); } String nombreDelItem[] = new String[1]; humanoAtacado = humanoAtacado .desequiparItem((PersonajeEquipado) humanoAtacado.desequiparItemConMayorPrioridad(), nombreDelItem); Assert.assertEquals("ConEspada", nombreDelItem[0]); Assert.assertEquals(0, humano.getCantidadDeItems()); Assert.assertEquals(10, humano.obtenerPuntosDeAtaque()); Assert.assertEquals(2, humanoAtacado.getCantidadDeItems()); Assert.assertEquals(14, humanoAtacado.obtenerPuntosDeDefensa()); Assert.assertEquals(25, humanoAtacado.obtenerPuntosDeAtaque()); } /** * 13_** Como jugador, quiero al ganar una batalla me sea dada una cantidad * de puntos de experiencia para subir de nivel. */ @Test public void historiaDeUsuarioNº13() { Humano humano = new Humano(new Guerrero(), null, null); Elfo elfo = new Elfo(new Brujo(), null, null); Orco orco = new Orco(new Paladin(), null, null); while (humano.estaVivo()) { orco.atacar(humano); orco.serEnergizado(); } orco.atacar(humano); while (elfo.estaVivo()) { orco.atacar(elfo); orco.serEnergizado(); } orco.atacar(elfo); // el orco mato a 2 jugadores y sube un nivel Assert.assertEquals(2, orco.getNivel()); } @Test public void queFuncionaLaAlianza() { Alianza FPV = new Alianza(); Alianza Cambiemos = new Alianza(); Personaje Macri = new Elfo(new Guerrero(), null, null); Personaje Carrio = new Elfo(new Brujo(), null, null); Personaje Cristina = new Humano(new Guerrero(), null, null); Personaje Scioli = new Humano(new Paladin(), null, null); FPV.agregarAliado(Cristina); FPV.agregarAliado(Scioli); Cambiemos.agregarAliado(Macri); Cambiemos.agregarAliado(Carrio); Batalla batalla = new Batalla(FPV, Cambiemos); batalla.batalla(); } @Test public void quePuedoAgregarYQuitarUnItem() { Personaje personaje = new Humano(new Guerrero(), null, null); personaje = new ConEspada(personaje); Assert.assertEquals(100, personaje.obtenerPuntosDeSalud()); Assert.assertEquals(15, personaje.obtenerPuntosDeAtaque()); Assert.assertEquals(10, personaje.obtenerPuntosDeDefensa()); personaje = new ConCascoDeLaMuerte(personaje); personaje = new ConArmadura(personaje); Assert.assertEquals(15, personaje.obtenerPuntosDeAtaque()); Assert.assertEquals(27, personaje.obtenerPuntosDeDefensa()); String[] nombreDelItem = new String[1]; personaje = personaje.desequiparItem((PersonajeEquipado) personaje.desequiparItemConMayorPrioridad(), nombreDelItem); Assert.assertEquals(10, personaje.obtenerPuntosDeAtaque()); Assert.assertEquals(27, personaje.obtenerPuntosDeDefensa()); Assert.assertEquals(2, personaje.getCantidadDeItems()); Assert.assertEquals("ConEspada", nombreDelItem[0]); personaje = new ConEspada(personaje); Assert.assertEquals(15, personaje.obtenerPuntosDeAtaque()); Assert.assertEquals(27, personaje.obtenerPuntosDeDefensa()); Assert.assertEquals(3, personaje.getCantidadDeItems()); // } @Test public void queBuscaLasImagenes() { BuscarImagen buscar = new BuscarImagen(); String imagen = "orcoP.png"; Assert.assertEquals(32, buscar.alto(imagen)); Assert.assertEquals(32, buscar.ancho(imagen)); String mapa = "stage2"; Assert.assertEquals(128, buscar.altoMapa(mapa)); Assert.assertEquals(96, buscar.anchoMapa(mapa)); } @Test public void queCaminaElPersonaje() { PersonajeDibujable personaje = new PersonajeDibujable("Nombre", "orcoP"); personaje.caminar(); } @Test public void quePuedoCrearHabilidades() { AumentarAtaque a = new AumentarAtaque(); Desgarrar d = new Desgarrar(); Ejecutar e = new Ejecutar(); BolaDeLaOscuridad b = new BolaDeLaOscuridad(); DisminuirAtaque di = new DisminuirAtaque(); LatigazoMortal l = new LatigazoMortal(); GolpeHeroico g = new GolpeHeroico(); Sanar s = new Sanar(); TormentaDivina t = new TormentaDivina(); } } <file_sep>package test; import org.junit.Assert; import org.junit.Test; import castas.Guerrero; import castas.Paladin; import personaje.Personaje; import personajeEquipado.ConAnillo; import personajeEquipado.ConArmadura; import personajeEquipado.ConBastonAghanim; import personajeEquipado.ConCascoDeLaMuerte; import personajeEquipado.ConEspada; import razas.Humano; import razas.Orco; public class HumanoTest { @Test public void quePuedoCrearUnGuerrero() { Personaje guerrero = new Humano(new Guerrero(),null,null); Assert.assertEquals(100, guerrero.getSalud()); Assert.assertEquals(100, guerrero.getEnergia()); Assert.assertEquals(1, guerrero.getNivel()); Assert.assertEquals(0, guerrero.getExp()); Assert.assertEquals(10, guerrero.getAtaque()); Assert.assertEquals(10, guerrero.getDefensa()); Assert.assertEquals(10, guerrero.getInteligencia()); Assert.assertEquals(0, guerrero.getMana()); Assert.assertEquals("Guerrero", guerrero.getCasta().nombreCastaElegida()); } @Test public void quePuedoEquiparlo() { Personaje guerrero = new Humano(new Guerrero(),null,null); guerrero = new ConAnillo(guerrero); // aumenta el ataque 15 pts Assert.assertEquals(10 + 15, guerrero.getAtaque()); guerrero = new ConArmadura(guerrero); // aumenta la defensa 13 pts Assert.assertEquals(10 + 13, guerrero.getDefensa()); guerrero = new ConBastonAghanim(guerrero); // aumenta el poder de // hechizo 5 pts Assert.assertEquals(5, guerrero.obtenerPuntosDeHechizos()); guerrero = new ConEspada(guerrero); // aumenta la defensa 13 pts Assert.assertEquals(10 + 15 + 5, guerrero.getAtaque()); guerrero = new ConCascoDeLaMuerte(guerrero); // aumenta la defensa 13 pts Assert.assertEquals(10 + 13 + 4, guerrero.getDefensa()); } @Test public void quePuedeAtacar() { Personaje guerrero = new Humano(new Guerrero(),null,null); Personaje orco = new Orco(new Paladin(),null,null); guerrero.atacar(orco); Assert.assertEquals(111, orco.getSalud()); Assert.assertEquals(90, guerrero.getEnergia()); } @Test public void quePuedeSerAtacado() { Personaje guerrero = new Humano(new Guerrero(),null,null); Personaje orco = new Orco(new Paladin(),null,null); orco.atacar(guerrero); Assert.assertEquals(91, guerrero.getSalud()); Assert.assertEquals(88, orco.getEnergia()); } @Test public void quePuedeHechizar() { Personaje guerrero = new Humano(new Guerrero(),null,null); Personaje orco = new Orco(new Paladin(),null,null); guerrero.setMana(37); Assert.assertTrue(guerrero.aplicarHechizo("Aumentar ataque", orco)); Assert.assertEquals(12 + 4, orco.getAtaque()); Assert.assertEquals(37 - 15, guerrero.getMana()); Assert.assertFalse(guerrero.aplicarHechizo("Desgarrar", orco)); guerrero.setMana(37); Assert.assertTrue(guerrero.aplicarHechizo("Desgarrar", orco)); Assert.assertEquals(85, orco.getSalud()); Assert.assertEquals(37 - 30, guerrero.getMana()); Assert.assertFalse(guerrero.aplicarHechizo("Ejecutar", orco)); guerrero.setMana(37); Assert.assertTrue(guerrero.aplicarHechizo("Ejecutar", orco)); Assert.assertEquals(72, orco.getSalud()); Assert.assertEquals(37 - 25, guerrero.getMana()); } } <file_sep>package hechizosDeBrujo; import personaje.HechizoOHab; import personaje.Personaje; public class BolaDeLaOscuridad extends HechizoOHab{ public BolaDeLaOscuridad(){ this.costo = 23; } @Override public void afectar(Personaje personaje,int poderDeHabilidad) { personaje.serAtacado(30+poderDeHabilidad); } } <file_sep>package razas; import castas.Casta; import personaje.Personaje; public class Elfo extends Personaje { int ataquesRecibidos; public Elfo(Casta castaElegida, String nombrePersonaje, String img){ this.maxSalud = 85; this.maxEnergia = 120; this.expMax=100; this.manaMax=80; this.salud=85; this.inteligencia=12; this.ataque=10; this.defensa=2; this.casta=castaElegida; this.energia=120; this.exp=0; this.nivel=1; this.ataquesRecibidos=0; this.mana=3; this.id=nombrePersonaje; this.img=img; this.idRaza = 2; } @Override public void despuesDeAtacar() { mana+=10; } @Override public int calcularPuntosDeAtaque() { return ataque + ataquesRecibidos + this.ataqueAfectado; } @Override public boolean puedeAtacar() { return energia >= calcularPuntosDeAtaque(); } @Override public void serAtacado(int daņo) { super.serAtacado(daņo); this.ataquesRecibidos++; } @Override public int obtenerPuntosDeDefensa() { return this.defensa; } } <file_sep>package castas; import java.util.HashMap; import java.util.Map; import personaje.HechizoOHab; import personaje.Personaje; public class Casta { protected String casta; private String habilidadCasta; protected int poderDeHabilidad; protected int idCasta; protected Map<String, HechizoOHab> hechizos = new HashMap<String, HechizoOHab>(); public void agregarHechizo(String conjuro, HechizoOHab hechizo) { this.hechizos.put(conjuro, hechizo); } public int getCantidadDeHechizos() { return 3; } public int hechizar(String conjuro, Personaje personaje, int mana, int poder) { int manaActualizado = mana - this.hechizos.get(conjuro).costoHabilidad(); if (manaActualizado >= 0) { this.hechizos.get(conjuro).afectar(personaje, this.poderDeHabilidad + poder / 2); return manaActualizado; } return mana; } public String nombreCastaElegida() { return casta; } public String nombreHabilidad() { return getHabilidadCasta(); } public int poderHabilidad() { return poderDeHabilidad; } public int getIdCasta() { return this.idCasta; } public String getHabilidadCasta() { return habilidadCasta; } public void setHabilidadCasta(String habilidadCasta) { this.habilidadCasta = habilidadCasta; } } <file_sep>package personajeEquipado; import personaje.Personaje; public class ConBastonAghanim extends PersonajeEquipado{ public ConBastonAghanim(Personaje personajeDecorado) { super(personajeDecorado); this.prioridad = 3; this.nombreDelItem = "ConBastonAghanim"; } public int calcularPuntosDeHechizos(){ return super.obtenerPuntosDeHechizos()+5; } @Override public int getCantidadDeItems() { return personajeDecorado.getCantidadDeItems()+1; } } <file_sep>package gui; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import personaje.Personaje; import personaje.PersonajeDibujable; import razas.Humano; import razas.Orco; import razas.Elfo; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JOptionPane; import com.google.gson.Gson; import cliente.Mensaje; import castas.Brujo; import castas.Guerrero; import castas.Paladin; public class CrearPersonaje extends JFrame { private JPanel elegirRaza; private Personaje personaje; private String raza; private String casta; private boolean eligio = false; private String nombrePersonaje; private Gson gson; private PersonajeDibujable personajeDibujable; private Mensaje mensaje = new Mensaje("", ""); private String entrada; private boolean seCerro = false; private Login login; private String nombreImagen; public CrearPersonaje(final String nombrePersonaje, Socket cliente, final Login login) { this.gson = new Gson(); this.nombrePersonaje = nombrePersonaje; this.login = login; setTitle("Warlords"); setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 300); elegirRaza = new JPanel(); elegirRaza.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(elegirRaza); elegirRaza.setLayout(null); final JButton btnOrco = new JButton("Orco"); final JButton btnElfo = new JButton("Elfo"); final JButton btnHumano = new JButton("Humano"); btnElfo.setBounds(155, 134, 89, 23); elegirRaza.add(btnElfo); btnHumano.setBounds(155, 179, 89, 23); elegirRaza.add(btnHumano); btnOrco.setBounds(155, 87, 89, 23); elegirRaza.add(btnOrco); btnOrco.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { raza = "orco"; eligio = true; btnHumano.setEnabled(false); btnElfo.setEnabled(false); btnOrco.setEnabled(false); } }); btnElfo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { raza = "elfo"; eligio = true; btnHumano.setEnabled(false); btnElfo.setEnabled(false); btnOrco.setEnabled(false); } }); btnHumano.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { raza = "humano"; eligio = true; btnHumano.setEnabled(false); btnElfo.setEnabled(false); btnOrco.setEnabled(false); } }); final JButton btnElegir = new JButton("Elegir"); btnElegir.setBounds(155, 213, 89, 23); elegirRaza.add(btnElegir); final JButton btnPaladin = new JButton("Paladin"); btnPaladin.setBounds(155, 121, 89, 23); elegirRaza.add(btnPaladin); btnPaladin.setVisible(false); final JButton btnGuerrero = new JButton("Guerrero"); btnGuerrero.setBounds(155, 155, 89, 23); elegirRaza.add(btnGuerrero); btnGuerrero.setVisible(false); final JButton btnBrujo = new JButton("Brujo"); btnBrujo.setBounds(155, 87, 89, 23); elegirRaza.add(btnBrujo); btnBrujo.setVisible(false); final JButton elegirCasta = new JButton("Elegir"); elegirCasta.setBounds(155, 213, 89, 23); elegirRaza.add(elegirCasta); elegirCasta.setVisible(false); final JLabel lblNombre = new JLabel("Nombre:"); lblNombre.setBounds(121, 189, 200, 14); elegirRaza.add(lblNombre); lblNombre.setVisible(false); final JLabel lblEligeUnaRaza = new JLabel("Elige una raza"); lblEligeUnaRaza.setBounds(155, 11, 142, 14); elegirRaza.add(lblEligeUnaRaza); final JLabel lblEligeUnaCasta = new JLabel("Elige una casta"); lblEligeUnaCasta.setBounds(155, 36, 162, 14); elegirRaza.add(lblEligeUnaCasta); lblEligeUnaCasta.setVisible(false); final JButton btnDeshacerRaza = new JButton("Deshacer"); btnDeshacerRaza.setBounds(155, 240, 89, 23); elegirRaza.add(btnDeshacerRaza); btnDeshacerRaza.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { eligio = false; btnHumano.setEnabled(true); btnElfo.setEnabled(true); btnOrco.setEnabled(true); } }); final JButton btnDeshacerCasta = new JButton("Deshacer"); btnDeshacerCasta.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { eligio = false; btnPaladin.setEnabled(true); btnBrujo.setEnabled(true); btnGuerrero.setEnabled(true); } }); btnDeshacerCasta.setBounds(155, 247, 89, 23); elegirRaza.add(btnDeshacerCasta); btnDeshacerCasta.setVisible(false); btnElegir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!eligio) return; // else // abrirJuego(); btnElegir.setVisible(false); btnHumano.setVisible(false); btnElfo.setVisible(false); btnOrco.setVisible(false); lblEligeUnaRaza.setVisible(false); btnDeshacerRaza.setVisible(false); btnDeshacerCasta.setVisible(true); lblNombre.setVisible(true); lblNombre.setText("Nombre de personaje: " + nombrePersonaje); if (raza.compareTo("orco") != 0) btnBrujo.setVisible(true); btnGuerrero.setVisible(true); btnPaladin.setVisible(true); elegirCasta.setVisible(true); lblEligeUnaCasta.setVisible(true); } }); btnPaladin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { casta = "paladin"; btnPaladin.setEnabled(false); btnGuerrero.setEnabled(false); btnBrujo.setEnabled(false); } }); btnGuerrero.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { casta = "guerrero"; btnPaladin.setEnabled(false); btnGuerrero.setEnabled(false); btnBrujo.setEnabled(false); } }); btnBrujo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { casta = "brujo"; btnPaladin.setEnabled(false); btnGuerrero.setEnabled(false); btnBrujo.setEnabled(false); } }); elegirCasta.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { switch (raza) { case "humano": switch (casta) { case "paladin": personaje = new Humano(new Paladin(), nombrePersonaje, "humanoP"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "humanoP"); nombreImagen = "humanoP"; break; case "guerrero": personaje = new Humano(new Guerrero(), nombrePersonaje, "humanoG"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "humanoG"); nombreImagen = "humanoG"; break; case "brujo": personaje = new Humano(new Brujo(), nombrePersonaje, "humanoB"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "humanoB"); nombreImagen = "humanoB"; break; default: break; } break; case "orco": switch (casta) { case "paladin": personaje = new Orco(new Paladin(), nombrePersonaje, "orcoP"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "orcoP"); nombreImagen = "orcoP"; break; case "guerrero": personaje = new Orco(new Guerrero(), nombrePersonaje, "orcoG"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "orcoG"); nombreImagen = "orcoG"; break; default: break; } break; case "elfo": switch (casta) { case "paladin": personaje = new Elfo(new Paladin(), nombrePersonaje, "elfoP"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "elfoP"); nombreImagen = "elfoP"; break; case "guerrero": personaje = new Elfo(new Guerrero(), nombrePersonaje, "elfoG"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "elfoG"); nombreImagen = "elfoG"; break; case "brujo": personaje = new Elfo(new Brujo(), nombrePersonaje, "elfoB"); personajeDibujable = new PersonajeDibujable(nombrePersonaje, "elfoB"); nombreImagen = "elfoB"; break; default: break; } break; default: break; } try { enviarMensaje("guardarPersonaje"); leerRespuesta(); enviarMensaje("guardarPersonajeDibujable"); leerRespuesta(); } catch (IOException e1) { JOptionPane.showMessageDialog(null, "Error al guardar personaje en la BD", "Error", JOptionPane.ERROR_MESSAGE); } login.setPersonaje(login.obtenerPersonaje()); login.setPersonajeDibujable(login.obtenerPersonajeDibujable()); login.abrirJuego(nombrePersonaje); } }); } public boolean seCerro() { return seCerro; } public Personaje obtenerPersonaje() { return personaje; } public PersonajeDibujable obtenerPersDibujable() { return personajeDibujable; } // metodos para solicitar registro de los personajes del jugador public void leerRespuesta() throws IOException { String entrada; entrada = login.getDataInputStream().readUTF(); mensaje = gson.fromJson(entrada, Mensaje.class); } public void enviar(Mensaje mensj) throws IOException { String msg = gson.toJson(mensj); login.getDataOutPutStream().writeUTF(msg); login.getDataOutPutStream().flush(); } public void enviarMensaje(String nombreMensaje) throws IOException { if (nombreMensaje.equals("guardarPersonajeDibujable")) { String json = gson.toJson(personajeDibujable); mensaje.cambiarMensaje(nombreMensaje, json); enviar(mensaje); } if (nombreMensaje.equals("guardarPersonaje")) { ArrayList<String> personaje = new ArrayList<>(); personaje.add(this.personaje.getID()); personaje.add("" + this.personaje.getIdRaza()); personaje.add("" + this.personaje.getCasta().getIdCasta()); personaje.add("" + this.personaje.getNivel()); personaje.add("" + this.personaje.getExp()); personaje.add("" + this.personaje.getSalud()); personaje.add("" + this.personaje.getEnergia()); personaje.add("" + this.personaje.getAtaque()); personaje.add("" + this.personaje.getDefensa()); personaje.add("" + this.personaje.getMana()); String json = gson.toJson(personaje); mensaje.cambiarMensaje(nombreMensaje, json); enviar(mensaje); } } } <file_sep>package personajeEquipado; import personaje.Personaje; public class ConAnillo extends PersonajeEquipado{ public ConAnillo(Personaje personajeDecorado) { super(personajeDecorado); this.prioridad = 2; this.nombreDelItem = "ConAnillo"; } @Override public int obtenerPuntosDeAtaque() { return super.obtenerPuntosDeAtaque()+15; } @Override public int getCantidadDeItems() { return personajeDecorado.getCantidadDeItems()+1; } } <file_sep>package hechizosDeBrujo; import personaje.HechizoOHab; import personaje.Personaje; public class DisminuirAtaque extends HechizoOHab { public DisminuirAtaque(){ this.costo = 15; } @Override public void afectar(Personaje personaje ,int poderDeHabilidad) { personaje.disminuirAtaque(6); } } <file_sep>package mapa; import java.awt.Image; import personaje.PersonajeDibujable; public interface Dibujable extends Comparable<Dibujable>{ public String getID(); public int getPosicionX(); public int getPosicionY(); public int getAncho(); public int getAlto(); public Image getImagen(); } <file_sep>package razas; import castas.Casta; import personaje.Personaje; public class Orco extends Personaje{ private int cantidadDeAtaques; public Orco(Casta castaElegida, String nombrePersonaje, String img){ this.maxSalud = 120; this.maxEnergia = 100; this.salud=120; this.ataque=12; this.manaMax=80; this.defensa=3; this.inteligencia=5; this.casta=castaElegida; this.energia=100; this.exp=0; this.nivel=1; this.cantidadDeAtaques=0; this.mana=0; this.expMax=100; this.id=nombrePersonaje; this.img=img; this.idRaza = 3; } @Override public void despuesDeAtacar() { cantidadDeAtaques++; mana+=10; } @Override public int calcularPuntosDeAtaque() { return ataque + cantidadDeAtaques; } @Override public boolean puedeAtacar() { return energia >= calcularPuntosDeAtaque(); } @Override public int obtenerPuntosDeDefensa() { return this.defensa; } } <file_sep>package habDeGuerrero; import personaje.HechizoOHab; import personaje.Personaje; public class AumentarAtaque extends HechizoOHab{ public AumentarAtaque(){ this.costo = 15; } @Override public void afectar(Personaje personaje,int poderDeHabilidad) { personaje.aumentarAtaque(4); } } <file_sep>package gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import castas.Paladin; import personaje.Personaje; import personaje.PersonajeDibujable; import razas.Elfo; public class Juego extends JFrame { /** * */ private static final long serialVersionUID = 1L; public Juego(String nombre) throws UnknownHostException, IOException { setTitle("Juego 2D con Java "); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); setResizable(false); add(new Jugador(nombre)); setVisible(true); } public Juego(Socket sock, String id, PersonajeDibujable p, Personaje pb) throws UnknownHostException, IOException { setTitle("Juego 2D con Java "); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800, 600); setLocationRelativeTo(null); this.setLayout(new BorderLayout()); setResizable(false); JPanel pane = new JPanel(); pane.setBounds(0, 600, 800, 100); pane.setBackground(Color.GREEN); pane.setVisible(true); pane.setFocusable(true); pane.setSize(800, 200); pane.setMinimumSize(new Dimension(800, 200)); JButton boton = new JButton("boton"); boton.setBackground(Color.BLUE); boton.setBounds(0, 0, 100, 100); boton.setVisible(true); pane.add(boton); Jugador ju = new Jugador(sock, id, p, pb); // ju.setSize(800, 600); add(ju); // this.add(pane, BorderLayout.SOUTH); // add(boton); setVisible(true); } public static void main(String args[]) throws UnknownHostException, IOException { // new Juego(2); // new Juego(3); Socket cliente = new Socket("localhost", 2028); String id = "jugador1"; String id2 = "jugador2"; PersonajeDibujable personajeDibujable1 = new PersonajeDibujable(id, "elfoP"); Personaje personaje1 = new Elfo(new Paladin(), id, "elfoP"); new Juego(cliente, id, personajeDibujable1, personaje1); //PersonajeDibujable personajeDibujable2 = new PersonajeDibujable(id2, "elfoP"); //Personaje personaje2 = new Elfo(new Paladin(), id2, "elfoP"); //new Juego(cliente, id2, personajeDibujable2, personaje2); } }
efdd3b169cb9e9489c0aa1cf299b790e27fa2ea5
[ "Markdown", "Java" ]
30
Java
GDVillalba/Juego-Java-JRPG
173258b785172ba425e3081b2d65e9803cc305c6
bfca030cc5eae05658567071993c3ff357be1b52
refs/heads/master
<repo_name>tomusdrw/SortedList<file_sep>/tests/SortedList-tests.js QUnit.specify("eu.blacksoft.js.sortedlist", function() { describe("With default comparator", function() { var cut = null; before(function() { cut = SortedList.create(); }); describe("intial state", function() { it("should be empty", function() { // given // when // then assert(cut.isEmpty()).isTrue(); assert(cut.size()).isEqualTo(0); }); given('peekMin', 'popMin', 'peekMax', 'popMax').// it('invocation should return null', function(funcName) { // when var actual = cut[funcName](); // then assert(actual).isNull(); }); it('should return empty array', function() { // given // when var arr = cut.getArray(); // then assert(arr).isSameAs([]); }); }); describe("with one element", function() { var element = "a"; before(function() { cut.push(element); }); it("should increase size", function() { // given // when // then assert(cut.isEmpty()).isFalse(); assert(cut.size()).isEqualTo(1); }); given('peekMin', 'popMin', 'peekMax', 'popMax').// it('invocation should return same element', function(funcName) { // when var actual = cut[funcName](); // then assert(actual).isEqualTo(element); }); it('should contain pushed element', function() { // when var actual = cut.contains(element); // then assert(actual).isTrue(); }); given(5, 'b', 'c', [1], {}, 0).// it('should not contain element', function(element) { // when var actual = cut.contains(element); // then assert(actual).isFalse(); }); it('should clear and become empty', function() { // when cut.clear(); // then assert(cut.isEmpty()).isTrue(); assert(cut.size()).isEqualTo(0); }); it('should remove element', function() { // when var actual = cut.remove(element); // then assert(actual).isTrue(); assert(cut.isEmpty()); }); it('should return array with element', function() { // when var arr = cut.getArray(); // then assert(arr).isSameAs([element]); }); }); describe("empty values", function() { given("pushAll", "push", "contains", "remove").// it('invocation should throw exception', function(func) { // given var empty = null; // when assert(function() { cut[func](empty); }).throwsException(); }); given("pushAll", "push", "contains", "remove").// it('invocation should throw exception', function(func) { // given var empty = undefined; // when assert(function() { cut[func](empty); }).throwsException(); }); }); describe("pushing multiple elements", function() { given([[6, 2, 3, 41, 3]], [[1, 2, 3]], [[3, 2, 1]], [["a", "f", "d", "b"]], [["2", 1, 3]]).// it('should push all elements', function(elements) { // given var sorted = elements.slice(0).sort(cut._cmp); // when cut.pushAll(elements); // then assert(cut.size()).isEqualTo(elements.length); assert(cut.peekMin()).isEqualTo(sorted[0]); assert(cut.peekMax()).isEqualTo(sorted[sorted.length - 1]); assert(cut.getArray()).isSameAs(sorted); elements.forEach(function(e) { assert(cut.contains(e)).isTrue("Contains " + e); }); }); }); describe("Removing elements", function() { var elements = [5, 3, 4, 2, 1, 15]; before(function() { cut.pushAll(elements); }); it('should not remove non-existing element', function() { // given var sorted = elements.slice(0).sort(cut._cmp); // when var actual = cut.remove(12345); // then assert(actual).isFalse(); assert(cut.getArray()).isSameAs(sorted); }); given(5, 3, 4, 2, 1, 15).// it('should remove element', function(toRemove2) { var toRemove = toRemove2 + 0; // some weird pavlov conversion? // given var sortedAndRemoved = elements.slice(0).sort(cut._cmp); sortedAndRemoved.splice(sortedAndRemoved.indexOf(toRemove), 1); // when var actual = cut.remove(toRemove); // then assert(actual).isTrue(); assert(cut.contains(toRemove)).isFalse(); assert(cut.getArray()).isSameAs(sortedAndRemoved); }); }); }); }); <file_sep>/README.md SortedList implementation for JavaScript based on array and mostly native array functions. There is a possiblity to specify your own comparator - default comparator works well for Numbers and Strings. Complexity of functions (without `splice` complexity): * **peekMin/popMin** `O(1)` * **peekMax/popMax** `O(1)` * **size** `O(1)` * **isEmpty** `O(1)` * **pushAll(k)** `O(k*log(n))` * **push** `O(log(n))` * **contains** `O(log(n))` * **remove** `O(log(n))` * **getArray** `O(1)`
c538beeaf336bb4ce268dcbe4e62b7653230f846
[ "JavaScript", "Markdown" ]
2
JavaScript
tomusdrw/SortedList
f87e283724310daa5a151341c87805785454947d
55c0864155df199afe2a7170749da44ea1d0829d
refs/heads/main
<file_sep>import click from pypsrp.client import Client from pypsrp.powershell import PowerShell, RunspacePool DUMMY_HASH = "00000000000000000000000000000000" @click.command() @click.option("--cmd", required=True) @click.option("--host", required=True) @click.option("--username", required=True) @click.option("--lm_hash", default=DUMMY_HASH) @click.option("--nt_hash", default=DUMMY_HASH) @click.option("--use_ssl", default=False) @click.option("--timeout", default=3, type=int) def run_remote_cmd( cmd, host, username, lm_hash=DUMMY_HASH, nt_hash=DUMMY_HASH, use_ssl=True, timeout=3, ): formatted_credentials = ( f"Username: {username}, LM Hash: {lm_hash}, NT Hash: {nt_hash}" ) try: client = connect(host, username, lm_hash, nt_hash, use_ssl, timeout) print(f"Authentication succeeded -- {formatted_credentials}") except Exception as ex: print(f"Authentication failed -- {formatted_credentials}") print(ex) else: execute_cmd(cmd, client) def connect(host, username, lm_hash, nt_hash, use_ssl=True, timeout=3): # The pypsrp library requires LM or NT hashes to be formatted like "LM_HASH:NT_HASH" # # Example: # If your LM hash is 1ec78eb5f6edd379351858c437fc3e4e and your NT hash is # 79a760336ad8c808fee32aa96985a305, then you would pass # "1ec78eb5f6edd379351858c437fc3e4e:79a760336ad8c80<PASSWORD>" as the # `password` parameter to pypsrp. # # pypsrp will parse this string and automatically use the appropriate hash # for NTLM authentication. # # If you only have one of the two hashes, this script will automatically # populate the other hash with zeros. formatted_ntlm_hashes = f"{lm_hash}:{nt_hash}" client = Client( host, username=username, password=<PASSWORD>, cert_validation=False, ssl=use_ssl, auth="ntlm", encryption="auto", connection_timeout=timeout, ) # Execute a command to validate that authentication was actually successful. This # will raise an exception if authentication failed. client.execute_cmd("dir") return client def execute_cmd(cmd, client): # SECURITY: Watch out! No attempt is made to protect against command # injection. print(f"Running command: {cmd}") stdout, stderr, rc = client.execute_cmd(cmd) print(f"STDOUT:\n{stdout}\n\n") print(f"STDERR:\n{stderr}\n\n") print(f"RETURN CODE: {rc}") if __name__ == "__main__": run_remote_cmd() <file_sep>certifi==2021.5.30 cffi==1.14.6 charset-normalizer==2.0.6 click==8.0.1 cryptography==3.4.8 idna==3.2 pycparser==2.20 pypsrp==0.5.0 pyspnego==0.2.0 requests==2.26.0 six==1.16.0 urllib3==1.26.7 <file_sep># PowerShell Pass-the-Hash ## Disclaimer The contents of this repository are for educational purposes. Do not use this information to access any system without the express written permission of the system's owner, such as during a red team activity. The author is not liable for any damage, direct or indirect, caused by the information contained in this repository. ## Description This repository contains a simple, cross-platform, proof-of-concept utility for the automation of [pass-the-hash](https://en.hackndo.com/pass-the-hash/) attacks against servers with PowerShell Remoting enabled. ## Why did you write this utility? I couldn't find any example code written in Python that executes a pass-the-hash attack over PowerShell Remoting. The best Python library I've been able to find for using PowerShell Remoting is [pypsrp](https://pypi.org/project/pypsrp/). pypsrp allows you to interact with PowerShell Remoting programmatically from both Windows and Linux. It's not obvious how to use pypsrp to execute a pass-the-hash attack. This utility serves as an example that red teamers can use to write their own Python code to automate pass-the-hash attacks. Simply put, this is the magic that makes everything work: ```python def connect(host, username, lm_hash, nt_hash, use_ssl=True, timeout=3): # The pypsrp library requires LM or NT hashes to be formatted like "LM_HASH:NT_HASH" # # Example: # If your LM hash is 1ec78eb5f6edd379351858c437fc3e4e and your NT hash is # 79a760336ad8c808fee32aa96985a305, then you would pass # "<PASSWORD>4e:79a760336ad8c808fee32aa96985a305" as the # `password` parameter to pypsrp. # # pypsrp will parse this string and automatically use the appropriate hash # for NTLM authentication. # # If you only have one of the two hashes, this script will automatically # populate the other hash with zeros. formatted_ntlm_hashes = f"{lm_hash}:{nt_hash}" ``` [See code in context](https://github.com/mssalvatore/powershell-pth/blob/e8bd82e3120b9ecec9f19a9d14451831640dc6b0/powershell-pth.py#L39-L53) ## How should I use this utility? This utility is primarily intended to be an example you can use to write your own tools. However, it does provide basic functionality. If you have a target host, username, and a hash, you can use this utility to try to gain access to the target (see [disclaimer](#disclaimer)). ## How do I run powershell-pth.py Install the necessary Python dependencies: ``` $ pip install -r requirements.txt ``` Invoke the script with `python`. Example: ``` $ python powershell-pth.py --cmd dir --host 10.0.0.30 --username test --nt_hash 10f017bbc08a8d415d60299c06f4869f Authentication succeeded -- Username: test, LM Hash: 00000000000000000000000000000000, NT Hash: 10f017bbc08a8d415d60299c06f4869f Running command: dir STDOUT: Volume in drive C has no label. Volume Serial Number is 5719-64DC Directory of C:\Users\test 09/24/2021 08:44 AM <DIR> . 09/24/2021 08:44 AM <DIR> .. 08/20/2021 07:37 AM <DIR> Contacts 08/20/2021 07:37 AM <DIR> Desktop 09/24/2021 08:44 AM <DIR> Documents 09/01/2021 08:28 AM <DIR> Downloads 08/20/2021 07:37 AM <DIR> Favorites 08/20/2021 07:37 AM <DIR> Links 08/20/2021 07:37 AM <DIR> Music 08/20/2021 07:37 AM <DIR> Pictures 08/20/2021 07:37 AM <DIR> Saved Games 08/20/2021 07:37 AM <DIR> Searches 08/20/2021 07:37 AM <DIR> Videos 0 File(s) 0 bytes 13 Dir(s) 31,387,150,750 bytes free STDERR: RETURN CODE: 0 ``` `powershell-pth.py` can be run with an NT hash (`--nt_hash`), an LM hash (`--lm_hash`), or both. Run `python powershell-pth.py --help` for more options. ``` $ python powershell-pth.py --help Usage: powershell-pth.py [OPTIONS] Options: --cmd TEXT [required] --host TEXT [required] --username TEXT [required] --lm_hash TEXT --nt_hash TEXT --use_ssl BOOLEAN --timeout INTEGER --help Show this message and exit. ```
5269bb27adc994b9e9a497d7770bf3e988df7771
[ "Markdown", "Python", "Text" ]
3
Python
iNoSec2/powershell-pth
df22e365e2e60dfc958e127ab71ed257da36bc7b
133a3de5ffc04d0e4f60208a559a566a5c94006e
refs/heads/main
<repo_name>bentzlec/CS362-HW3<file_sep>/connor_bentzley_leap_year_no_error_handle.py import time year = int(input("What year do you want to check? Enter: ")) if (year % 4 == 0) and (year % 100 != 0): print(year, " is a leap year") elif (year % 400 == 0): print(year, " is a leap year") else: print(year, " is not a leap year") time.sleep(50)<file_sep>/README.md # CS362-HW3 ![Flowchart for Leap-Year Program](https://github.com/bentzlec/CS362-HW3/blob/main/Leap_Year_Flowchart.PNG)
c23e6f4e813f6355bd823379a08c3825eb20a084
[ "Markdown", "Python" ]
2
Python
bentzlec/CS362-HW3
b31cf565e85e09e03af06a19e25fc7529c862a46
6bda7cead5a5843c59a59122efde38533c80f0f5
refs/heads/master
<file_sep><?php session_start(); //require_once __DIR__ . '/src/Facebook/autoload.php'; require_once '../config/config.php'; require_once '../src/Facebook/autoload.php'; /** * facebook login , poting functions are here * * @author S.A.K.I */ class PostFacebook { private $facebook = null; private $helper = null; private $accessToken = null; private $user_message = null; private $permissions = ['publish_actions']; /** * initialise facebook object using credentials * @param null */ public function __construct() { $this->facebook = new Facebook\Facebook([ 'app_id' => fb_app_id, 'app_secret' => fb_app_secret, 'default_graph_version' => fb_default_graph_version, ]); $this->helper = $this->facebook->getRedirectLoginHelper(); } /** * relevent post is received * @param type $msg */ public function functionPost($msg) { $this->user_message = $msg; $this->initialize(); } /** * get acces token and set to session variable */ private function initialize() { try { $_SESSION['facebook_access_token']= access_tokan; if (isset($_SESSION['facebook_access_token'])) { $this->accessToken = $_SESSION['facebook_access_token']; echo '1'; } else { $this->accessToken = $this->helper->getAccessToken(); echo $this->accessToken; } } catch (Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch (Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } /** * access token management */ if (isset($this->accessToken)) { if (isset($_SESSION['facebook_access_token'])) { $this ->facebook ->setDefaultAccessToken($_SESSION['facebook_access_token']); } else { // getting short-lived access token $_SESSION['facebook_access_token']= (string) $this->accessToken; // OAuth 2.0 client handler $oAuth2Client = $this->facebook->getOAuth2Client(); // Exchanges a short-lived access token for a long-lived one $longLivedAccessToken = $oAuth2Client ->getLongLivedAccessToken($_SESSION['facebook_access_token']); $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken; // setting default access token to be used in script $this ->facebook ->setDefaultAccessToken($_SESSION['facebook_access_token']); } // redirect the user back to the same page if it has "code" GET variable if (isset($_GET['code'])) { header('Location: ./'); } //post is done $post = $this->facebook->post('/me/feed', array('message' => $this->user_message)); echo "successfully posted to facebook"; } else { // if user dosnt loged in and dosent accept the application $loginUrl = $this->helper->getLoginUrl(base_url."home.php", $this->permissions); echo '<a href="' . $loginUrl . '">it seems you' . ' are first time to use this app' . ' click this link once to loging to' . ' facebook and accept the app </a>'; } } } <file_sep> <?php /** * controller class * @author <NAME> a.k.a S.A.K.I */ $type_val = $_POST['fb_type']; // remove text area value unset($_POST['fb_type']); $arvm = $_POST; $arob = array( 'fbb' => 'postFacebook', 'tww' => 'postTwiter', ); foreach ($arvm as $value) { //call relevent files require_once '../models/'.$arob[$value].'.php'; // ceate object from selected media $arob_ob = new $arob[$value]; $arob_ob->functionPost($type_val); } <file_sep><?php require_once 'postFacebook.php'; $loginUrl = $this->helper->getLoginUrl(base_url."home.php", $this->permissions); echo '<a href="' . $loginUrl . '">it seems you' . ' are first time to use this app' . ' click this link once to loging to' . ' facebook and accept the app </a>'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ <file_sep><!DOCTYPE html> <?php require_once '/config/config.php';?> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div style="text-align: center"> <form action="<?php echo base_url?>controller/commn_controller.php" method="post" onsubmit="return test()"> <input type="checkbox" value="fbb" id="facebook" name="fb"> &ensp;&ensp; <label>facebook</label> <input type="checkbox" value="tww" id="tweeter" name="tw"> &ensp;&ensp; <label> Twitter</label> <br> <br> <textarea id="post" name="fb_type" value="test"></textarea> <input type="submit" > </form> </div> <script> function test() { var text = document.getElementById('post').value; // vat fb = document.getElementById('facebook'); // var tw = document.getElementById('tweeter') if(text == "") { alert ("you cannot post empty status"); return false; }else if (document.getElementById('facebook').checked === false || document.getElementById('tweeter')=== false) { alert ("plaese select one of the sociel media to post your message"); return false; } else { if(confirm('Are you sure ?')=== true) { return true; }else { return false; }; } } </script> </body> </html> <file_sep><?php require_once("/twitteroauth-master/autoload.php"); use Abraham\TwitterOAuth\TwitterOAuth; require_once './config.php'; /** * twitter login , poting functions are here * * @author S.A.K.I */ class PostTwiter { public function __construct() { } public function functionPost($msg) { // define twitter object $tw = new TwitterOAuth(consumer_key, consumer_secret, access_token, access_token_secret); $content = $tw->get("account/verify_credentials"); // check length if(strlen($msg) > 140) { $status = substr($msg, 0, 140); } //post $tw->post('statuses/update', array( 'status' => $msg )); echo "successfully posted to twitter"; } } <file_sep><?php // facebook credentials here define('fb_app_id', '554586574724824'); define('fb_app_secret', '<KEY>'); define('fb_default_graph_version', 'v2.6'); define('base_url',"http://localhost/Social_app/"); define ('access_tokan','<KEY>'); // twiter credentials here define('consumer_key',"QFLRF1Lsp31z9OeftpUqcMgTX"); define('consumer_secret',"<KEY>"); define('access_token',"<KEY>"); define('access_token_secret',"<KEY>");
aae66c95cf0f1b0eac8b4216bc03fc7aaad2b500
[ "PHP" ]
6
PHP
vishvaratnayake1/SocialPosting
344075d928916c68e84be8da117424058b7f7dc5
dc06593e30d4f5e4f5a2de933e32627392bf78b9
refs/heads/master
<file_sep>""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # YOUR CODE HERE fhand = open('foo.txt') for line in fhand: print(line) fhand.close() # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain # YOUR CODE HERE fhand2 = open('bar.txt', 'w') fhand2.write('Arbitrary text\n') fhand2.write('Another line of text\n') fhand2.write('Sure why not\n') fhand2.close() fhand3 = open('bar.txt') print(fhand3.read()) <file_sep>""" The Python standard library's 'calendar' module allows you to render a calendar to your terminal. https://docs.python.org/3.6/library/calendar.html Write a program that accepts user input of the form `14_cal.py month [year]` and does the following: - If the user doesn't specify any input, your program should print the calendar for the current month. The 'datetime' module may be helpful for this. - If the user specifies one argument, assume they passed in a month and render the calendar for that month of the current year. - If the user specifies two arguments, assume they passed in both the month and the year. Render the calendar for that month and year. - Otherwise, print a usage statement to the terminal indicating the format that your program expects arguments to be given. Then exit the program. """ import sys import calendar from datetime import datetime def rules(): print('Include a month to see that calendar\nInclude a month and year for years other than 2020\n') def show_calendar(args): now = datetime.now() if len(args) > 2: if test_month(args[1]) and test_year(args[2]): month = int(args[1]) year = int(args[2]) else: return False elif len(args) == 2: if test_month(args[1]): month = int(args[1]) year = now.year else: return False else: month = now.month year = now.year cal = calendar.TextCalendar(firstweekday=0) print(cal.formatmonth(year, month, w=0, l=0)) return True def test_month(month): if not month.isdigit() or int(month) > 12: return False return True def test_year(year): if not year.isdigit(): return False return True # main program if not show_calendar(sys.argv): rules() <file_sep># Get user number print("Gimme Number") # user_input = 300000 user_input = input() # Find highest prime that could be a factor # highest_val = int(math.sqrt(int(user_input))//1) # highest_val = user_input # Create Sieve primes = [2, 3, 5, 7] sieve = [x for x in range(int(user_input)+1) if x > 1 and x % 2 != 0 and x % 3 != 0 and x % 5 != 0 and x % 7 != 0] # Process Sieve while len(sieve) > 0: new_prime = sieve.pop(0) primes.append(new_prime) for x in range(int(user_input)+1//new_prime): if new_prime*x in sieve: sieve.remove(new_prime*x) # print(highest_val, sieve, primes) print(primes) if int(user_input) in primes: print("PRIME!") else: print("NOT PRIME!") <file_sep>import math # Get user number while True: print("Gimme Number\n") user_input = input() if user_input == "q": break # Find highest prime that could be a factor highest_val = int(math.sqrt(int(user_input))//1)+1 prime = False for x in range(2, highest_val): # print("vals", user_input, x, int(user_input) % x) if int(user_input) % x == 0: prime = True print("HV", highest_val, prime) if not prime: print("PRIME!\n") else: print("NOT PRIME!\n")
bf82ff829b177ac4c8acf00d8e6ec96b34522726
[ "Python" ]
4
Python
H4rliquinn/Intro-Python-I
651590243ceaad6c64f4e93ee7e7c41542c7e5c2
ff8489f586e70450dd3be4e1250e1bcfb3e8a359
refs/heads/master
<repo_name>AllyTally/CPP-Input-system<file_sep>/Input/input.cpp // The actual input handling #include "input.h" #include <SDL.h> // SDL #include <SDL_image.h> // SDL_Image #include <SDL_ttf.h> // SDL_ttf #include <string> #include <sstream> #include <vector> #include <iostream> // utf8::unchecked::distance(str.begin(), str.end()) - leo namespace input { bool taking_input; int current_scroll; bool selecting; bool cursor_spawn_up; std::vector<std::string>* current_text; std::vector<cursor> cursors; void Init() { taking_input = false; current_scroll = 0; } void StartInput(std::vector<std::string> *text) { current_text = text; if (current_text->size() == 0) { current_text->push_back(""); } if (cursors.size() == 0) { cursor temp; temp.position = 0; temp.line = 0; temp.highest_position = 0; cursors.push_back(temp); } taking_input = true; SDL_StartTextInput(); } void Logic() { if (!taking_input) return; } void InsertText(std::string text) { for (int i = 0; i < (int) cursors.size(); i++) { // For all cursors... std::stringstream string_stream(text); // Create a stringstream for the text we're inserting std::string output; // We'll need the output later while (std::getline(string_stream, output)) { // Iterate through all lines, output.erase(std::remove(output.begin(), output.end(), '\r'), output.end()); // Strip \r... dammit Windows. (*current_text)[cursors[i].line].insert(cursors[i].position, output); // Insert the current line of text into our text cursors[i].position += output.length(); // Update cursor position if (!string_stream.eof()) { // If we haven't hit the end of the file, InsertNewlineSingleCursor(i); // Insert a newline } } cursors[i].highest_position = cursors[i].position; // Update highest_position } } void InsertNewlineSingleCursor(int i) { for (int j = 0; j < (int)cursors.size(); j++) { // For all cursors... if (cursors[j].line >= cursors[i].line + 1) { cursors[j].line++; // Shift the cursors which are after the newline } } std::string first_part = (*current_text)[cursors[i].line].substr(0, cursors[i].position); std::string second_part = (*current_text)[cursors[i].line].substr(cursors[i].position, std::string::npos); (*current_text)[cursors[i].line] = first_part; (*current_text).insert((*current_text).begin() + cursors[i].line + 1, second_part); cursors[i].line++; cursors[i].position = 0; cursors[i].highest_position = 0; } void InsertNewline() { // The user pressed enter! for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... InsertNewlineSingleCursor(i); } } void SelectAll() { selecting = true; cursors.resize(1); cursors[0].started_selection_position = 0; cursors[0].started_selection_line = 0; cursors[0].line = (*current_text).size() - 1; cursors[0].position = (*current_text)[cursors[0].line].size(); } int CheckIfShiftHeld() { if (SDL_GetModState() & KMOD_SHIFT) { if (!selecting) { for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... cursors[i].started_selection_position = cursors[i].position; cursors[i].started_selection_line = cursors[i].line; } selecting = true; } } else { if (selecting) { selecting = false; return true; } } return false; } void MoveCursorUp() { if ((SDL_GetModState() & (KMOD_ALT)) && (SDL_GetModState() & (KMOD_SHIFT))) { if (cursors.size() == 1 || cursor_spawn_up) { cursor_spawn_up = true; cursor temp = cursors[0]; cursors.push_back(temp); } if (cursors[0].line > 0) cursors[0].line--; cursors[0].position = cursors[0].highest_position; if (cursors[0].position > (*current_text)[cursors[0].line].length()) cursors[0].position = (*current_text)[cursors[0].line].length(); return; } bool reset = CheckIfShiftHeld(); // Only returns true if you don't hold shift if (!selecting) cursors.resize(1); if (reset && (cursors[0].line > cursors[0].started_selection_line)) { cursors[0].line = cursors[0].started_selection_line; } for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... if (cursors[i].line > 0) cursors[i].line--; cursors[i].position = cursors[i].highest_position; if (cursors[i].position > (*current_text)[cursors[i].line].length()) cursors[i].position = (*current_text)[cursors[i].line].length(); } } void MoveCursorDown() { if ((SDL_GetModState() & (KMOD_ALT)) && (SDL_GetModState() & (KMOD_SHIFT))) { if (cursors.size() == 1 || !cursor_spawn_up) { cursor_spawn_up = false; cursor temp = cursors[0]; cursors.push_back(temp); } if (cursors[0].line < (*current_text).size() - 1) cursors[0].line++; cursors[0].position = cursors[0].highest_position; if (cursors[0].position > (*current_text)[cursors[0].line].length()) cursors[0].position = (*current_text)[cursors[0].line].length(); return; } bool reset = CheckIfShiftHeld(); // Only returns true if you don't hold shift if (!selecting) cursors.resize(1); if (reset && (cursors[0].line < cursors[0].started_selection_line)) { cursors[0].line = cursors[0].started_selection_line; } for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... if (cursors[i].line < (*current_text).size() - 1) cursors[i].line++; cursors[i].position = cursors[i].highest_position; if (cursors[i].position > (*current_text)[cursors[i].line].length()) cursors[i].position = (*current_text)[cursors[i].line].length(); } } void MoveCursorLeft() { bool reset = CheckIfShiftHeld(); // Only returns true if you don't hold shift if (!selecting) cursors.resize(1); if (reset) { if (cursors[0].position > cursors[0].started_selection_position) { cursors[0].position = cursors[0].started_selection_position; cursors[0].highest_position = cursors[0].position; } return; } for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... if (cursors[i].position > 0) { cursors[i].position--; cursors[i].highest_position = cursors[0].position; } else { if (cursors[i].line > 0) { cursors[i].line--; cursors[i].position = (*current_text)[cursors[i].line].length(); cursors[i].highest_position = cursors[i].position; } } } } void MoveCursorRight() { bool reset = CheckIfShiftHeld(); // Only returns true if you don't hold shift if (!selecting) cursors.resize(1); if (reset) { if (cursors[0].position < cursors[0].started_selection_position) { cursors[0].position = cursors[0].started_selection_position; cursors[0].highest_position = cursors[0].position; } return; } for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... if (cursors[i].position < (*current_text)[cursors[i].line].length()) { cursors[i].position++; cursors[i].highest_position = cursors[i].position; } else { if (cursors[i].line < (*current_text).size() - 1) { cursors[i].line++; cursors[i].position = 0; cursors[i].highest_position = 0; } } } } std::string GetSelectedText(int cursor) { rect positions = ReorderSelectionPositions(cursor); if (positions.y == positions.y2) { return (*current_text)[positions.y].substr(positions.x, positions.x2 - positions.x); } std::string return_string; return_string += (*current_text)[positions.y].substr(positions.x, std::string::npos); // Get the selected part of the first line return_string += "\n"; for (int j = positions.y + 1; j < positions.y2; j++) { return_string += (*current_text)[j] + "\n"; } return_string += (*current_text)[positions.y2].substr(0, positions.x2); // Get the selected part of the last line return return_string; } std::string GetAllSelectedText() { std::string builder; for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... builder += GetSelectedText(i); if (i != cursors.size() - 1) { builder += "\n"; } } return builder; } void RemoveCharacters(int x, int y, int x2, int y2) { std::string rest_of_string = (*current_text)[y2].substr(x2,std::string::npos); // Get the rest of the last line for (int i = y2; i > y; i--) { for (int j = 0; j < (int)cursors.size(); j++) { // For all cursors... if (cursors[j].line >= i) { cursors[j].line--; } if (cursors[j].started_selection_line >= i) { cursors[j].started_selection_line--; } } (*current_text).erase((*current_text).begin() + i); // Remove the current line } (*current_text)[y].erase(x, std::string::npos); (*current_text)[y] += rest_of_string; } rect ReorderSelectionPositions(int cursor) { rect positions; bool in_front = false; if (input::cursors[cursor].line > input::cursors[cursor].started_selection_line) { in_front = true; } else if (input::cursors[cursor].line == input::cursors[cursor].started_selection_line) { if (input::cursors[cursor].position >= input::cursors[cursor].started_selection_position) { in_front = true; } } if (in_front) { positions.x = cursors[cursor].started_selection_position; positions.x2 = cursors[cursor].position; positions.y = cursors[cursor].started_selection_line; positions.y2 = cursors[cursor].line; } else { positions.x = cursors[cursor].position; positions.x2 = cursors[cursor].started_selection_position; positions.y = cursors[cursor].line; positions.y2 = cursors[cursor].started_selection_line; } return positions; } void RemoveSelectionCharacters() { for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... rect positions = ReorderSelectionPositions(i); cursors[i].position = positions.x; cursors[i].highest_position = positions.x; cursors[i].line = positions.y; RemoveCharacters(positions.x, positions.y, positions.x2, positions.y2); } selecting = false; } void Backspace() { // The user pressed backspace! for (int i = 0; i < (int)cursors.size(); i++) { // For all cursors... if (cursors[i].position == 0) { // If we're right at the start of the newline... if (cursors[i].line == 0) continue; // Don't do anything if it's at the start of the file. // Great! Now we need to merge the two lines... for (int j = 0; j < (int)cursors.size(); j++) { // For all cursors... (again...) if (i == j) continue; if (cursors[j].line >= cursors[i].line) { cursors[j].line--; // Shift the cursors which are after the removed line } } int current_size = (*current_text)[cursors[i].line - 1].length(); // Save the length of the previous line (*current_text)[cursors[i].line - 1] += (*current_text)[cursors[i].line]; // Add the current line to the previous line (*current_text).erase((*current_text).begin() + cursors[i].line); // Remove the current line cursors[i].line--; // Make the cursor go back a line cursors[i].position = current_size; // Position the cursor at the end of the previous (now current) line before the new text was added cursors[i].highest_position = current_size; } else { for (int j = 0; j < (int)cursors.size(); j++) { // For all cursors... (again...) if (i == j) continue; if (cursors[j].line != cursors[i].line) continue; if (cursors[j].position >= cursors[i].position) { cursors[j].position--; // Shift the cursors which are after the removed letter } } (*current_text)[cursors[i].line].erase(cursors[i].position - 1, 1); // Delete the character before the cursor cursors[i].position--; // Move the cursor back one cursors[i].highest_position = cursors[i].position; } } } void RemoveDuplicateCursors() { if (cursors.size() == 1) return; for (int i = (int)cursors.size() - 1; i >= 0; i--) { for (int j = (int)cursors.size() - 1; j >= 0; j--) { if (i >= cursors.size()) continue; if (i == j) continue; if ((cursors[i].line == cursors[j].line) && (cursors[i].position == cursors[j].position)) { if (j == 0) continue; // J is the one that gets removed, and we don't want to remove the first cursor. cursors.erase(cursors.begin() + j); } if (selecting) { if ((cursors[j].line == cursors[i].started_selection_line) && (cursors[j].position = cursors[i].started_selection_position)) { cursors[i].started_selection_line = cursors[j].started_selection_line; cursors[i].started_selection_position = cursors[j].started_selection_position; cursors.erase(cursors.begin() + j); } } } } } void HandleEvents(SDL_Event e) { if (!taking_input) return; if (e.type == SDL_KEYDOWN) { // Handle backspace if (e.key.keysym.sym == SDLK_BACKSPACE) { // Remove the character if (selecting) { RemoveSelectionCharacters(); } else { Backspace(); } } else if (e.key.keysym.sym == SDLK_v && SDL_GetModState() & KMOD_CTRL) { if (selecting) { RemoveSelectionCharacters(); } char* heck = SDL_GetClipboardText(); InsertText(heck); SDL_free(heck); } else if (e.key.keysym.sym == SDLK_c && SDL_GetModState() & KMOD_CTRL) { SDL_SetClipboardText(GetAllSelectedText().c_str()); } else if (e.key.keysym.sym == SDLK_x && SDL_GetModState() & KMOD_CTRL) { SDL_SetClipboardText(GetAllSelectedText().c_str()); RemoveSelectionCharacters(); } else if (e.key.keysym.sym == SDLK_a && SDL_GetModState() & KMOD_CTRL) { SelectAll(); } else if (e.key.keysym.sym == SDLK_RETURN) { InsertNewline(); } else if (e.key.keysym.sym == SDLK_UP) { MoveCursorUp(); } else if (e.key.keysym.sym == SDLK_DOWN) { MoveCursorDown(); } else if (e.key.keysym.sym == SDLK_LEFT) { MoveCursorLeft(); } else if (e.key.keysym.sym == SDLK_RIGHT) { MoveCursorRight(); } RemoveDuplicateCursors(); } //Special text input event else if (e.type == SDL_TEXTINPUT) { //Append character(s) if (selecting) { RemoveSelectionCharacters(); } InsertText(e.text.text); RemoveDuplicateCursors(); } } }<file_sep>/Input/input.h #pragma once #ifndef INPUT_H #define INPUT_H #include <SDL.h> // SDL #include <SDL_image.h> // SDL_Image #include <SDL_ttf.h> // SDL_ttf #include <string> #include <vector> namespace input { struct cursor { int position; int line; int highest_position; int started_selection_position; int started_selection_line; }; struct rect { int x; int y; int x2; int y2; }; extern bool taking_input; extern int current_scroll; extern bool selecting; extern std::vector<std::string>* current_text; extern std::vector<cursor> cursors; void Init(); void Logic(); void StartInput(std::vector<std::string>* text); void HandleEvents(SDL_Event e); void InsertText(std::string text); void InsertNewlineSingleCursor(int i); void InsertNewline(); int CheckIfShiftHeld(); void MoveCursorUp(); void MoveCursorDown(); void MoveCursorLeft(); void MoveCursorRight(); std::string GetSelectedText(int cursor); std::string GetAllSelectedText(); void RemoveCharacters(int x, int y, int x2, int y2); rect ReorderSelectionPositions(int cursor); void RemoveSelectionCharacters(); } #endif<file_sep>/Input/editor.h #pragma once #ifndef EDITOR_H #define EDITOR_H #include <SDL.h> // SDL #include <SDL_image.h> // SDL_Image #include <SDL_ttf.h> // SDL_ttf #include <string> #include <vector> namespace editor { extern std::vector<std::string> script_lines; extern int current_scroll; void Render(); } #endif<file_sep>/Input/editor.cpp // Dummy namespace where input would be used #include "editor.h" #include <SDL.h> // SDL #include <SDL_image.h> // SDL_Image #include <SDL_ttf.h> // SDL_ttf #include <string> #include <vector> #include "graphics.h" #include "input.h" namespace editor { std::vector<std::string> script_lines; int current_scroll = 0; void Render() { //Draw cursors for (int i = 0; i < (int)input::cursors.size(); i++) { if (input::selecting) { int x = input::cursors[i].started_selection_position; int y = input::cursors[i].started_selection_line; int w = input::cursors[i].position - x; int h = input::cursors[i].line - y; if (input::cursors[i].line == input::cursors[i].started_selection_line) { graphics::DrawRectangle(16 + x * 8, 20 + y * 8, w * 8, (h * 8) + 8, 0, 127, 255); } else { bool in_front = false; if (input::cursors[i].line > input::cursors[i].started_selection_line) { in_front = true; } else if (input::cursors[i].line == input::cursors[i].started_selection_line) { if (input::cursors[i].position >= input::cursors[i].started_selection_position) { in_front = true; } } if (in_front) { graphics::DrawRectangle(16 + x * 8, 20 + y * 8, (script_lines[input::cursors[i].started_selection_line].size() - x) * 8, 8, 0, 127, 255); for (int j = 1; j < h; j++) { graphics::DrawRectangle(16, 20 + (y + j) * 8, (script_lines[y + j].size() * 8), 8, 0, 127, 255); } graphics::DrawRectangle(16, 20 + input::cursors[i].line * 8, input::cursors[i].position * 8, 8, 0, 127, 255); } else { graphics::DrawRectangle(16, 20 + y * 8, input::cursors[i].started_selection_position * 8, 8, 0, 127, 255); for (int j = 1; j < input::cursors[i].started_selection_line - input::cursors[i].line; j++) { graphics::DrawRectangle(16, 20 + (input::cursors[i].line + j) * 8, (script_lines[input::cursors[i].line + j].size() * 8), 8, 0, 127, 255); } graphics::DrawRectangle(16 + input::cursors[i].position * 8, 20 + input::cursors[i].line * 8, (script_lines[input::cursors[i].line].size() - input::cursors[i].position) * 8, 8, 0, 127, 255); } } } graphics::DrawText(graphics::font, 16 + (input::cursors[i].position * 8), 20 + (input::cursors[i].line * 8), "_", 255, 0, 255, false); } graphics::DrawText(graphics::font, 16 + (input::cursors[0].position * 8), 20 + (input::cursors[0].line * 8), "_", 255, 0, 0, false); //Draw text for (int i = 0; i < 25; i++) { if (i + current_scroll < (int)script_lines.size()) { graphics::DrawText(graphics::font, 16, 20 + (i * 8), script_lines[i], 255, 0, 255, false); } } graphics::DrawText(graphics::font, 0, 0, std::to_string(input::cursors.size()), 255, 0, 255); } }<file_sep>/Input/graphics.h #pragma once #ifndef GRAPHICS_H #define GRAPHICS_H #include <SDL.h> // SDL #include <SDL_image.h> // SDL_Image #include <SDL_ttf.h> // SDL_ttf #include <string> extern SDL_Window* g_window; extern SDL_Surface* g_surface; extern SDL_Renderer* g_renderer; namespace graphics { extern TTF_Font* font; void Init(); bool DrawText(TTF_Font* font, int x, int y, std::string text, int r, int g, int b, int a); bool DrawText(TTF_Font* font, int x, int y, std::string text, int r, int g, int b); void DrawTextBordered(TTF_Font* font, int x, int y, std::string text, int r, int g, int b, int a); void DrawTextBordered(TTF_Font* font, int x, int y, std::string text, int r, int g, int b); void DrawRectangle(int x, int y, int w, int h, int r, int g, int b, int a); void DrawRectangle(int x, int y, int w, int h, int r, int g, int b); void DrawRectangleOutline(int x, int y, int w, int h, int r, int g, int b, int a); void DrawRectangleOutline(int x, int y, int w, int h, int r, int g, int b); } #endif<file_sep>/Input/graphics.cpp // This should contain everything to do with graphics #include "graphics.h" #include <stdio.h> // Standard IO #include <SDL.h> // SDL #include <SDL_image.h> // SDL_Image #include <SDL_ttf.h> // SDL_ttf #include <string> namespace graphics { TTF_Font* font; void Init() { font = TTF_OpenFont("assets/PetMe64.ttf", 8); } bool DrawText(TTF_Font* font, int x, int y, std::string text, int r, int g, int b, int a) { SDL_Color color = { (Uint8) r, (Uint8) g, (Uint8) b }; // this is the color in rgb format, maxing out all would give you the color white, and it will be your text's color SDL_Surface* surface_text = TTF_RenderUTF8_Solid(font, text.c_str(), color); // as TTF_RenderText_Solid could only be used on SDL_Surface then you have to create the surface first SDL_Texture* texture_text = SDL_CreateTextureFromSurface(g_renderer, surface_text); //now you can convert it into a texture int w, h; TTF_SizeUTF8(font, text.c_str(), &w, &h); SDL_Rect text_rect; //create a rect text_rect.x = x; //controls the rect's x coordinate text_rect.y = y; // controls the rect's y coordinte text_rect.w = w; // controls the width of the rect text_rect.h = h; // controls the height of the rect //Mind you that (0,0) is on the top left of the window/screen, think a rect as the text's box, that way it would be very simple to understand //Now since it's a texture, you have to put RenderCopy in your game loop area, the area where the whole code executes SDL_RenderCopy(g_renderer, texture_text, NULL, &text_rect); //you put the renderer's name first, the Message, the crop size(you can ignore this if you don't want to dabble with cropping), and the rect which is the size and coordinate of your texture //Don't forget to free your surface and texture SDL_FreeSurface(surface_text); SDL_DestroyTexture(texture_text); return true; } bool DrawText(TTF_Font* font, int x, int y, std::string text, int r, int g, int b) { return graphics::DrawText(font, x, y, text, r, g, b, 255); } void DrawTextBordered(TTF_Font* font, int x, int y, std::string text, int r, int g, int b, int a) { DrawText(font, x - 1, y, text, 0, 0, 0, a); DrawText(font, x + 1, y, text, 0, 0, 0, a); DrawText(font, x, y - 1, text, 0, 0, 0, a); DrawText(font, x, y + 1, text, 0, 0, 0, a); DrawText(font, x, y, text, r, g, b, a); } void DrawTextBordered(TTF_Font* font, int x, int y, std::string text, int r, int g, int b) { DrawTextBordered(font, x, y, text, r, g, b, 255); } void DrawRectangle(int x, int y, int w, int h, int r, int g, int b, int a) { SDL_SetRenderDrawColor(g_renderer, r, g, b, a); SDL_Rect rectangle; rectangle.x = x; rectangle.y = y; rectangle.w = w; rectangle.h = h; SDL_RenderFillRect(g_renderer, &rectangle); } void DrawRectangle(int x, int y, int w, int h, int r, int g, int b) { DrawRectangle(x, y, w, h, r, g, b, 255); } void DrawRectangleOutline(int x, int y, int w, int h, int r, int g, int b, int a) { SDL_SetRenderDrawColor(g_renderer, r, g, b, a); SDL_Rect rectangle; rectangle.x = x; rectangle.y = y; rectangle.w = w; rectangle.h = h; SDL_RenderDrawRect(g_renderer, &rectangle); } void DrawRectangleOutline(int x, int y, int w, int h, int r, int g, int b) { DrawRectangle(x, y, w, h, r, g, b, 255); } }<file_sep>/Input/main.cpp /* INPUT <NAME> The goal of my content is always to entertain */ #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <stdio.h> // Standard IO #include <cstdlib> // Standard Library #include <iostream> #include "graphics.h" #include "input.h" #include "editor.h" // Screen dimension constants const int SCREEN_WIDTH = 320; const int SCREEN_HEIGHT = 240; const int SCREEN_SCALE = 2; const char* WINDOW_TITLE = "Input Test Window"; // The window we'll be rendering to SDL_Window* g_window = NULL; SDL_Surface* g_surface = NULL; SDL_Renderer* g_renderer = NULL; int main(int argc, char* args[]) { // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } // Create the window g_window = SDL_CreateWindow( WINDOW_TITLE, // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position SCREEN_WIDTH, // width, in pixels SCREEN_HEIGHT, // height, in pixels SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE // flags - see below ); // And the renderer g_renderer = SDL_CreateRenderer(g_window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (g_window == NULL) { printf("Window could not be created! SDL_Error: %s\n", SDL_GetError()); return EXIT_FAILURE; } int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); return EXIT_FAILURE; } if (TTF_Init() == -1) { printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError()); return EXIT_FAILURE; } // Set up the renderer SDL_SetRenderDrawColor(g_renderer, 0x00, 0x00, 0x00, 0xFF); // Resize the window SDL_RenderSetLogicalSize(g_renderer, SCREEN_WIDTH, SCREEN_HEIGHT); SDL_RenderSetIntegerScale(g_renderer, SDL_FALSE); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); SDL_SetWindowSize(g_window, SCREEN_WIDTH * SCREEN_SCALE, SCREEN_HEIGHT * SCREEN_SCALE); SDL_SetWindowPosition(g_window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); // Show the window SDL_ShowWindow(g_window); // Get the window's surface g_surface = SDL_GetWindowSurface(g_window); // Make it black! SDL_FillRect(g_surface, NULL, SDL_MapRGB(g_surface->format, 0x00, 0x00, 0x00)); input::Init(); graphics::Init(); input::StartInput(&editor::script_lines); bool quit = false; SDL_Event e; while (!quit) { while (SDL_PollEvent(&e) != 0) { // Input input::HandleEvents(e); // User requests quit if (e.type == SDL_QUIT) { quit = true; break; } } if (quit) break; // Logic state machine! input::Logic(); // Doesn't do anything if not currently taking input //Clear screen SDL_SetRenderDrawColor(g_renderer, 0, 0, 0, 255); SDL_RenderClear(g_renderer); // Rendering state machine! editor::Render(); //graphics::DrawText(graphics::font, 20, 20, "pogger", 255, 0, 255, 255); //Update screen SDL_RenderPresent(g_renderer); } SDL_FreeSurface(g_surface); SDL_DestroyRenderer(g_renderer); SDL_DestroyWindow(g_window); g_surface = NULL; g_renderer = NULL; g_window = NULL; // Quit SDL subsystems SDL_Quit(); return 0; } <file_sep>/README.md CPP input system for VVVVVV (if it gets accepted)
f0218c2c5027fc82d45909da235dc5b7042fdcc7
[ "Markdown", "C++" ]
8
C++
AllyTally/CPP-Input-system
3d7f4aa215bda9c73d657fa64f93fb28c02eb672
a38d594f8f15c1630096aa44f40691396e9920ad
refs/heads/master
<repo_name>gopal85/flaskproject<file_sep>/app/routes.py from app import app from app.models import model from flask import render_template from flask import request @app.route('/') @app.route('/index') def index(): user = {'name': 'Suraj'} return render_template('index.html', title='Home', user=user) @app.route('/secret') def secret(): name = "Suraj" return "<h1>Hello " + name + "!</h1>" @app.route('/welcome') def welcome(): name = "Upperline" return "<h1>Hello, and welcome to " + name + "!</h1>" @app.route('/goodbye') def goodbye(): return "<h2>That's the end of our time together.</h2>" @app.route('/resultspage') def resultspage(): user = {'name': 'Gopi', 'pets': '7'} return render_template('resultspage.html', title='On the Run', user=user) @app.route('/sendBreakfast', methods=['GET', 'POST']) def handleBreakfast(): if request.method == 'GET': return "You're getting the breakfast page!" else: userdata = dict(request.form) nickname = model.shout(userdata['nickname']) breakfast = model.shout(userdata['breakfast']) return "Hello, " + nickname + ", I heard you had " + breakfast + " for breakfast! Sounds delicious." <file_sep>/app/project.py from app import app from app.models import separate from flask import render_template from flask import request @app.route('/') @app.route('/startpage') def startpage(): user = {'name': 'Suraj', 'age': '34', 'pets': '7'} return render_template('startpage.html', title='Home', user=user) @app.route('/separator', methods=['GET', 'POST']) def separator(): if request.method == 'GET': return "You're getting the results page!" else: userdata = dict(request.form) user_string = str(userdata) broken = separate.arrange(userdata['sentence']) broken_length = len(broken) return render_template('separator.html', len = broken_length, broken = broken)
0422bab538be10e9fa7ceb5c0740de53bdee3a37
[ "Python" ]
2
Python
gopal85/flaskproject
57448c44d6eeb79f8dad080781668fd7fdfd63a2
a9e942827874fdc3029067115c299d38d97c8afb
refs/heads/master
<file_sep>package model; public enum Gender { yes, no } <file_sep>package model; public enum AgeCategory { Nissan, Mazda, Land_Rover, Lada, Honda }
3720bc7d1612cd240c815baf6fcef3dd90e5fa67
[ "Java" ]
2
Java
ILoveRedEd55/crud-output
09c0636fd16e2901c3f8a798a8c2fd1538b6fa96
d0b2dbbb2239d5d1c370c0c498f49172b388f5a7
refs/heads/master
<file_sep>package _03_More_Array_Fun; import java.util.Random; public class MoreArrayFun { //1. Create a main method to test the other methods you write. public static void main(String[] args) { String [] test = {"as", "be", "d", "z", "test"}; //System.out.println("rip1"); jumbleArr(test); //System.out.println("rip"); } //2. Write a method that takes an array of Strings and prints all the Strings in the array. static void printArr(String [] strings) { for(String str : strings) { System.out.println(str); } } //3. Write a method that takes an array of Strings and prints all the Strings in the array // in reverse order. static void printArrReverse(String [] strings) { for(int i = strings.length - 1; i > -1; i-- ) { System.out.println(strings[i]); } } //4. Write a method that takes an array of Strings and prints every other String in the array. static void printArrButString(String [] strings, String target) { for(int i = strings.length - 1; i > -1; i-- ) { if(strings[i] != target) System.out.println(strings[i]); } } //5. Write a method that takes an array of Strings and prints all the Strings in the array // in a completely random order. Almost every run of the program should result in a different order. static void jumbleArr(String [] strings) { Random rand = new Random(); int [] indices = new int[strings.length]; for(int i = 0; i < indices.length; i++) { indices[i] = -1; } for(int i = 0; i < indices.length; i++) { int value = rand.nextInt(indices.length); while(contains(indices, value)) { // System.out.println(value + " " + i); value = rand.nextInt(indices.length); } indices[i] = value; } String [] newStrings = new String[strings.length]; for(int i = 0; i < strings.length; i++) { newStrings[indices[i]] = strings[i]; } for(int i = 0; i < newStrings.length; i++) { System.out.println(newStrings[i]); } } static boolean contains(int [] arr, int value) { for(int i = 0; i < arr.length; i++) { if(arr[i] == value) return true; } return false; } }
94977527375b5fa72c5f7dd5319aa434e46cdb7d
[ "Java" ]
1
Java
League-level3-student/level3-module0-portoaj
dca48e3adae12f35df287b8689422fb02796b6d4
87182c534769567800d9e66cb073fb6310559122
refs/heads/master
<file_sep>require_relative '../spec_helper' describe CoffeeShop do before :each do CoffeeShop.create(name: "<NAME>", address: "362 2nd Ave", postal_code: '10010', avatar: 'https://irs1.4sqi.net/img/general/original/5497982_gHyWLCApRCC3WGbx1O-7ya8WYz7iQKGqku2Pp_TjLN4.jpg', phone_number: '(646) 476-8416', rating: 9.41, wifi_rating: 0, outlet_rating: 0, workspace_rating: 0, lat: 40.7363725255321, lon: -73.9818981457148, coffee_rating: 0.941, foursquare_id: '5058bd06e4b0e27671bf4399', total_wifi_reviews: 0, total_wifi_upvotes: 0, total_outlet_reviews: 0, total_outlet_upvotes: 0, total_workspace_reviews: 0, total_workspace_upvotes: 0, total_coffee_quality_reviews: 0, total_coffee_quality_upvotes: 0, foursquare_rating: 0.941) end it { should have_many :foursquare_reviews } it { should have_many :reviews } it { should have_many :tips } describe ".cache_from_foursquare" do it "should pull all coffee shops within the specififed zipcode and save them to the database as new Coffee Shop objects" do CoffeeShop.cache_from_foursquare(10010) expect(CoffeeShop.all).not_to eq([]) end end describe ".coffeeshop_user_distance" do it "should return the first 10 coffeeshops near the specified zipcode" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first expect(CoffeeShop.coffeeshop_user_distance(10010)).to have(10).item end end describe "#update_wifi_rating" do it "should upvote the coffee shop's wifi rating if the argument is true and then update coffee shop's wifi rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_wifi_rating(true) expect(@shop.total_wifi_reviews) == 1 expect(@shop.total_wifi_upvotes) == 1 expect(@shop.wifi_rating) == 1 end it "should downvote the coffee shop's wifi rating if the argument is false and then update the coffee shop's wifi rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_wifi_rating(false) expect(@shop.total_wifi_reviews) == 1 expect(@shop.total_wifi_upvotes) == 0 expect(@shop.wifi_rating) == 0 end end describe "#update_outlet_rating" do it "should upvote the coffee shop's outlet rating if the argument is true and then update coffee shop's outlet rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_outlet_rating(true) expect(@shop.total_outlet_reviews) == 1 expect(@shop.total_outlet_upvotes) == 1 expect(@shop.outlet_rating) == 1 end it "should downvote the coffee shop's outlet rating if the argument is false and then update the coffee shop's outlet rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_outlet_rating(false) expect(@shop.total_outlet_reviews) == 1 expect(@shop.total_outlet_upvotes) == 0 expect(@shop.outlet_rating) == 0 end end describe "#update_workspace_rating" do it "should upvote the coffee shop's workspace rating if the argument is true and then update coffee shop's workspace rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_workspace_rating(true) expect(@shop.total_workspace_reviews) == 1 expect(@shop.total_workspace_upvotes) == 1 expect(@shop.workspace_rating) == 1 end it "should downvote the coffee shop's workspace rating if the argument is false and then update the coffee shop's workspace rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_workspace_rating(false) expect(@shop.total_workspace_reviews) == 1 expect(@shop.total_workspace_upvotes) == 0 expect(@shop.workspace_rating) == 0 end end describe "#update_coffee_rating" do it "should upvote the coffee shop's coffee rating if the argument is true and then update coffee shop's coffee rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_coffee_rating(true) expect(@shop.total_coffee_quality_reviews) == 1 expect(@shop.total_coffee_quality_upvotes) == 1 expect(@shop.coffee_rating) == 1 end it "should downvote the coffee shop's coffee rating if the argument is false and then update the coffee shop's coffee rating and recalculate its total rating" do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @shop.update_coffee_rating(false) expect(@shop.total_coffee_quality_reviews) == 1 expect(@shop.total_coffee_quality_upvotes) == 0 expect(@shop.coffee_rating) == 0 end end end <file_sep>require 'chronic' task :refresh_check_ins => :environment do desc "It iterates through all users and if a user's last check_in_time is over 2 hours ago, it checks out the user" User.all.each do |user| if user.check_in_time < Chronic.parse("two hours ago") user.check_out end end end <file_sep>Rails.application.routes.draw do devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } get '/about' => 'welcome#about' resources :coffee_shops, shallow: true do resource :foursquarereviews resource :reviews resources :tips collection do get '/search', to: 'coffee_shops#search' get '/results', to: 'coffee_shops#results' post ':id/checkin' => 'users#check_in', :as => 'check_in' end end resources :users root to: 'coffee_shops#index' end <file_sep>class CreateCoffeeShops < ActiveRecord::Migration def change create_table :coffee_shops do |t| t.string :name t.string :address t.string :city t.string :postal_code t.string :avatar t.string :url t.string :phone_number t.string :hours t.integer :rating t.integer :wifi_rating t.integer :outlet_rating t.integer :workspace_rating t.timestamps end end end <file_sep>class ChangeCoffeeShopIdNameonFoursquareReviews < ActiveRecord::Migration def change rename_column :foursquare_reviews, :coffeeshop_id, :coffee_shop_id end end <file_sep>class AddCoffeeRatingToCoffeeShops < ActiveRecord::Migration def change add_column :coffee_shops, :coffee_rating, :float change_column :coffee_shops, :wifi_rating, :float change_column :coffee_shops, :outlet_rating, :float change_column :coffee_shops, :workspace_rating, :float end end <file_sep>require_relative '../spec_helper' require 'pry' describe FoursquareReview do before :each do CoffeeShop.cache_from_foursquare(10010) @shop = CoffeeShop.first @wifi_ranked_shops = CoffeeShop.where('total_wifi_reviews > ?', 0) @outlet_ranked_shops = CoffeeShop.where('total_outlet_reviews > ?', 0) @workspace_ranked_shops = CoffeeShop.where('total_workspace_reviews > ?', 0) FoursquareReview.add_foursquare_reviews end describe ".add_foursquare_reviews" do it "should iterate over all CoffeeShops and all foursquare reviews to each shop" do expect(@shop.foursquare_reviews).not_to eq([]) end end describe ".update_rating_based_on_foursquare_reviews" do it "should search all foursquare tips and edit each coffee shop's wifi, outlet and workspace ratings if it finds any positive or negative comments relating to any of these ratings" do FoursquareReview.update_rating_based_on_foursquare_reviews expect(@wifi_ranked_shops.first.total_wifi_reviews).not_to eq(0) expect(@outlet_ranked_shops.first.total_outlet_reviews).not_to eq(0) expect(@workspace_ranked_shops.first.total_workspace_reviews).not_to eq(0) end end end <file_sep>class CoffeeShopsController < ApplicationController def index @coffee_shops = CoffeeShop.all if request.env["HTTP_REFERER"] == 'http://moker.herokuapp.com/' elsif request.env["HTTP_REFERER"] == nil else redirect_to :back end end def show @coffee_shop = CoffeeShop.find(params[:id]) @tips = @coffee_shop.tips.order(created_at: :desc).includes(:user) @picture_reviews_toshow = @coffee_shop.foursquare_reviews.where.not(picture: nil).first(4) if @picture_reviews_toshow.count >= 4 last_pics = @picture_reviews_toshow.count - 4 @picture_reviews_tohide = @coffee_shop.foursquare_reviews.where.not(picture: nil).last((last_pics)) @picture_tips_to_show = nil @picture_tips_to_hide = @coffee_shop.tips.where.not(picture_file_name: nil) else @picture_reviews_tohide = nil @picture_tips_to_show = @coffee_shop.tips.where.not(picture_file_name: nil).first(4 - @picture_reviews_toshow.count) @picture_tips_to_hide = @coffee_shop.tips.where.not(picture_file_name: nil).last(@coffee_shop.tips.where.not(picture_file_name: nil).count - @picture_tips_to_show.count) end end def search end def results if /\A\d{5}(-\d{4})?\z/.match(params[:query]) != nil zip_code = params[:query] @sorted_coffee_shops = CoffeeShop.coffeeshop_user_distance(zip_code) else @sorted_coffee_shops = [] filter = ["coffee", "cafe"] query_names = params[:query].downcase.split() filter.each do |filter_word| query_names.delete_if {|x| x.include? filter_word } end query_names.each do |searched_word| @matching_shops = CoffeeShop.where("name ILIKE ?", "%#{searched_word}%") @matching_shops.each do |shop| @sorted_coffee_shops.push([shop, shop.rating]) end end end end end <file_sep>class ReviewsController < ApplicationController before_action :authenticate_user!, only: [:new, :create] def index coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @reviews = coffee_shop.reviews end def show coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @review = coffee_shop.reviews.find(params[:id]) end def new # if current_user @coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @review = Review.new render :layout => "simple_layout" end def create @coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @review = Review.new(review_params) @review.coffee_shop = @coffee_shop @review.user_id = current_user.id if @review.valid? @coffee_shop.update_wifi_rating(@review.wifi_rating) @coffee_shop.update_outlet_rating(@review.outlet_rating) @coffee_shop.update_workspace_rating(@review.workspace_rating) @coffee_shop.update_coffee_rating(@review.coffee_rating) @review.save! redirect_to @coffee_shop else render 'new' end end private def review_params return params.require(:review).permit(:outlet_rating, :wifi_rating, :workspace_rating, :coffee_rating) end end <file_sep>class RemoveFoursquareReviewIdFromCoffeeShops < ActiveRecord::Migration def change remove_column :coffee_shops, :foursquare_reviews_id end end <file_sep>class User < ActiveRecord::Base has_many :authorizations has_many :reviews has_many :tips belongs_to :coffee_shop # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :omniauthable, :omniauth_providers => [:facebook] def self.find_for_facebook_oauth(auth) where(auth.slice(:provider, :uid)).first_or_create do |user| user.provider = auth.provider user.uid = auth.uid user.email = auth.info.email user.password = <PASSWORD>_token[0,20] user.name = auth.info.name # assuming the user model has a name user.image = auth.info.image # assuming the user model has an image end end def self.new_with_session(params, session) super.tap do |user| if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"] user.email = data["email"] if user.email.blank? end end end def check_in(coffee_shop) self.coffee_shop_id = coffee_shop.to_i self.check_in_time = Time.now self.save! end def check_out self.coffee_shop_id = nil self.check_in_time = nil self.save! end end <file_sep>class CreateReviews < ActiveRecord::Migration def change create_table :reviews do |t| t.references :user t.references :coffee_shop t.boolean :wifi_rating t.boolean :outlet_rating t.boolean :workspace_rating t.boolean :coffee_rating t.string :comment end end end <file_sep>class AddColumnsToCoffeeShop < ActiveRecord::Migration def change add_column :coffee_shops, :total_wifi_reviews, :integer add_column :coffee_shops, :total_wifi_upvotes, :integer add_column :coffee_shops, :total_outlet_reviews, :integer add_column :coffee_shops, :total_outlet_upvotes, :integer add_column :coffee_shops, :total_workspace_reviews, :integer add_column :coffee_shops, :total_workspace_upvotes, :integer add_column :coffee_shops, :total_coffee_quality_reviews, :integer add_column :coffee_shops, :total_coffee_quality_upvotes, :integer end end <file_sep># Moker_App --- ### Project Description Moker(mobile worker) makes finding a place to work easy. Our goal is to find you a coffee shop with 3 things - fast wifi, comftorable workspace, and amazing coffee. The best thing about Moker is that you're part of a mobile workforce community. Every time you walk into a coffee shop to get some work done you'll have a chance to interact with other Moker's that are working on interesting projects as well. Moker allows you to see who's checked into a particular coffee shop at the time you open the app to search for a nearby coffee shop to work in. Here's an example of the benefits Moker provides. You're deciding between coffee shop A and B. You know that you will be working with python and might need someone to look over your code - well what if you can see someones profile that is currently checked into coffee shop A? Their profile says that they are proficient in python and javascript. You would probably go to coffee shop A instead of B. Developers constantly pass each other by at coffee shops without ever saying hello. Think of all the new projects, ideas, and friendships that can come of a simple 10 minute conversation. The possibilities are limitless. ### Team Members --- * [<NAME>](mailto: <EMAIL>) * [<NAME>](mailto: <EMAIL>) --- ### Links --- * Heroku (Coming Soon) * Trello - User Stories * [View](https://trello.com/b/KMc1eMil/moker-app) the current status of our project and the timeline for each feature's completion. --- ### Technologies Used * Core Technologies * [Ruby on Rails](http://rubyonrails.org/) * [jQuery](http://jquery.com/) * [PostgreSQL](http://www.postgresql.org/) * Testing Platforms * RSpec * Shoulda Matchers * Simple Cov * Testing Coverage: 90.3% ### ERD ![ERD](/images/erdv4.png)<file_sep>require_relative '../spec_helper.rb' describe User do # Will have to use integration tests for OAuth. More info at https://github.com/intridea/omniauth/wiki/Integration-Testing end <file_sep>class CoffeeShop < ActiveRecord::Base has_many :foursquare_reviews has_many :reviews has_many :tips has_many :users FOURSQUARE_VENUE_PREFIX = 'https://api.foursquare.com/v2/venues/' FOURSQUARE_VENUE_SUFFIX = '?client_id=QAOJQNY2JJHJC2DNYHLDH0EEBPFDZAXEOA44DY1X1BZJOJOD&client_secret=<KEY>&v=20140315' FOURSQUARE_SEARCH_PREFIX = 'https://api.foursquare.com/v2/venues/search?client_id=<KEY>&client_secret=<KEY>&v=20140315&ll=' FOURSQUARE_SEARCH_SUFFIX = '&limit=50&query=coffee' def self.cache_from_foursquare(zipcode) new = false zip = zipcode.to_s lat = zip.to_lat lon = zip.to_lon puts "===============================" puts "grabbing for zipcode #{zipcode}" puts "===============================" response = HTTParty.get("#{FOURSQUARE_SEARCH_PREFIX}#{lat},#{lon}#{FOURSQUARE_SEARCH_SUFFIX}") begin response["response"]["venues"].each do |coffee_shop| shop = CoffeeShop.find_or_create_by(foursquare_id: coffee_shop["id"]) if shop.name == nil new = true shop.foursquare_id = coffee_shop["id"] shop.wifi_rating = 0 shop.outlet_rating = 0 shop.workspace_rating = 0 shop.total_wifi_reviews = 0 shop.total_wifi_upvotes = 0 shop.total_outlet_reviews = 0 shop.total_outlet_upvotes = 0 shop.total_workspace_reviews = 0 shop.total_workspace_upvotes = 0 shop.total_coffee_quality_reviews = 0 shop.total_coffee_quality_upvotes = 0 new_shop = HTTParty.get("#{FOURSQUARE_VENUE_PREFIX}#{shop.foursquare_id}#{FOURSQUARE_VENUE_SUFFIX}") # Rating is set on second API call shop.rating = new_shop["response"]["venue"]["rating"].to_f shop.coffee_rating = (new_shop["response"]["venue"]["rating"].to_f * 0.1) shop.foursquare_rating = (new_shop["response"]["venue"]["rating"].to_f * 0.1) # Picture grabbed in second API call begin shop.avatar = "#{new_shop["response"]["venue"]["photos"]["groups"][0]["items"][0]["prefix"]}original#{new_shop["response"]["venue"]["photos"]["groups"][0]["items"][0]["suffix"]}" || nil rescue NoMethodError shop.avatar = nil end end shop.name = coffee_shop["name"] shop.address = coffee_shop["location"]["address"] shop.city = coffee_shop["location"]["city"] shop.postal_code = coffee_shop["location"]["postalCode"] shop.lat = coffee_shop["location"]["lat"] shop.lon = coffee_shop["location"]["lng"] shop.url = coffee_shop["url"] if new == true puts "#{shop.name} has been added to the database." else puts "#{shop.name} has been updated in the database." end shop.save! end rescue NoMethodError end end def self.coffeeshop_user_distance(user_zip) zip = user_zip.to_s lat1 = zip.to_lat.to_f long1 = zip.to_lon.to_f user_city = zip.to_region(:city => true) distance_hash = {} CoffeeShop.where(city: user_city).each do |shop| lat2 = shop.lat long2 = shop.lon distance_hash[shop] = shop.haversine(lat1, long1, lat2, long2) end sorted_array = distance_hash.sort_by {|key, value| value} limited_sorted_array = sorted_array.first(15) new_sorted_array = limited_sorted_array.map do |shop| shop end return new_sorted_array.sort {|a,b| b[0].rating <=> a[0].rating}.first 10 end def haversine(lat1, long1, lat2, long2) dtor = Math::PI/180 r = 3959 rlat1 = lat1 * dtor rlong1 = long1 * dtor rlat2 = lat2 * dtor rlong2 = long2 * dtor dlon = rlong1 - rlong2 dlat = rlat1 - rlat2 a = power(Math::sin(dlat/2), 2) + Math::cos(rlat1) * Math::cos(rlat2) * power(Math::sin(dlon/2), 2) c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a)) d = r * c return d end def update_wifi_rating(value) if value == true self.total_wifi_reviews += 1 self.total_wifi_upvotes += 1 self.wifi_rating = (total_wifi_upvotes / total_wifi_reviews) self.recalculate_rating self.save! elsif value == false self.total_wifi_reviews += 1 self.wifi_rating = (total_wifi_upvotes / total_wifi_reviews) self.recalculate_rating self.save! end end def update_outlet_rating(value) if value == true self.total_outlet_reviews += 1 self.total_outlet_upvotes += 1 self.outlet_rating = (total_outlet_upvotes / total_outlet_reviews) self.recalculate_rating self.save! elsif value == false self.total_outlet_reviews += 1 self.outlet_rating = (total_outlet_upvotes / total_outlet_reviews) self.recalculate_rating self.save! end end def update_workspace_rating(value) if value == true self.total_workspace_reviews += 1 self.total_workspace_upvotes += 1 self.workspace_rating = (total_workspace_upvotes / total_workspace_reviews) self.recalculate_rating self.save! elsif value == false self.total_workspace_reviews += 1 self.workspace_rating = (total_workspace_upvotes / total_workspace_reviews) self.recalculate_rating self.save! end end def update_coffee_rating(value) if value == true self.total_coffee_quality_reviews += 1 self.total_coffee_quality_upvotes += 1 self.coffee_rating = (total_coffee_quality_upvotes / total_coffee_quality_reviews) self.recalculate_rating self.save! elsif value == false self.total_coffee_quality_reviews +=1 self.coffee_rating = (total_coffee_quality_upvotes / total_coffee_quality_reviews) self.recalculate_rating self.save! end end def recalculate_rating # Set up weights for each rating. If a rating is zero (defined above) remove the weight from impacting rating calculation below foursquare_weight = 80 if workspace_rating > 0 workspace_weight = 8 else workspace_weight = 0 end if wifi_rating > 0 wifi_weight = 6 else wifi_weight = 0 end if coffee_rating > 0 coffee_weight = 4 else coffee_weight = 0 end if outlet_rating > 0 outlet_weight = 2 else outlet_weight = 0 end # create weighted rating by multiplying weight by rating weighted_foursquare_rating = foursquare_weight * foursquare_rating weighted_workspace_rating = workspace_weight * workspace_rating weighted_wifi_rating = wifi_weight * wifi_rating weighted_coffee_rating = coffee_weight * coffee_rating weighted_outlet_rating = outlet_weight * outlet_rating # Set total weighted rating by adding all weighted ratings together weighted_rating_total = weighted_foursquare_rating + weighted_workspace_rating + weighted_wifi_rating + weighted_coffee_rating + weighted_outlet_rating # The updated rating is the weighted rating total over the weights total updated_rating = weighted_rating_total / (foursquare_weight + workspace_weight + wifi_weight + coffee_weight + outlet_weight) # Update the rating and round to two decimal places self.rating = '%.2f' % (updated_rating * 10) self.save! end private def power(num, pow) num ** pow end end <file_sep>class AddTimestampsToFoursquareReviews < ActiveRecord::Migration def change add_column :foursquare_reviews, :created_at, :datetime add_column :foursquare_reviews, :updated_at, :datetime end end <file_sep>class Review < ActiveRecord::Base belongs_to :coffee_shop belongs_to :user # validates :outlet_rating, inclusion: [true, false], :message => 'Jason is a scrumbag' validates :outlet_rating, :workspace_rating, :wifi_rating, :coffee_rating, :inclusion => { :in => [true, false], :message => "was not filled in" } # validates :user, uniqueness: {message: 'You cannot vote more than once.'} end <file_sep>class AddFoursquareReviewRefToCoffeeShop < ActiveRecord::Migration def change add_reference :coffee_shops, :foursquare_reviews, index: true end end <file_sep>class AddCheckInDeetsToUser < ActiveRecord::Migration def change add_column :users, :coffee_shop_id, :integer add_column :users, :check_in_time, :datetime end end <file_sep>class TipsController < ApplicationController before_action :authenticate_user!, only: [:new, :create] def index @coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @tips = @coffee_shop.tips end def show @coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @tip = Tip.find(params[:id]) end def new @coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @tip = Tip.new render :layout => "simple_layout" end def create @coffee_shop = CoffeeShop.find(params[:coffee_shop_id]) @tip = Tip.new(tip_params) @tip.coffee_shop = @coffee_shop @tip.user = current_user @tip.save! redirect_to @coffee_shop end private def tip_params return params.require(:tip).permit(:comment, :picture) end end <file_sep>class AddFoursquareRatingToCoffeeShops < ActiveRecord::Migration def change add_column :coffee_shops, :foursquare_rating, :float end end <file_sep>class ChangeCoffeeShopColumnNameOnTips < ActiveRecord::Migration def change rename_column :tips, :coffeeshop_id, :coffee_shop_id end end <file_sep>class FoursquareReview < ActiveRecord::Base belongs_to :coffee_shop FOURSQUARE_VENUE_PREFIX = 'https://api.foursquare.com/v2/venues/' FOURSQUARE_VENUE_SUFFIX = '?client_id=QAOJQNY2JJHJC2DNYHLDH0EEBPFDZAXEOA44DY1X1BZJOJOD&client_secret=<KEY>&v=20140315' def self.add_foursquare_reviews CoffeeShop.all.each do |shop| FoursquareReview.cache_from_foursquare(shop) end end def self.cache_from_foursquare(coffeeshop) venueID = coffeeshop.foursquare_id id = coffeeshop.id if coffeeshop.foursquare_reviews = [] response = HTTParty.get("#{FOURSQUARE_VENUE_PREFIX}#{venueID}#{FOURSQUARE_VENUE_SUFFIX}") response["response"]["venue"]["tips"]["groups"][0]["items"].each do |foursquare_tip| review = FoursquareReview.create review.comment = foursquare_tip["text"] || nil unless foursquare_tip["photo"] == nil review.picture = "#{foursquare_tip["photo"]["prefix"]}original#{foursquare_tip["photo"]["suffix"]}" end review.username = "#{foursquare_tip["user"]["firstName"]} #{foursquare_tip["user"]["lastName"]}" || nil review.user_pic ="#{foursquare_tip["user"]["photo"]["prefix"]}original#{foursquare_tip["user"]["photo"]["suffix"]}" || nil review.coffee_shop_id = id puts "#{coffeeshop.name} updated with a review from #{review.username}" review.save! end end end def self.update_rating_based_on_foursquare_reviews wifi_good_list = ['free', 'great', 'fast', 'solid', 'password', 'has', 'strong'] wifi_bad_list = ['no', 'bad', 'slow', 'had'] workspace_good_list = ['big'] workspace_bad_list = ['small', 'no', 'not', 'more', 'wish', 'tight'] outlet_good_list = ['has', 'alot', 'lot'] outlet_bad_list = ['not', 'no'] # Iterate over every coffee shop CoffeeShop.all.each do |shop| # Iterate over every coffee shop's foursquare reviews shop.foursquare_reviews.each do |foursquare_review| split_string = foursquare_review.comment.downcase.gsub(/[^0-9a-z]/i, ' ').split() # If the split array of this particular coffee shop's particular foursquare comment includes the word wifi, do this if split_string.include? "wifi" # If the word before 'wifi' contains a word from the good_word list upvote the coffee shop's wifi rating wifi_good_list.each do |good_word| if split_string[split_string.index("wifi") - 1] == good_word shop.update_wifi_rating(true) end # If the word two before 'wifi' contains a word from the good_word list upvote the coffee shop's wifi rating if split_string[split_string.index("wifi") - 2] == good_word shop.update_wifi_rating(true) end end # If the word before 'wifi' contains a word from the bad_word list downvote the coffee shop's wifi rating wifi_bad_list.each do |bad_word| if split_string[split_string.index("wifi") - 1] == bad_word shop.update_wifi_rating(false) end # If the word two before 'wifi' contains a word from the bad_word list downvote the coffee shop's wifi rating if split_string[split_string.index("wifi") - 2] == bad_word shop.update_wifi_rating(false) end end end # If the split array of this particular coffee shop's particular foursquare comment includes the word outlet, do this if (split_string.include? "outlets") outlet_good_list.each do |good_word| # If the word before 'outlet' contains a word from the good_word list upvote the coffee shop's outlet rating if split_string[split_string.index("outlets") - 1] == good_word shop.update_outlet_rating(true) end # If the word two before 'outlet' contains a word from the good_word list upvote the coffee shop's outlet rating if split_string[split_string.index("outlets") - 2] == good_word shop.update_outlet_rating(true) end end outlet_bad_list.each do |bad_word| # If the word before 'outlet' contains a word from the bad_word list downvote the coffee shop's outlet rating if split_string[split_string.index("outlets") - 1] == bad_word shop.update_outlet_rating(false) end # If the word two before 'outlet' contains a word from the bad_word list downvote the coffee shop's outlet rating if split_string[split_string.index("outlets") - 2] == bad_word shop.update_outlet_rating(false) end end end # Check for tables (aka workspace) in reviews if (split_string.include? "tables") workspace_good_list.each do |good_word| # If the word before 'workspace' contains a word from the good_word list upvote the coffee shop's workspace rating if split_string[split_string.index("tables") - 1] == good_word shop.update_workspace_rating(true) end # If the word two before 'workspace' contains a word from the good_word list upvote the coffee shop's workspace rating if split_string[split_string.index("tables") - 2] == good_word shop.update_workspace_rating(true) end if split_string[split_string.index("tables") + 1] == good_word shop.update_workspace_rating(true) end if split_string[split_string.index("tables") + 2] == good_word shop.update_workspace_rating(true) end end workspace_bad_list.each do |bad_word| # If the word before 'workspace' contains a word from the bad_word list downvote the coffee shop's workspace rating if split_string[split_string.index("tables") - 1] == bad_word shop.update_workspace_rating(false) end # If the word two before 'workspace' contains a word from the bad_word list downvote the coffee shop's workspace rating if split_string[split_string.index("tables") - 2] == bad_word shop.update_workspace_rating(false) end if split_string[split_string.index("tables") + 1] == bad_word shop.update_workspace_rating(false) end if split_string[split_string.index("tables") + 2] == bad_word shop.update_workspace_rating(false) end end end # Check for space (aka workspace in reviews) if (split_string.include? "space") workspace_good_list.each do |good_word| # If the word before 'workspace' contains a word from the good_word list upvote the coffee shop's workspace rating if split_string[split_string.index("space") - 1] == good_word shop.update_workspace_rating(true) end # If the word two before 'workspace' contains a word from the good_word list upvote the coffee shop's workspace rating if split_string[split_string.index("space") - 2] == good_word shop.update_workspace_rating(true) end if split_string[split_string.index("space") + 1] == good_word shop.update_workspace_rating(true) end if split_string[split_string.index("space") + 2] == good_word shop.update_workspace_rating(true) end end workspace_bad_list.each do |bad_word| # If the word before 'workspace' contains a word from the bad_word list downvote the coffee shop's workspace rating if split_string[split_string.index("space") - 1] == bad_word shop.update_workspace_rating(false) end # If the word two before 'workspace' contains a word from the bad_word list downvote the coffee shop's workspace rating if split_string[split_string.index("space") - 2] == bad_word shop.update_workspace_rating(false) end if split_string[split_string.index("space") + 1] == bad_word shop.update_workspace_rating(false) end if split_string[split_string.index("space") + 2] == bad_word shop.update_workspace_rating(false) end end end end end end end
b5fcf56a6af45ad1d0eb5542e6e2b91b88f99aa8
[ "Markdown", "Ruby" ]
24
Ruby
ByteDown/moker_app
436f97a98d440fbadb0ea22acae9d2a0d4e2086e
2556a004eb9210cd262d97c8b9515b8aa787d10f
refs/heads/master
<repo_name>hpaasch/private_api<file_sep>/app/views.py from django.shortcuts import render from rest_framework import generics from app.serializers import BeagleFarmSerializer from app.models import BeagleFarm class BeagleFarmListAPIView(generics.ListCreateAPIView): # queryset = BeagleFarm.objects.all() # ditched this when we created get_queryset serializer_class = BeagleFarmSerializer def get_queryset(self): # needs to be function. can't just change queryset. to make it lazily evaluated, changeable per use return BeagleFarm.objects.filter(user=self.request.user) # this pulls from header in Postman Send request. <file_sep>/app/serializers.py from rest_framework import serializers from app.models import BeagleFarm class BeagleFarmSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) # added the above to bind the user to the new entry in Postman # key part for the weekend homework class Meta: model = BeagleFarm # depth = 1 # took out to reduce what is auto delivered on the token <file_sep>/private_api/urls.py from django.conf.urls import url from django.contrib import admin from rest_framework.authtoken import views from app.views import BeagleFarmListAPIView urlpatterns = [ url(r'^admin/', admin.site.urls), url('^beagle_farms/$', BeagleFarmListAPIView.as_view(), name='beagle_farm_list_api_view'), # pluralize and underscore the model name url('^api-token-auth/', views.obtain_auth_token), ] <file_sep>/app/models.py from django.db import models from django.dispatch import receiver from django.db.models.signals import post_save from rest_framework.authtoken.models import Token class BeagleFarm(models.Model): user = models.ForeignKey('auth.User') # avoids import owner = models.CharField(max_length=25) dog_beds = models.IntegerField() food_bins = models.IntegerField() specialty = models.CharField(max_length=20) @receiver(post_save, sender='auth.User') def create_token(**kwargs): # a shortcut pass in created = kwargs.get("created") # boilerplate instance = kwargs.get("instance") # boilerplate if created: Token.objects.create(user=instance) # yep. standard. <file_sep>/main.py import requests username = input("Username? ") password = input("<PASSWORD>? ") post_data = { "username": username, "password": <PASSWORD>, } response = requests.post('http://localhost:8000/api-token-auth/', post_data).json() token = response['token'] headers = { "Authorization": "Token {}".format(token) # need EXACTLY } response = requests.get('http://localhost:8000/beagle_farms/', headers=headers).json() for farm in response: print(farm['owner'], farm['dog_beds'])
adba83e64442891eba4efc1dc5a2642cb172dbbb
[ "Python" ]
5
Python
hpaasch/private_api
6ed05ea8ce5c4ed58517c15f06f8127979053129
089b278f8bec45513e8ab6abef099a3eb325769b
refs/heads/master
<repo_name>cyrillos/vjk<file_sep>/Makefile .PHONY: all .FORCE .DEFAULT_GOAL := all ifeq ($(strip $(V)),) E := @echo Q := @ else E := @\# Q := endif export E Q define msg-gen $(E) " GEN " $(1) endef define msg-clean $(E) " CLEAN " $(1) endef export msg-gen msg-clean MAKEFLAGS += --no-print-directory export MAKEFLAGS RM ?= rm -f MAKE ?= make GIT ?= git CP ?= cp -f CTAGS ?= ctags PYTHON ?= python3 SBCL ?= sbcl export RM MAKE GIT CP CTAGS PYTHON SBCL srv-y += src/server/vjk.lisp cli-y += src/client/vjk.py srv: $(srv-y) $(Q) $(SBCL) --noinform --load $(srv-y) --conf conf/vjk.json .PHONY: srv cli-start: $(cli-y) $(Q) $(PYTHON) $(cli-y) --conf conf/vjk.json start psmb@vz,sas32 .PHONY: cli-start cli-stop: $(cli-y) $(Q) $(PYTHON) $(cli-y) --conf conf/vjk.json stop .PHONY: cli-start .SUFFIXES: <file_sep>/src/client/vjktz.py #!/usr/bin/python3 import datetime import calendar import time import re from datetime import datetime # # The database stores time in four columns # # 'tsstart': 1575649404 # 'tzstart': 10800 # # 'tsstop': 1575652702 # 'tzstop': 10800 # # where tsstart and tsstop are star and stop # times of activity in plain unix timestamp # and tzstart, tzstop are local timezone offset. # # For example above it is # # 2019-12-06 19:23:24 as start # # tsstart: 1575649404 -> Friday, December 6, 2019 16:23:24 # tzstart: 10800 -> GMT+03:00 # # 2019-12-06 20:18:22 as stop # # tsstop: 1575652702 -> Friday, December 6, 2019 17:18:22 # tzstop: 10800 -> GMT+03:00 # class VjkTz: def __init__(self): '''A class for managing unix epoch taking into account local time offset. At start it caches timezone offset and operates with it on demand. ''' # # Cache timezone offset now = self.epoch() utc = time.gmtime(now) loc = time.localtime(now) self.tz_offset = int(time.mktime(loc) - time.mktime(utc)) # # relative time # -1ds, 1ds, 1ws self.relative_re = re.compile(r'^([\-]?)(\d+)([wdh])([s]?)$') # # long date format yyyy-mm-dd hh:mm:ss self.long_date_re = re.compile(r'^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$') # # short date format yyyy-mm-dd self.short_date_re = re.compile(r'^(\d\d\d\d)-(\d\d)-(\d\d)$') def epoch_local_relative(self, s: str) -> int: '''Takes offset in format [-]num[wdh][s] and returns a timestamp for it or -1 on error. Timezone offset is substracted. @- negative offset @num number (including zero) @w weeks @d days @h hours @s use today's start of a day as relative point to count offset from, otherwise current time is used''' if s[0] == '\\': # bash escaping before negative number m = self.relative_re.search(s[1:]) else: m = self.relative_re.search(s) if not m: return -1 if m.group(4) == 's': epoch = self.epoch_local_000000() else: epoch = self.epoch() num = int(m.group(2)) if m.group(3) == 'w': # weeks seconds = 7 * 24 * 60 * 60 elif m.group(3) == 'd': # days seconds = 24 * 60 * 60 elif m.group(3) == 'h': # hours seconds = 60 * 60 else: seconds = 1 return epoch - num * seconds def seconds_to_hms(self, seconds) -> (int,int,int): '''Convert seconds to hours, minutes, seconds tuple.''' hours = seconds // 3600 seconds -= hours * 3600 minutes = seconds // 60 seconds -= minutes * 60 return (hours, minutes, seconds) def epoch(self) -> int: '''Returns plain unix timestamp, no timezone accounted.''' return int(time.time()) def tzoff(self) -> int: '''Returns local timezone offset.''' return self.tz_offset def epoch_local_month_day_hms(self, local_time: time.struct_time, month: int, day: int, hours: int, minutes: int, seconds: int) -> int: '''Adjust struct_time by month, day, hours, minutes, seconds and convert it into unix timestamp substracting timezone.''' epoch = int(calendar.timegm((local_time.tm_year, month, day, hours, minutes, seconds, local_time.tm_wday, local_time.tm_yday, local_time.tm_isdst))) return epoch - self.tzoff() def epoch_local_hms(self, hours: int, minutes: int, seconds: int) -> int: '''Fetches local time and converts today's hours:minutes:seconds into unix timestamp substracting timezone.''' t = time.localtime() return self.epoch_local_month_day_hms(t, t.tm_mon, t.tm_mday, hours, minutes, seconds) def epoch_local_month(self) -> int: '''Fetches local time and returns timestamp for a month start moment substracting timezone.''' t = time.localtime() return self.epoch_local_month_day_hms(t, t.tm_mon, 1, 0, 0, 0) def epoch_local_week(self) -> int: '''Fetches local time and returns timestamp for a week start moment substracting timezone.''' # tw_day counts from 0: 0 - Mon, ..., 6 - Sun t = time.localtime() return self.epoch_local_000000() - t.tm_wday * 3600 * 24 def epoch_local_000000(self) -> int: '''Fetches local time and converts today's 00:00:00 into a unix timestamp substracting timezone. For example, localtime is Friday, December 6, 2019 00:00:01 GMT+03:00 then it returns 1575579600 which is Thursday, December 5, 2019 21:00:00 in GMT format. ''' return self.epoch_local_hms(0, 0, 0) def epoch_local_235959(self) -> int: '''Fetches local time and converts today's 23:59:59 into a unix timestamp substracting timezone. For example, localtime is Friday, December 6, 2019 21:22:22 GMT+03:00 then it returns 1575665999 which is Friday, December 6, 2019 20:59:59 in GMT format. ''' return self.epoch_local_hms(23, 59, 59) def epoch_strftime(self, timestamp: int, fmt: str) -> str: '''Converts unix timestamp to string with by fmt.''' return datetime.utcfromtimestamp(timestamp).strftime(fmt) def epoch_strftime_long(self, timestamp: int) -> str: '''epoch_strftime with fmt %Y-%m-%d %H:%M:%S.''' return self.epoch_strftime(timestamp, '%Y-%m-%d %H:%M:%S') def local_strftime_long(self, timestamp: int) -> str: '''epoch_strftime_long but adding timezone offset''' return self.epoch_strftime_long(timestamp + self.tzoff()) def epoch_strftime_short(self, timestamp: int): '''epoch_strftime with fmt %H:%M:%S.''' return self.epoch_strftime(timestamp, '%H:%M:%S') def local_strftime_short(self, timestamp: int): '''epoch_strftime but adding timezone offset''' return self.epoch_strftime_short(timestamp + self.tzoff()) def epoch_local_strptime_long(self, s: str) -> int: '''Converts local time string %Y-%m-%d %H:%M:%S to unix timestamp substracting timezone. Returns -1 on error.''' try: d = datetime.strptime(s, '%Y-%m-%d %H:%M:%S') return int(calendar.timegm(d.timetuple())) - self.tzoff() except: return -1 def epoch_local_strptime_short(self, s: str) -> int: '''Converts local time string %Y-%m-%d 00:00:00 to unix timestamp substracting timezone. Returns -1 on error.''' return self.epoch_local_strptime_long(s + " 00:00:00") if __name__ == "__main__": tz = VjkTz() print('epoch', tz.epoch()) print('tzoff', tz.tzoff()) print('epoch_local_month', tz.epoch_local_month()) print('epoch_local_week', tz.epoch_local_week()) print('epoch_local_000000', tz.epoch_local_000000()) print('epoch_local_235959', tz.epoch_local_235959()) print('epoch_local_relative -1ds', tz.epoch_local_relative("-1ds")) print('epoch_local_relative -1d', tz.epoch_local_relative("-1d")) print('epoch_local_relative -0ds', tz.epoch_local_relative("-0ds")) print('epoch_local_relative -0d', tz.epoch_local_relative("-0d")) # # GMT: Friday, December 6, 2019 14:53:19 # Local: Friday, December 6, 2019 17:53:19 GMT+03:00 epoch = 1575643999 date_long_local = "2019-12-06 17:53:19" print('epoch_strftime_long', tz.epoch_strftime_long(epoch)) print('epoch_strftime_short', tz.epoch_strftime_short(epoch)) print('epoch_local_strptime_long', tz.epoch_local_strptime_long(date_long_local)) # GMT: Thursday, December 5, 2019 21:00:00 # Local: Friday, December 6, 2019 0:00:00 GMT+03:00 epoch = 1575579600 date_short_local = "2019-12-06" print('epoch_local_strptime_short', tz.epoch_local_strptime_short(date_short_local)) <file_sep>/contrib/vjk-completion.sh _vjk() { local cmd cur prev words cword split=false if type -t _init_completion >/dev/null; then _init_completion -n = || return else # manual initialization for older bash completion versions COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" fi if [ $COMP_CWORD -gt 1 ] ; then cmd="${COMP_WORDS[1]}" else cmd="$prev" fi case "$cmd" in add) COMPREPLY=($(compgen -W '--category' -- $cur)) return ;; edit) COMPREPLY=($(compgen -W '--category --id --start --stop' -- $cur)) return ;; delete) COMPREPLY=($(compgen -W '--category --id' -- $cur)) return ;; list) COMPREPLY=($(compgen -W '--merge --category --start --stop --start-date --start-short-date --stop-date --stop-short-date --summary --long --raw --filter-category' -- $cur)) return ;; restart) COMPREPLY=($(compgen -W '--id --filter-category' -- $cur)) return ;; vjk) COMPREPLY=($(compgen -W 'start restart stop list add edit delete exit' -- $cur)) return ;; esac return } && complete -F _vjk vjk <file_sep>/src/client/vjk #!/usr/bin/python3 import argparse import datetime import calendar import logging import pprint import json import time import sys import os import re from datetime import datetime import vjk import vjktz def get_loglevel(num): lvl_nums = { 4: logging.DEBUG, 3: logging.DEBUG, 2: logging.INFO, 1: logging.WARNING, 0: logging.ERROR, } if num in lvl_nums: return lvl_nums[num] return logging.ERROR parser = argparse.ArgumentParser(prog='vjk.py') parser.add_argument('--conf', dest = 'conf', default = 'conf/vjk.json', help = 'configuration file in JSON format') sp = parser.add_subparsers(dest = 'cmd') for cmd in ['start']: spp = sp.add_parser(cmd, help = 'Start an activity. \ Format "activity@category,comment".') for cmd in ['restart']: spp = sp.add_parser(cmd, help = 'Restart last activity.') spp.add_argument('--id', dest = 'id', help = 'Activity ID', required = False) spp.add_argument('--filter-category', dest = 'filter_category', help = 'Filter by category') for cmd in ['stop']: spp = sp.add_parser(cmd, help = 'Stop the current activity if running.') for cmd in ['list']: spp = sp.add_parser(cmd, help = 'List activities/categories') spp.add_argument('--category', dest = 'category', help = 'Show categories', action = 'store_true') spp.add_argument('--filter-category', dest = 'filter_category', help = 'Filter by category') spp.add_argument('--summary', dest = 'summary', help = 'Show summary time spent', action = 'store_true') spp.add_argument('--merge', dest = 'merge', help = 'Merge same activities', action = 'store_true') spp.add_argument('--long', dest = 'long', help = 'Long output for time records.', action = 'store_true') spp.add_argument('--raw', dest = 'raw', help = 'Raw epoch output for time records.', action = 'store_true') spp.add_argument('--start', dest = 'start', help = 'Time to report from. Format [-]number[w|d|h])') spp.add_argument('--stop', dest = 'stop', help = 'Time to report until. Format [-]number[w|d|h])') spp.add_argument('--start-date', dest = 'start_date', help = 'Date to report from. Format YYYY-MM-DD hh:mm:ss)') spp.add_argument('--stop-date', dest = 'stop_date', help = 'Date to report until. Format YYYY-MM-DD hh:mm:ss)') spp.add_argument('--start-short-date', dest = 'start_short_date', help = 'Date to report from. Format YYYY-MM-DD)') spp.add_argument('--stop-short-date', dest = 'stop_short_date', help = 'Date to report until. Format YYYY-MM-DD)') for cmd in ['add']: spp = sp.add_parser(cmd, help = 'Add category') spp.add_argument('--category', dest = 'category', help = 'Category mode', action = 'store_true') for cmd in ['edit']: spp = sp.add_parser(cmd, help = 'Edit activity/category') spp.add_argument('--category', dest = 'category', help = 'Category mode', action = 'store_true') spp.add_argument('--start', dest = 'start', help = 'Date and time activity started at. \ Format [YYYY-MM-DD] hh:mm:ss.') spp.add_argument('--stop', dest = 'stop', help = 'Date and time activity stopped at. \ Format [YYYY-MM-DD] hh:mm:ss.') spp.add_argument('--id', dest = 'id', help = 'Activity/category ID', required = True) for cmd in ['delete']: spp = sp.add_parser(cmd, help = 'Delete activity/category') spp.add_argument('--category', dest = 'category', help = 'Category mode', action = 'store_true') spp.add_argument('--id', dest = 'id', help = 'Activity/category ID', required = True) for cmd in ['exit']: spp = sp.add_parser(cmd, help = 'Stop the server') args, unknown_args = parser.parse_known_args() if args.cmd == None: parser.print_help() sys.exit(1) conf = [] if args.conf != None and os.path.isfile(args.conf): with open(args.conf) as f: conf = json.load(f) else: if 'VJKCONF' in os.environ: with open(os.environ['VJKCONF']) as f: conf = json.load(f) else: logging.error("Provide server configuration") sys.exit(1) if 'loglevel-client' not in conf: loglevel = logging.DEBUG else: loglevel = get_loglevel(conf['loglevel-client']) logging.basicConfig(format = '%(asctime)s %(filename)s %(funcName)s %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = loglevel) logging.debug('Configuration') logging.debug(pprint.pformat(conf)) logging.debug(pprint.pformat(args)) def reply_ok(reply): '''Test if server reply is OK''' if reply: return reply.get('status') == 200 return False def reply_err(reply): '''Log server error and exit''' if reply == None: logging.error("ERR: Reply is empty") else: logging.error("ERR: Reply status %s data %s" % (reply.get('status', ""), reply.get('data', ""))) sys.exit(1) def reply_verify_data(reply): '''Validate server reply''' if reply_ok(reply): if reply.get('data'): return True return False reply_err(reply) return False def verify_tz_record(vjktz, d, name): '''Verify if time offset is present and matches required''' v = d.get(name) if v == None: logging.error("No time offset record") return False elif int(v) != vjktz.tzoff(): logging.error("Time offset record %d mismatches %d" % int(v), vjktz.tzoff()) return False return True def merge_records(vjktz, reply): '''Merge records with same name updating stop time to account time spent''' merged = { } def mergeable(vjktz, x): # # Make sure it started and finished for i in ['tsstart', 'tsstop']: if not x.get(i): return False # # Verify timezones for name in ['tzstart', 'tzstop']: if not verify_tz_record(vjktz, x, name): return False return True # # Chain by names into arrays or records. # We need to keep index of the record in # original @reply['data'] array so we could # mark seen entries and skip them from report. for idx, rec in enumerate(reply['data']): name = rec.get('name') if not name: continue if merged.get(name): merged[name].append([idx, rec]) else: merged[name] = [[idx, rec]] # # Preprocess merged records: # - drop entries with single record, which means # we ran some activity only once so no need to # to merge it and simply we will report it as is # - verify that start/stop times are present and # timezone offset is immutable for name in [k for k in merged.keys()]: if len(merged[name]) == 1: del merged[name] continue for i in range(0, len(merged[name])): rec = merged[name][i][1] if not mergeable(vjktz, rec): del merged[name] break # # Now do a real merge procedure: # - mark merged records in original @reply['data'] # with a sign # - count summary spent time and adjust stop time # for the first entry # - the rest of entries mark with 'skip' attribute for name in [k for k in merged.keys()]: pos = merged[name][0][0] top = reply['data'][pos] top['name'] += '*' top_epoch_start = int(top.get('tsstart')) top_epoch_stop = int(top.get('tsstop')) for i in range(1, len(merged[name])): pos = merged[name][i][0] rest = reply['data'][pos] rest_epoch_start = int(rest.get('tsstart')) rest_epoch_stop = int(rest.get('tsstop')) spent = rest_epoch_stop - rest_epoch_start top_epoch_stop += spent rest['skip'] = True top['tsstop'] = str(top_epoch_stop) del merged[name] def cmd_handler_invalid(vjkcli, vjktz, args, unknown_args): '''Print help and exit''' parser.print_help() sys.exit(1) def cmd_handler_activity_list(vjkcli, vjktz, args, unknown_args): '''List activities''' if args.start: report_from = vjktz.epoch_local_relative(args.start) elif args.start_date: report_from = vjktz.epoch_local_strptime_long(args.start_date) elif args.start_short_date: report_from = vjktz.epoch_local_strptime_short(args.start_short_date) else: # # If nothing specified use local today's start of day report_from = vjktz.epoch_local_000000() if report_from < 0: logging.error("Wrong start date/time specificator") return report_until = None if args.stop: report_until = vjktz.epoch_local_relative(args.stop) elif args.stop_date: report_until = vjktz.epoch_local_strptime_long(args.stop_date) elif args.stop_short_date: report_until = vjktz.epoch_local_strptime_short(args.stop_short_date) if report_until and report_until < 0: logging.error("Wrong stop date/time specificator") return catid = None if args.filter_category: reply = vjkcli.category_list(name=args.filter_category) if not reply_verify_data(reply): return if len(reply['data']) > 0: catid=reply['data'][0].get('id', None) # # We assume the time-zone offset is constant and # matches time-zone of the system. Otherwise this # needs to be fixed. reply = vjkcli.activity_list(report_from, report_until, catid=catid) if not reply_verify_data(reply): return if args.long: ts_len = 22 elif args.raw: ts_len = 12 else: ts_len = 10 catlen = 8 namelen = 4 for x in reply['data']: catlen = max(len(x.get('category', '')), catlen) namelen = max(len(x.get('name', '')), namelen) summary = int(0) fmt = "{1:<{0:}}{3:<{2:}}{5:<{4:}}{7:<{6:}}{9:<{8:}}{11:<{10:}}{13:<{12:}}" print(fmt.format(6, 'ID', (namelen + 2), 'Name', catlen + 2, 'Category', ts_len, 'Start', ts_len, 'Stop', 14, 'Duration', 16, 'Comment')) # # When merging we're manging the name so user # will notice and extend stop time. if args.merge: merge_records(vjktz, reply) for x in reply['data']: if x.get('skip'): continue timestamp_start = int(x.get('tsstart', 0)) if not verify_tz_record(vjktz, x, 'tzstart'): continue if timestamp_start < report_from: continue timestamp_stop = int(x.get('tsstop', 0)) if timestamp_stop == 0: spent = vjktz.epoch() - timestamp_start else: if not verify_tz_record(vjktz, x, 'tzstop'): continue spent = timestamp_stop - timestamp_start if report_until and report_until < timestamp_start: continue if args.long: timestamp_start_str = vjktz.local_strftime_long(timestamp_start) if timestamp_stop > 0: timestamp_stop_str = vjktz.local_strftime_long(timestamp_stop) elif args.raw: timestamp_start_str = str(timestamp_start) if timestamp_stop > 0: timestamp_stop_str = str(timestamp_stop) else: timestamp_start_str = vjktz.local_strftime_short(timestamp_start) if timestamp_stop > 0: timestamp_stop_str = vjktz.local_strftime_short(timestamp_stop) if timestamp_stop <= 0: timestamp_stop_str = '' summary += spent h, m, s = vjktz.seconds_to_hms(spent) hms = "{0:04d}:{1:02d}:{2:02d}".format(h, m, s) print(fmt.format(6, x['id'], (namelen + 2), x.get('name', ''), catlen + 2, x.get('category', ''), ts_len, timestamp_start_str, ts_len, timestamp_stop_str, 14, hms, 16, x.get('comment', ''))) if args.summary: h, m, s = vjktz.seconds_to_hms(summary) hms = "{0:04d}:{1:02d}:{2:02d}".format(h, m, s) print("---\nSummary: %s" % (hms)) def cmd_handler_category_list(vjkcli, vjktz, args, unknown_args): '''List categories''' reply = vjkcli.category_list() if not reply_verify_data(reply): return catlen = 8 for x in reply['data']: catlen = max(len(x.get('category', '')), catlen) fmt = "{1:<{0:}}{3:<{2:}}" print(fmt.format(6, 'ID', catlen + 2, 'Category')) for x in reply['data']: print(fmt.format(6, x.get('id', ''), catlen + 2, x.get('category',''))) def cmd_handler_delete_record(vjkcli, vjktz, args, unknown_args): '''Delete record by id''' if args.category: vjkcli.category_delete(int(args.id)) else: vjkcli.activity_delete(int(args.id)) def cmd_handler_server_exit(vjkcli, vjktz, args, unknown_args): '''Exit server''' vjkcli.server_exit() def parse_activity_argument(arg): '''Parse string in format activity@category|comment and return a tuple (activity,category,comment)''' m = re.match("([^\@]+)\@([^\,]+)(\,.+)?", arg) if m == None or m.group(1) == None or m.group(2) == None: return (None, None, None) comment = m.group(3) if comment != None: comment = m.group(3)[1:] return (m.group(1), m.group(2), comment) def cmd_handler_activity_start(vjkcli, vjktz, args, unknown_args): '''Start new activity''' # Previous must be stopped last_rec = vjkcli.activity_last() if len(last_rec.get('data',[])): tsstop = last_rec['data'][0].get('tsstop') if not tsstop: logging.error("Found an unfinished activity, stop it first") return if len(unknown_args) < 1: logging.error("Not enough arguments provided") return activity, category, comment = parse_activity_argument(unknown_args[0]) if activity == None: logging.error("Wrong activity format") return vjkcli.activity_add(vjktz.epoch(), None, activity, category, comment) def cmd_handler_activity_stop(vjkcli, vjktz, args, unknown_args): '''Stop current activity''' vjkcli.activity_stop(vjktz.epoch()) return def cmd_handler_activity_restart(vjkcli, vjktz, args, unknown_args): '''Restart activity''' if args.id: last_rec = vjkcli.activity_list(activity_id=args.id) else: last_rec = vjkcli.activity_last(filter_category=args.filter_category) if 'data' not in last_rec or len(last_rec['data']) < 1: logging.error("Can't fetch data") return tsstop = last_rec['data'][0].get('tsstop') if not tsstop: logging.error("Found an unfinished activity, stop it first") return if not last_rec['data'][0].get('tsstop'): logging.error('Last activity is still active') rec = last_rec['data'][0].get('name', '') + "@" + \ last_rec['data'][0].get('category', '') comment = last_rec['data'][0].get('comment') if comment: rec += "," + comment cmd_handler_activity_start(vjkcli, vjktz, args, [rec]) def cmd_handler_category_add(vjkcli, vjktz, args, unknown_args): '''Add new category''' if len(unknown_args) < 1: logging.error("Not enough arguments provided") return vjkcli.category_add(unknown_args[0]) def cmd_handler_activity_edit(vjkcli, vjktz, args, unknown_args): '''Edit existing activity''' if len(unknown_args) > 0: activity, category, comment = parse_activity_argument(unknown_args[0]) else: activity, category, comment = (None, None, None) if activity == None or category == None: reply = vjkcli.activity_list(None, None, args.id) if not reply_verify_data(reply): return if len(reply['data']) == 1: x = reply['data'][0] if activity == None: activity = x.get('name') if category == None: category = x.get('category') args.start = vjktz.epoch_local_strptime_long(args.start) if args.start < 0: logging.error("Wrong start time format") if args.stop: args.stop = vjktz.epoch_local_strptime_long(args.stop) if args.stop < 0: logging.error("Wrong stop time format") vjkcli.activity_update(args.id, args.start, args.stop, activity, category, comment) def cmd_handler_category_edit(vjkcli, vjktz, args, unknown_args): '''Edit category''' if len(unknown_args) < 1: logging.error("Not enough arguments provided") return vjkcli.category_update(args.id, unknown_args[0]) cmd_handler = { 'list': [True, cmd_handler_activity_list, cmd_handler_category_list], 'delete': [True, cmd_handler_delete_record, cmd_handler_delete_record], 'exit': [False, cmd_handler_server_exit, cmd_handler_invalid], 'start': [False, cmd_handler_activity_start, cmd_handler_invalid], 'restart': [False, cmd_handler_activity_restart, cmd_handler_invalid], 'stop': [False, cmd_handler_activity_stop, cmd_handler_invalid], 'add': [True, cmd_handler_invalid, cmd_handler_category_add], 'edit': [True, cmd_handler_activity_edit, cmd_handler_category_edit], } vjkcli = vjk.Vjk(logging, conf) if vjkcli.connected() == False: logging.error("Not connected") sys.exit(1) vjktz = vjktz.VjkTz() if args.cmd in cmd_handler: if cmd_handler[args.cmd][0]: if args.category: cmd_handler[args.cmd][2](vjkcli, vjktz, args, unknown_args) else: cmd_handler[args.cmd][1](vjkcli, vjktz, args, unknown_args) else: cmd_handler[args.cmd][1](vjkcli, vjktz, args, unknown_args) vjkcli.fini() <file_sep>/README.md ## VJK **VJK** is a simple time tracking tool. ### Client ![Client](/docs/client.png) ### Server ![Server](/docs/server.png) <file_sep>/src/client/vjk.py #!/usr/bin/python3 import socket import json import sys import vjktz class Vjk: def __init__(self, log, conf): '''Setup logger from @log and configuration from @conf. Then connect to a server.''' self.vjktz = vjktz.VjkTz() self.log = log self.conf = conf self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.addr, self.port = conf["address"].split(":") try: self.sock.connect((self.addr, int(self.port))) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.log.debug("Vjk: Connected") except: self.sock.close() self.sock = None self.log.error("Vjk: Can't connect %s:%s" % (self.addr, self.port)) def fini(self): '''Finalize Vjk. Close connection to a server.''' if self.connected(): obj = { 'cmd': 'fini' } self.send(obj) self.sock.close() self.sock = None self.log.debug("Vjk: Disconnected") def connected(self): '''Test if connection to a server is established.''' return self.sock != None def receive(self): '''Receive packet from a server.''' try: data = self.sock.recv(16) m = json.loads(data.decode('utf8').replace("'", '"')) if m.get('size'): self.log.debug("Vjk: recv size: %d" % (m.get('size'))) data = self.sock.recv(int(m.get('size'))) return json.loads(data.decode('utf8').replace("'", '"')) else: self.log.error("Vjk: no size obtained %s" % (repr(data))) except: return None def send_only(self, obj): '''Send packet to a server without receiving reply.''' try: seq = json.dumps(obj).encode() hdr = ("{\"size\":%7d}" % (len(seq))).encode('utf-8') self.log.debug("Vjk: send: %s %s" % (hdr, seq)) self.sock.send(hdr) self.sock.send(seq) except: return None def send(self, obj): '''Send packet to a server and receive a reply.''' self.send_only(obj) try: recv = self.receive() self.log.debug("Vjk: recv: %s" % (repr(recv))) return recv except: return None def server_exit(self): '''Force a server to exit.''' self.log.debug("Vjk: server_exit") obj = { 'cmd': 'exit' } self.send_only(obj) def activity_add(self, ts_start, ts_stop, activity, category, comment): '''Send new activity to a sever.''' self.log.debug("Vjk: activity_add: %s %s %s %s %s" % (repr(ts_start), repr(ts_stop), repr(activity), repr(category), repr(comment))) if ts_start == None: self.log.error("Vjk: activity_add: no start epoch") return None if activity == None or category == None: self.log.error("Vjk: activity_add: no activity/category") return None data = { 'activity': activity, 'category': category, 'tsstart': ts_start, 'tzstart': self.vjktz.tzoff() } if ts_stop: data['tsstop'] = ts_stop data['tzstop'] = self.vjktz.tzoff() if comment: data['comment'] = comment obj = { 'cmd': 'activity-start', 'data': data } return self.send(obj) def activity_last(self, filter_category=None): '''Fetch last activity from a server.''' self.log.debug("Vjk: activity_last: filter_category %s" % repr(filter_category)) obj = { 'cmd': 'activity-last' } if filter_category: reply = self.category_list(name=filter_category) if reply.get('status') == 200 and len(reply['data']) > 0: catid=reply['data'][0].get('id', None) if catid: data = {'catid': catid} obj['data'] = data return self.send(obj) def activity_stop(self, ts_stop): '''Send stop activity record.''' self.log.debug("Vjk: activity_stop: %s" % (repr(ts_stop))) if ts_stop == None: self.log.error("Vjk: activity_stop: no stop epoch") return None data = { 'tsstop': ts_stop, 'tzstop': self.vjktz.tzoff() } obj = { 'cmd': 'activity-stop', 'data': data } return self.send(obj) def activity_update(self, eid, ts_start, ts_stop, activity, category, comment): '''Update existing activity.''' self.log.debug("Vjk: activity_update: %s %s %s %s %s %s" % (repr(eid), repr(ts_start), repr(ts_stop), repr(activity), repr(category), repr(comment))) if eid == None: self.log.error("Vjk: activity_update: no ID") return None data = { 'id': eid } if activity: data['activity'] = activity if category: data['category'] = category if ts_start: data['tsstart'] = ts_start data['tzstart'] = self.vjktz.tzoff() if ts_stop: data['tsstop'] = ts_stop data['tzstop'] = self.vjktz.tzoff() if comment: data['comment'] = comment obj = { 'cmd': 'activity-update', 'data': data } return self.send(obj) def activity_list(self, ts_start=None, ts_stop=None, activity_id=None, catid=None): '''Fetch activities with params passed.''' self.log.debug("Vjk: activity_list: %s %s %s %s" % (repr(ts_start), repr(ts_stop), repr(activity_id), repr(catid))) data = { } if activity_id: data['id'] = activity_id else: if ts_start: data['tsstart'] = ts_start if ts_stop: data['tsstop'] = ts_stop if catid: data['catid'] = catid obj = { 'cmd': 'activity-list', 'data': data } return self.send(obj) def activity_delete(self, eid): '''Delete activity.''' self.log.debug("Vjk: activity_delete: %s" % (repr(eid))) if eid == None: self.log.error("Vjk: activity_delete: no ID") return None data = { 'id': eid } obj = { 'cmd': 'activity-delete', 'data': data } return self.send(obj) def category_add(self, category): '''Add category.''' if category == None: self.log.error("Vjk: category_add: no category") return None data = { 'category': category } obj = { 'cmd': 'category-add', 'data': data } return self.send(obj) def category_update(self, eid, category): '''Edit category.''' if eid == None or category == None: self.log.error("Vjk: category_update: no ID or category") return None data = { 'id': eid, 'category': category } obj = { 'cmd': 'category-update', 'data': data } return self.send(obj) def category_list(self, name=None): '''List categories.''' obj = { 'cmd': 'category-list' } if name: obj['data'] = { 'name': name } return self.send(obj) def category_delete(self, eid): '''Delete category.''' if eid == None: self.log.error("Vjk: category_delete: no ID") return None data = { 'id': eid } obj = { 'cmd': 'category-delete', 'data': data } return self.send(obj)
2befeeb2b061a53771e70eaffac2477d0ce549cd
[ "Markdown", "Python", "Makefile", "Shell" ]
6
Makefile
cyrillos/vjk
5a72bc7950f0d87d38b52f065ed4dd3e4345f8ed
f10fd1540c86737878547be1e978bf7fff6500d8
refs/heads/master
<repo_name>gwalus/CeneoSearcher<file_sep>/Shared/Dtos/ProductDto.cs namespace Shared.Dtos { /// <summary> /// ProductDto class to map product model with subscribed property. /// </summary> public class ProductDto { public string Name { get; set; } public string Link { get; set; } public string Image { get; set; } public string Rate { get; set; } public string Price { get; set; } public bool IsSubscribed { get; set; } } } <file_sep>/WebEngine/Model/ProductInteriorPrice.cs namespace WebEngine.Model { public class Offers { public double lowPrice { get; set; } } public class ProductInteriorPrice { public Offers offers { get; set; } } } <file_sep>/Shared/Model/Product.cs using System.ComponentModel.DataAnnotations; namespace Shared.Model { /// <summary> /// Basic product model class /// </summary> public class Product { public string Name { get; set; } [Key] public string Link { get; set; } public string Image { get; set; } public string Rate { get; set; } public string Price { get; set; } } } <file_sep>/DesktopClient/Services/ProductRepository.cs using DesktopClient.Interfaces; using Shared.Dtos; using Shared.Model; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Text.Json; using System.Threading.Tasks; using System.Web; namespace DesktopClient.Services { /// <summary> /// The service class of the queries to the api. /// </summary> public class ProductRepository : IProductRepository { private static readonly HttpClient _client = new HttpClient(); private static string uri; /// <summary> /// Constructor that puts a uri server into the uri variable.. /// </summary> /// <param name="serwerUri">uri as string</param> public ProductRepository(string serwerUri = "https://localhost:5001/") { uri = serwerUri; } /// <summary> /// Query for products with a given name. /// </summary> /// <param name="product">Name of product as string</param> /// <returns>Kolekcja produktów</returns> public async Task<ICollection<ProductDto>> GetProductsAsync(string product) { var Link = HttpUtility.UrlEncode(product); var products = (await _client.GetFromJsonAsync(uri + $"api/Ceneo/products/search/{Link}", typeof(ICollection<ProductDto>))) as ICollection<ProductDto>; return products; } /// <summary> /// Query for item subscribing. /// </summary> /// <param name="product">Product</param> /// <returns>Feedback from server</returns> public async Task<string> SubscribeProductAsync(Product product) { var message = await SendProductRequestAsync(product, $"{uri}api/Ceneo/product/subscribe"); return message; } /// <summary> /// Sending a query to the given url with product json. /// </summary> /// <param name="product">Product</param> /// <param name="url">url as string</param> /// <returns>Feedback from the server</returns> public async Task<string> SendProductRequestAsync(Product product, string url) { var response = string.Empty; var jsonString = JsonSerializer.Serialize<Product>(product); HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json"); HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(url), Content = content }; HttpResponseMessage result = await _client.SendAsync(request); if (result.IsSuccessStatusCode) { response = result.StatusCode.ToString(); } return response; } /// <summary> /// Url request /// </summary> /// <param name="url">Url for string queries</param> /// <returns>Feedback from the server</returns> public async Task<string> SendProductRequestAsync(string url) { var response = string.Empty; HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(url) }; HttpResponseMessage result = await _client.SendAsync(request); if (result.IsSuccessStatusCode) { response = result.StatusCode.ToString(); } return response; } /// <summary> /// Request for subscribed products. /// </summary> /// <returns>Collection of subscribed products</returns> public async Task<ICollection<Product>> GetSubscribeProductsAsync() { var products = (await _client.GetFromJsonAsync(uri + $"api/Ceneo/products", typeof(ICollection<Product>))) as ICollection<Product>; return products; } /// <summary> /// Unsubscribing product /// </summary> /// <param name="link">Id of product as string</param> /// <returns>Feedback from the server</returns> public async Task<string> UnSubscribeProductsAsync(string link) { var Link = HttpUtility.UrlEncode(link); var message = await SendProductRequestAsync($"{uri}api/Ceneo/product/unsubscribe?Link={Link}"); return message; } /// <summary> /// Check price /// </summary> /// <returns>Collection of subscribed items</returns> public async Task<ICollection<Product>> UpdateProductsAsync() { //var message = await SendProductRequestAsync($"{uri}api/Ceneo/product/checkprice"); try { var products = (await _client.GetFromJsonAsync($"{uri}api/Ceneo/product/checkprice", typeof(ICollection<Product>))) as ICollection<Product>; return products; } catch (Exception) { return null; throw; } } } } <file_sep>/WebEngine/Interfaces/IWebScraper.cs using Shared.Model; using System.Collections.Generic; namespace WebEngine.Interfaces { public interface IWebScraper { /// <summary> /// Scraps items from the page /// </summary> /// <param name="html">Link to list of products</param> /// <returns>List of Products</returns> List<Product> GetListOfProducts(string html); /// <summary> /// Gets item the lowest price /// </summary> /// <param name="link">Link to the specified product</param> /// <returns>Single product price</returns> double GetProductPrice(string link); } } <file_sep>/WebEngine/Startup.cs using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using WebEngine.Data; using WebEngine.Interfaces; using WebEngine.Services; using WebEngine.Repositories; using WebEngine.Helpers; namespace WebEngine { public class Startup { private readonly IConfiguration _configuration; public Startup(IConfiguration configuration) { _configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped<IWebScraper, WebScraper>(); services.AddScoped<IProductRepository, ProductRepository>(); services.AddDbContext<ProductContext>(options => { options.UseSqlite(_configuration.GetConnectionString("SqliteConnectionString")); }); services.AddAutoMapper(typeof(AutoMapperProfiles).Assembly); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebEngine", Version = "v1" }); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebEngine v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>/WebEngine/Helpers/AutoMapperProfiles.cs using AutoMapper; using Shared.Dtos; using Shared.Model; namespace WebEngine.Helpers { /// <summary> /// Class contains profiles to automapping between classes. /// </summary> public class AutoMapperProfiles : Profile { public AutoMapperProfiles() { CreateMap<Product, ProductDto>(); } } } <file_sep>/WebEngine/Controllers/CeneoController.cs using AutoMapper; using Microsoft.AspNetCore.Mvc; using Shared.Dtos; using Shared.Model; using System.Collections.Generic; using System.Threading.Tasks; using WebEngine.Interfaces; namespace WebEngine.Controllers { /// <summary> /// Ceneo controller class. Contains endpoints to work with ceneo. /// </summary> public class CeneoController : BaseApiController { private readonly IProductRepository _productRepository; private readonly IWebScraper _ceneoWebScraper; private readonly IMapper _mapper; private readonly string _baseUrl = "https://www.ceneo.pl/;szukaj-"; public CeneoController(IProductRepository productRepository, IWebScraper ceneoWebScraper, IMapper mapper) { _productRepository = productRepository; _ceneoWebScraper = ceneoWebScraper; _mapper = mapper; } /// <summary> /// Endpoint returns products from ceneo. /// </summary> /// <param name="keyword"></param> /// <returns>List of productsdto.</returns> [HttpGet("products/search/{keyword}")] public async Task<ActionResult<IList<ProductDto>>> GetProductsFromCeneo(string keyword) { var returnedProducts = new List<ProductDto>(); var ceneoProducts = _ceneoWebScraper.GetListOfProducts($"{_baseUrl}{keyword}"); if (ceneoProducts != null) { foreach (var product in ceneoProducts) { var mappedProduct = _mapper.Map<Product, ProductDto>(product); mappedProduct.IsSubscribed = await _productRepository.IfProductExists(product.Link); returnedProducts.Add(mappedProduct); } return Ok(returnedProducts); } return NotFound("No products were found for the keyword"); } /// <summary> /// Endpoint returns subscribed products. /// </summary> /// <returns>List of products.</returns> [HttpGet("products")] public async Task<ActionResult<ICollection<Product>>> GetProductsAsync() { var products = await _productRepository.GetSubscibedProductsAsync(); if (products != null) return Ok(products); return BadRequest("Data cannot be retrieved"); } /// <summary> /// Endpoint to add product to be subscribed. /// </summary> /// <param name="productToAdd"></param> /// <returns>ActionResult.</returns> [HttpPost("product/subscribe")] public async Task<ActionResult> SubscribeProduct(Product productToAdd) { if (await _productRepository.IfProductExists(productToAdd.Link)) return BadRequest("Product is already subscribed"); if (await _productRepository.AddProduct(productToAdd)) return Ok("Product has been subscribed"); return BadRequest(); } /// <summary> /// Endpoint to unsubscribe a product. /// </summary> /// <param name="link"></param> /// <returns>ActionResult.</returns> [HttpPost("product/unsubscribe")] public async Task<ActionResult> UnsubscribeProduct(string link) { if (await _productRepository.DeleteProduct(link)) return Ok("Product has been unsubscribed"); return BadRequest("Something went wrong"); } /// <summary> /// Endpoint to check actual product price. /// </summary> /// <returns>ActionResult or subscribed products when price was changed.</returns> [HttpGet("product/checkprice")] public async Task<ActionResult<IList<Product>>> CheckProductsPrice() { var products = await _productRepository.GetSubscibedProductsAsync(); if (products == null) return BadRequest("Data not found"); int updatedProducts = 0; foreach (var product in products) { double priceFromCeneo = _ceneoWebScraper.GetProductPrice(product.Link); double currentPrice = double.Parse(product.Price); if (priceFromCeneo != currentPrice && priceFromCeneo != 0) { product.Price = priceFromCeneo.ToString(); if (await _productRepository.UpdateProduct(product)) updatedProducts++; } } if(updatedProducts > 0) return Ok(await _productRepository.GetSubscibedProductsAsync()); return Ok("Product prices are up-to-date"); } } } <file_sep>/WebEngine.Test/CeneoControllerTests.cs using AutoFixture; using AutoFixture.AutoMoq; using Microsoft.EntityFrameworkCore; using Shared.Model; using System.Collections.Generic; using System.Linq; using WebEngine.Data; using WebEngine.Repositories; using Xunit; namespace WebEngine { public class CeneoControllerTests { private IList<Product> _products; [Fact] public void ShouldReturnAllProducts() { //Arange var options = new DbContextOptionsBuilder<ProductContext>() .UseInMemoryDatabase(databaseName: "ShouldGetAllProducts") .Options; var fixture = new Fixture().Customize(new AutoMoqCustomization()); _products = fixture.Create<IList<Product>>(); using (var context = new ProductContext(options)) { foreach (var product in _products) { context.Add(product); context.SaveChanges(); } } //Act IList<Product> actualProducts; using (var context = new ProductContext(options)) { var repository = new ProductRepository(context); actualProducts = repository.GetSubscibedProductsAsync().Result.ToList(); } //Assert Assert.Equal(_products.Count, actualProducts.Count); } } } <file_sep>/DesktopClient/Converters/BooleanToVisibilityButtonConverter.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; namespace DesktopClient.Converters { /// <summary> /// Class that converts a bool value to a visibility value. /// </summary> public class InvertableBooleanToVisibilityConverter : IValueConverter { enum Parameters { Normal, Inverted } /// <summary> /// Method that converts a bool (true, false) value to a visibility value(Visible, Collapsed). /// </summary> /// <param name="value">input parameter of bool type</param> /// <param name="targetType"></param> /// <param name="parameter"> Operation parameter - Normal or Inverted</param> /// <param name="culture"></param> /// <returns>Visibility value</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var boolValue = (bool)value; var direction = (Parameters)Enum.Parse(typeof(Parameters), (string)parameter); if (direction == Parameters.Inverted) return !boolValue ? Visibility.Visible : Visibility.Collapsed; return boolValue ? Visibility.Visible : Visibility.Collapsed; } /// <summary> /// Method that converts visibility (Visible, Collapsed) to bool (true, false). /// </summary> /// <param name="value">input parameter of type Visibility</param> /// <param name="targetType"></param> /// <param name="parameter">Operation parameter - Normal or Inverted</param> /// <param name="culture"></param> /// <returns>bool</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var VisibilityValue = (Visibility)value; var direction = (Parameters)Enum.Parse(typeof(Parameters), (string)parameter); if (direction == Parameters.Inverted) { if (VisibilityValue == Visibility.Visible) return false; else return true; } if (VisibilityValue == Visibility.Visible) return true; else return false; } } } <file_sep>/Readme.md ![](RackMultipart20210322-4-1q0k4u5_html_2dd637ae2fa5ca04.png) # Spis treści [1. Charakterystyka projektu 2](#_Toc67302452) [2.Specyfikacja wymagań funkcjonalnych 3](#_Toc67302453) [3.Specyfikacja wymagań niefunkcjonalnych 4](#_Toc67302454) [3.1 Główne informacje 4](#_Toc67302455) [3.2 Biblioteki 4](#_Toc67302456) [3.3 Specyfikacja niefunkcjonalna 4](#_Toc67302457) [4. Projekt systemu 5](#_Toc67302458) [4.1 UML 5](#_Toc67302459) [4.2 Baza danych 6](#_Toc67302460) [5. Przebieg techniczny projektu 6](#_Toc67302461) [5.1 Shared 6](#_Toc67302462) [5.2 WebEngine 6](#_Toc67302463) [5.3 DekstopClient 9](#_Toc67302464) [6. Organizacja pracy 10](#_Toc67302465) 1. # Charakterystyka projektu **Ceneo searcher** jest stosowany do wyszukiwania przedmiotów które mogą zainteresować użytkownika. Aplikacja wykorzystuję dane ze strony [www.ceneo.pl](http://www.ceneo.pl/) dzięki czemu jest w stanie wychwycić najniższe ceny produktów które mogą zainteresować potencjalnego konsumenta. Nasze oprogramowanie daje możliwość monitorowania zmiany cen zasubskrybowanych przedmiotów oraz pozwala na sprawdzenie pozycji tych pozycji nawet w trybie offline. 1. # Specyfikacja wymagań funkcjonalnych | ID | F1 | | --- | --- | | Nazwa | Pobieranie informacji ze strony internetowej | | Opis | Aplikacja ma możliwość wyciągania danych które nas zainteresowały ze strony www.ceneo.pl. | | ID | F2 | | --- | --- | | Nazwa | Prezentacja wyników (GUI) | | Opis | Aplikacja wyświetla w przejrzysty sposób wyniki wyszukiwania oraz zasubskrybowane przedmioty. | | ID | F3 | | --- | --- | | Nazwa | Wyszukiwanie produktów | | Opis | Użytkownik ma możliwość wyszukiwania produktów po wprowadzonych przez siebie frazach. | | ID | F4 | | --- | --- | | Nazwa | Subskrypcja produktu | | Opis | Zapisanie informacji o przedmiocie, który zainteresował użytkownika aplikacji i wyświetlanie ich w osobnej zakładce. | | ID | F5 | | --- | --- | | Nazwa | Aktualizowanie cen produktów | | Opis | Możliwość sprawdzania aktualnych cen produktów. | | ID | F6 | | --- | --- | | Nazwa | Przeglądanie zasubskrybowanych przedmiotów w trybie offline | | Opis | Użytkownik ma możliwość przeglądania swoich zasubskrybowanych przedmiotów w razie braku łączności z Internetem. | | ID | F7 | | --- | --- | | Nazwa | Płynne przełączanie się między zakładkami | | Opis | Możliwość przełączania się między wynikami wyszukiwania i zasubskrybowanymi przedmiotami które będą pokazywane w czasie rzeczywistym. | 1. # Specyfikacja wymagań niefunkcjonalnych ## 3.1 Główne informacje | Język programowania | C# | | --- | --- | | Platformy wspomagająca współpracę | Github.com, trello.com | | Silnik projektu | ASP.NET Core WebAPI | | Aplikacja kliencka | WPF .NET 5.0 | | Baza danych | SQLite | _Tabela 1 Główne informacje_ ## 3.2 Biblioteki | Nazwa biblioteki | Cel użycia | | --- | --- | | Entity Framework Core | Obsługa bazy danych | | Prism | Zorganizowanie czystego kodu | | RestSharp | Zapytania do HTTP | | XUnit | Testy jednostkowe | | AutoFixture | Testy TDD | | HtmlAgilityPack | Uzyskanie informacji ze strony ceneo.pl | | Material Design | Utworzenie przejrzystego stylu | | FontAwsome | Poprawienie szaty graficznej | _Tabela 2 Biblioteki_ ## 3.3 Specyfikacja niefunkcjonalna | ID | N1 | | --- | --- | | Nazwa | System organizacji pracy przy pomocy kanban board&#39;u | | Opis | Utworzenie tablicy w serwisie [www.trello.com](http://www.trello.com/) | | ID | N2 | | --- | --- | | Nazwa | Repozytorium internetowe | | Opis | Stworzenie repozytorium wspomagające wspólną prace w serwisie www.github.com | | ID | N3 | | --- | --- | | Nazwa | Utworzenie projektu | | Opis | Utworzenie projektu, w którym zawrą się wszystkie aplikacje oraz serwisy | | ID | N4 | | --- | --- | | Nazwa | Utworzenie silniku web | | Opis | Utworzenie silniku web który będzie zajmował się organizacją danych | | ID | N5 | | --- | --- | | Nazwa | Utworzenie aplikacji klienckiej | | Opis | Utworzenie aplikacji, dla klienta która będzie przejrzysta i intuicyjna | | ID | N6 | | --- | --- | | Nazwa | Utworzenie bazy danych | | Opis | Utworzenie bazy danych w której będą przechowywane elementy subskrypcji użytkownika | 1. # Projekt systemu ## 4.1 UML ![](RackMultipart20210322-4-1q0k4u5_html_df82146edb5b95cb.png) _Rysunek 1 Rysunek techniczny uml_ Rysunek przedstawiający zasadę działania całego projektu. ## 4.2 Baza danych | Product | | --- | | Nazwa: | Rodzaj: | | Name | string | | Link | string | | Image | string | | Rate | string | | Price | string | _Tabela 3 Struktura bazy danych_ 1. # Przebieg techniczny projektu ## 5.1 Shared Została utworzona biblioteka klas zawierająca modele by ograniczyć nadmiarowość klas oraz kodu. W tym miejscu zawarte są dwa foldery w każdy po jednej klasie: - Dtos - ProductDto - Name, - Link, - Image, - Rate, - Price, - IsSubscribed, - Model - Product - Name, - Link, - Image, - Rate, - Price, Są to modele, na których oparty jest cały projekt. Dzięki temu każdy element projektu, który wymaga odwołania się do tych struktur, zawszę otrzyma taki sam i dzięki temu pozbyliśmy się nadmiarowych tworzeń owych klas/modeli w każdej części projektu z osobna. ## 5.2 WebEngine Silnik, który został postawiony by niezależnie od aplikacji klienckiej zbierał informacje o produktach i działał w tle by użytkownik po uruchomieniu klienta mógł swobodnie wyszukiwać dane nie martwiąc się o brak połączenia. Silnik przy pomocy narzędzia o nazwie Swagger został naszym Web API. Głównym motywem wykorzystania tego sposobu była możliwość niezależnie od klienta sprawdzanie funkcjonalności co w późniejszym etapie pomogło przy komunikacji z klientem. Struktura silnika: - Klasa Program Miejsce, w którym znajduje się nasz **main** i od niego zaczyna się całe działanie programu - Klasa Startup W tej klasie zawarte są zawarte konfiguracje startowe wraz z zadeklarowaniem i ustawieniem naszych serwisów. - ConfigureServices Jako parametr wejściowy przyjmuje kolekcje serwisów które w późniejszym etapie wdraża do programu i konfiguruje. - Configure W tym miejscu konfiguracyjnym aplikacja sprawdza czy jest w stanie developerskim, jeśli tak to aplikacja ustawiana jest by działała zgodnie z możliwościami Swaggeru. Po przeglądnięciu tego warunku jest również ustawienie naszej aplikacji by używała odpowiednie ustawienia jakie zostały dla niej przydzielone. - Klasa WebScraper Ta klasa jest odpowiedzialna za zdobywanie informacji ze strony. Jako iż nie udało się uzyskać oficjalnego klucza do usług API dla [www.ceneo.pl](http://www.ceneo.pl/), aplikacja musiała dostać w inny sposób dane które potrzebuje. W tym celu została wykorzystana technika web scrapingu dzięki której po wyodrębnieniu informacji jakich potrzebujemy, przetwarzamy je na model, którym jest Product. Ta klasa zawiera metody takie jak: - Konstruktor, W tym miejscu inicjujemy zmienną przechowującą nową stronę internetową oraz listę typu produkt. - GetListOfProducts, Metoda, która przyjmuje zmienną typu string, a dokładniej to link, który zostanie wygenerowany po podaniu przez użytkownika wyszukiwanej frazy. Na tym etapie, metoda tworzy oraz zwraca listę z produktami które znajdą się na stronie. Przeszukuje wyznaczone miejsca w kodzie HTML strony i wyciąga informacje, które nas interesują takie jak nazwa, link do produktu, link do zdjęcia, ocenę oraz cenę. - GetProductPrice, Ta funkcjonalność również przyjmuje link tylko że już konkretnego elementu. Po sprawdzeniu czy link nie przekierowuje nas do strony zewnętrznej, wyciąga informacje o najniższej cenie proponowanej przez portal ceneo.pl. - Klasa ProductRepository Jest to repozytorium aplikacji dzięki któremu możemy wykonywać operacje z bazą danych. Metody w niej zawarte są asynchronicznymi taskami ponieważ nasza aplikacja musi czekać na otrzymanie informacji od bazy danych. Funkcje w niej zawarte to: | Nazwa funkcji | Opis | | --- | --- | | AddProduct | Dodanie produktu do bazy danych | | DeleteProduct | Usunięcie produktu z bazy danych | | GetSubscribedProductAsync | Pobranie z bazy zasubskrybowanych produktów | | IfProductExists | Sprawdza czy istnieje produkt o danym linku(id) | | UpdateProduct | Aktualizuje cenę produktu | _Tabela 4 Funkcje zawarte w ProductRepository_ - Klasa ProductInteriorPrice Znajduje się ona w folderze &quot;Model&quot;, jak wczesniej wspomniałem, posiadamy bibliotekę osobną, lecz w tym wypadku ten model znajduje się tylko w przestrzeni nazw silnika a nie całego projektu. Zawarte w niej są tak naprawdę dwie klasy, nadrzędna, czyli ProductInteriorPrice której właściwością jest Offers natomiast ona jest zadeklarowana również w tym pliku a zawiera ona lowPrice. - Interfejs IProductRepository - Interfejs IWebSCraper Korzystanie z interfejsów jest aktualnie standardem pracy, do naszych klas postanowiliśmy użyć tego sposobu by pisać kod czyściej, czytelniej i zgodnie z panującymi standardami. - Klasa AutoMapperProfiles Jest to klasa typu Helpers, dzięki niej projekt program jest w stanie przemapować klase Product na ProductDto. - Klasa ProductContext Zawiera kontekst potrzebny do wytworzenia bazy danych. - Klasa BaseApiController Kontroler dla naszego API. - Klasa CeneoController Ta klasa jest głównym kontrolerem serwera. W niej znajdują się metody, które decydują co wysłać w odpowiedzi do klienta. - GetProductsFromCeneo Metoda pobierająca informacje z ceneo.pl oraz sprawdzająca czy odpowiedź jaka przyszła nie jest nullem. Jeśli odpowiedź od strony jest prawidłowa, zwraca zmapowaną listę produktów, jeśli jednak jest nullem, zwróci wiadomość o błędzie do klienta. - GetProductsAsync Ten element aplikacji jest odpowiedzialny za zwrócenie do klienta listy rekordów z zasubskrybowanymi produktami. W razie problemów, zwróci wiadomość o błędzie do klienta. - SubscribeProduct Funkcja subskrybująca produkt która po wykonaniu akcji zwróci wiadomość, że produkt został dodany do listy bądź odpowie, że ten produkt się już na niej znajduje. - UnsubscribeProduct Funkcja, która usuwa przedmiot z listy subskrybowanych, po wykonaniu operacji zwraca odpowiedź czy udało się usunąć ten przedmiot. - CheckProductsPrice Metoda sprawdzająca czy w zasubskrybowanych produktach nie zaszła zmiana wartości ceny na niższą bądź wyższą co może pomoc w wyszukiwaniu okazji klientowi. ## 5.3 DekstopClient Nasza aplikacja kliencka jest stworzona standardem MVVM, dzięki temu praca nad projektem była płynna, przejrzysta i ułożona w odpowiedni sposób. Aplikacja prezentuje się w następujący sposób - Konwerter BooleanToVisibilityButtonConverter Jest to konwerter wspomagający elementy widoku, jest w stanie przekonwertować wartości true/false na Visible/Collapsed i odwrotnie, co pomaga przy wizualizacji elementów. - Interfejs IProductRepository - Klasa ProductRepository Zawiera wszystkie serwisy które wysyłają zapytania do serwera w sposób asynchroniczny jako Task. - Klasa MainWindowViewModel W tej klasie znajdziemy obsłużoną funkcjonalność klienta, wyszukiwanie, sprawdzanie poprawność wpisywanych fraz, subskrybowanie bądź usuwanie subskrypcji z przedmiotu. - Widok Jest to folder, który zawiera definicje przygotowanej szaty graficznej dla elementów w aplikacji klienckiej. ![](RackMultipart20210322-4-1q0k4u5_html_739b80bebd0cea4.png) _Rysunek 3 Projekt Shared_ ![](RackMultipart20210322-4-1q0k4u5_html_d41e498b8bd136a9.png) _Rysunek 4 Projekt WebEngine_ ![](RackMultipart20210322-4-1q0k4u5_html_c78b5571e5896bdf.png) _Rysunek 5 Projekt DesktopClient_ 1. # Organizacja pracy Podział zadań **<NAME>** - Utworzenie funkcjonalności silnika oraz połączenie z bazą danych. **<NAME>** - Utworzenie funkcjonalności do pozyskania informacji ze strony internetowej, utworzenie dokumentacji. **<NAME>** - Utworzenie oraz opracowanie aplikacji klienckiej. Praca jaka została wykonana nad projektem przebiegała w sposób płynny, cele były określane raz w tygodniu (poniedziałek), zebrania dotyczące dyskusji nad pracą odbywały się 2-4 razy w tygodniu. Łącznie na projekt zostało poświęcone 4 tygodnie pracy. Zadania jakie miały być realizowane, zostawały zapisane w serwisie Trello.com | Trello.com | https://trello.com/b/6ctaNJU3/ceneo | | --- | --- | | Github.com | https://github.com/gwalus/CeneoSearcher | _Linki do wykorzystania_ ![](RackMultipart20210322-4-1q0k4u5_html_7ddfa857d57958bd.png) _Rysunek 6 Trello_ Możliwość pisania wspólnego kodu została zrealizowana za pomocą serwisu github.com gdzie zostało utworzone repozytorium, w którym realizowaliśmy projekt. ![](RackMultipart20210322-4-1q0k4u5_html_a01a7272f5caf719.png) _Rysunek 7 GitHub_ ![](RackMultipart20210322-4-1q0k4u5_html_6205992337bf301d.png) _Rysunek 8 Statystyki github_ <file_sep>/WebEngine/Interfaces/IProductRepository.cs using Shared.Model; using System.Collections.Generic; using System.Threading.Tasks; namespace WebEngine.Interfaces { /// <summary> /// Product repository interface contains methods to operation of products. /// </summary> public interface IProductRepository { /// <summary> /// Returns subscribed products from database. /// </summary> /// <returns>List of products</returns> Task<ICollection<Product>> GetSubscibedProductsAsync(); /// <summary> /// Add product to database. /// </summary> /// <param name="productToAdd"></param> /// <returns>Bool</returns> Task<bool> AddProduct(Product productToAdd); /// <summary> /// Delete product from database. /// </summary> /// <param name="link"></param> /// <returns>Bool</returns> Task<bool> DeleteProduct(string link); /// <summary> /// Check if product already exists in database. /// </summary> /// <param name="link"></param> /// <returns>Bool</returns> Task<bool> IfProductExists(string link); /// <summary> /// Update product in database. /// </summary> /// <param name="productToUpdate"></param> /// <returns>Bool</returns> Task<bool> UpdateProduct(Product productToUpdate); } } <file_sep>/WebEngine/Repositories/ProductRepository.cs using Microsoft.EntityFrameworkCore; using Shared.Model; using System.Collections.Generic; using System.Threading.Tasks; using WebEngine.Data; using WebEngine.Interfaces; namespace WebEngine.Repositories { /// <summary> /// Product repository class contains methods to operation of products. /// </summary> /// <inheritdoc/> public class ProductRepository : IProductRepository { private ProductContext _context; public ProductRepository(ProductContext context) { _context = context; } public async Task<bool> AddProduct(Product productToAdd) { await _context.AddAsync(productToAdd); if (await _context.SaveChangesAsync() > 0) return true; return false; } public async Task<bool> DeleteProduct(string link) { var productToRemove = await _context.Products.SingleOrDefaultAsync(p => p.Link == link); _context.Remove(productToRemove); if (await _context.SaveChangesAsync() > 0) return true; return false; } public async Task<ICollection<Product>> GetSubscibedProductsAsync() { return await _context.Products.ToListAsync(); } public async Task<bool> IfProductExists(string link) { return await _context.Products.AnyAsync(p => p.Link == link); } public async Task<bool> UpdateProduct(Product productToUpdate) { _context.Entry(await _context.Products.FirstOrDefaultAsync(p => p.Link == productToUpdate.Link)).CurrentValues.SetValues(productToUpdate); if (await _context.SaveChangesAsync() > 0) return true; return false; } } } <file_sep>/DesktopClient/ViewModels/MainWindowViewModel.cs using DesktopClient.Interfaces; using Prism.Commands; using Prism.Mvvm; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Shared.Dtos; using Shared.Model; using System.Linq; using System.Windows; namespace DesktopClient.ViewModels { /// <summary> /// Main view. /// </summary> class MainWindowViewModel : BindableBase { /// <value>Loading product</value> private bool _loadButton; public bool LoadButton { get { return _loadButton; } set { SetProperty(ref _loadButton, value); } } /// <value>Collection of searched items</value> private ObservableCollection<ProductDto> _product; public ObservableCollection<ProductDto> Products { get { return _product; } set { SetProperty(ref _product, value); } } /// <value>Collection of subscribed items.</value> private ObservableCollection<Product> _subscribeProductCollection; public ObservableCollection<Product> SubscribeProductCollection { get { return _subscribeProductCollection; } set { SetProperty(ref _subscribeProductCollection, value); } } /// <value>Text from textbox</value> private string _text; public string Text { get { return _text; } set { SetProperty(ref _text, value); } } readonly IProductRepository _productRepository; // Definition of DelegateCommand public DelegateCommand SearchProductCommand { get; private set; } public DelegateCommand<string> GoToWebSiteProductCommand { get; private set; } public DelegateCommand<ProductDto> SubscribeProductCommand { get; private set; } public DelegateCommand<string> UnSubscribeProductCommand { get; private set; } public DelegateCommand UpdateProductCommand { get; private set; } /// <summary> /// Constructor assigning a dependency injection and create a DelegateCommand instance. /// </summary> /// <param name="productRepository">DI product repository</param> public MainWindowViewModel(IProductRepository productRepository) { _productRepository = productRepository; SearchProductCommand = new DelegateCommand(SearchProductAsync, CanSearchProduct); GoToWebSiteProductCommand = new DelegateCommand<string>(GoToWebSiteProduct, CanGoToWebSiteProduct); SubscribeProductCommand = new DelegateCommand<ProductDto>(SubscribeProduct, CanSubscribeProduct); UnSubscribeProductCommand = new DelegateCommand<string>(UnSubscribeProduct, CanUnSubscribeProduct); UpdateProductCommand = new DelegateCommand(UpdateProduct, CanUpdateProduct); LoadButton = false; GetSubscribeProduct(); } /// <summary> /// Method executed when calling the SearchProductCommand command, which gets the collection of products by name stored in _text and writes to the Products variable. /// </summary> async void SearchProductAsync() { if (!string.IsNullOrWhiteSpace(_text)) { var products = new ObservableCollection<ProductDto>(await Task.Run(() => _productRepository.GetProductsAsync(_text))); Products = products; } } /// <summary> /// A method that checks if the SearchProductAsync method can be executed. /// </summary> /// <returns>bool</returns> bool CanSearchProduct() { return true; } /// <summary> /// Method executed when calling the GoToWebSiteProductCommand command to open the product page. /// </summary> /// <param name="id">id as string</param> void GoToWebSiteProduct(string id) { var url = $"https://www.ceneo.pl/{id}"; try { Process.Start(url); } catch { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { url = url.Replace("&", "^&"); Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Process.Start("xdg-open", url); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Process.Start("open", url); } else { throw; } } } /// <summary> /// A method that checks if the GoToWebSiteProduct method can be executed /// </summary> /// <param name="id">Parameter as string</param> /// <returns>bool</returns> bool CanGoToWebSiteProduct(string id) { return true; } /// <summary> /// Method executed when calling the SubscribeProductCommand command to query the product to subscribe to. /// </summary> /// <param name="productDto">productDto as ProductDto</param> async void SubscribeProduct(ProductDto productDto) { if (productDto != null) { Product product = new Product() { Name = productDto.Name, Link = productDto.Link, Image = productDto.Image, Rate = productDto.Rate, Price = productDto.Price }; var message = await Task.Run(() => _productRepository.SubscribeProductAsync(product)); if (message == "OK") { Products.FirstOrDefault(p => p == productDto).IsSubscribed = true; Products = new ObservableCollection<ProductDto>(Products); SubscribeProductCollection.Add(product); } } } /// <summary> /// A method that checks if the SubscribeProduct method can be executed.. /// </summary> /// <param name="product">Parametr as ProductDto</param> /// <returns>bool</returns> bool CanSubscribeProduct(ProductDto product) { return true; } /// <summary> /// Method executed when calling the UnSubscribeProductCommand command, querying the product id to be unsubscribed. /// </summary> /// <param name="link"></param> async void UnSubscribeProduct(string link) { if (!string.IsNullOrWhiteSpace(link)) { var message = await Task.Run(() => _productRepository.UnSubscribeProductsAsync(link)); if (message == "OK") { if (Products != null) { var p = Products.FirstOrDefault(p => p.Link == link); if (p != null) { p.IsSubscribed = false; Products = new ObservableCollection<ProductDto>(Products); } } SubscribeProductCollection.Remove(SubscribeProductCollection.FirstOrDefault(p => p.Link == link)); } } } /// <summary> /// A method that checks if the UnSubscribeProduct method can be executed. /// </summary> /// <param name="link">Parametr as string</param> /// <returns>bool</returns> bool CanUnSubscribeProduct(string link) { return true; } /// <summary> /// A method that gets and enters the collection of the subscribed products into the SubscribeProductCollection field. /// </summary> async void GetSubscribeProduct() { SubscribeProductCollection = new ObservableCollection<Product>(await Task.Run(() => _productRepository.GetSubscribeProductsAsync())); } /// <summary> /// Database update method. /// </summary> async void UpdateProduct() { LoadButton = true; var products = await Task.Run(() => _productRepository.UpdateProductsAsync()); if (products != null) SubscribeProductCollection = new ObservableCollection<Product>(products); LoadButton = false; } /// <summary> /// A method that checks if the UpdateProduct method can be executed. /// </summary> /// <returns>Wartość bool</returns> bool CanUpdateProduct() { return true; } } } <file_sep>/WebEngine/Services/WebScraper.cs using HtmlAgilityPack; using Shared.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using WebEngine.Interfaces; using WebEngine.Model; namespace WebEngine.Services { public class WebScraper : IWebScraper { private readonly HtmlWeb _web; private List<Product> _products; public WebScraper() { _web = new HtmlWeb(); _products = new List<Product>(); } /// <summary> /// Method that allow us to scrap the information from the page /// <paramref name="html">Link to list of products </paramref> /// </summary> /// <returns>List of Products</returns> public List<Product> GetListOfProducts(string html) { var htmlDoc = _web.Load(html); try { foreach (HtmlNode link in htmlDoc.DocumentNode.SelectNodes("//div/div") .Where(x => x.GetAttributeValue("class", string.Empty) .Equals("cat-prod-row__body")) .ToList()) { Product element = new Product(); element.Link = link.SelectSingleNode("div/div/div/div/strong/a") .GetAttributeValue("href", string.Empty).Remove(0,1); element.Name = link.SelectSingleNode("div/div/div/div/strong/a") .InnerText; if (link.SelectSingleNode("div/a/img") .GetAttributeValue("src", string.Empty) .Equals("/content/img/icons/pix-empty.png")) { element.Image = link.SelectSingleNode("div/a/img") .GetAttributeValue("data-original", string.Empty).Insert(0,"http:"); } else { element.Image = link.SelectSingleNode("div/a/img") .GetAttributeValue("src", string.Empty).Insert(0, "http:"); } try { element.Rate = link.SelectNodes("div//span") .Where(x => x.GetAttributeValue("class", string.Empty) .Equals("product-score")) .First() .InnerText .Trim() .Remove(3); } catch (Exception) { element.Rate = string.Empty; } element.Price = link.SelectNodes("div/div") .Where(x => x.GetAttributeValue("class", string.Empty) .Equals("cat-prod-row__price")) .First() .SelectSingleNode("a//span/span") .InnerText; _products.Add(element); } return _products; } catch (Exception) { return _products; } } /// <summary> /// This method enter the link from the parameter and take the lowest price of the product if possible /// </summary> /// <param name="link">Link to the specified product</param> /// <returns>Single product price</returns> public double GetProductPrice(string link) { if (link.Contains("Click")) { return 0; } var htmlDoc = _web.Load("https://www.ceneo.pl/"+$"{link}"); var node = htmlDoc.DocumentNode.SelectSingleNode($"//script"); try { var productDetail = JsonSerializer.Deserialize<ProductInteriorPrice>(node.InnerText); return productDetail.offers.lowPrice; } catch (Exception) { throw; } } } } <file_sep>/DesktopClient/Interfaces/IProductRepository.cs using Shared.Dtos; using Shared.Model; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; namespace DesktopClient.Interfaces { /// <summary> /// Interface for the api service. /// </summary> public interface IProductRepository { Task<string> SendProductRequestAsync(Product product, string url); Task<ICollection<ProductDto>> GetProductsAsync(string product); Task<string> SubscribeProductAsync(Product product); Task<ICollection<Product>> GetSubscribeProductsAsync(); Task<string> UnSubscribeProductsAsync(string link); Task<ICollection<Product>> UpdateProductsAsync(); } }
2976f68b888d7456beb72f73fd3218e20c20b176
[ "Markdown", "C#" ]
16
C#
gwalus/CeneoSearcher
a684d7891e5e20efc5bf80dd97af8ab967f5321f
2018acde53270cf2eeeafac0c81874e5f11cad03
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /* ID: imzheng1 LANG: JAVA TASK: gift1 */ public class gift1 { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader("gift1.in")); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("gift1.out"))); int np = Integer.parseInt(reader.readLine()); List<String> members = new ArrayList<String>(); int[] value = new int[np]; for(int i = 0; i < np; i++) { members.add(reader.readLine()); } String giver = reader.readLine(); while(giver != null && !giver.trim().equals("")) { String[] numbers = reader.readLine().split(" "); int total = Integer.parseInt(numbers[0]); int num = Integer.parseInt(numbers[1]); if(num != 0) { int average = total / num; int remainder = total % num; int giverIndex = members.indexOf(giver); value[giverIndex] = value[giverIndex] - total + remainder; for(int i = 0; i < num; i++) { String receiver = reader.readLine(); int receiverIndex = members.indexOf(receiver); value[receiverIndex] = value[receiverIndex] + average; } } giver = reader.readLine(); } for(int i = 0; i < np; i++) { writer.println(members.get(i) + " " + value[i]); } writer.close(); reader.close(); } } <file_sep>/* ID: imzheng1 LANG: JAVA TASK: ride */ import java.io.*; public class ride { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader("ride.in")); PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("ride.out"))); String s1 = reader.readLine(); String s2 = reader.readLine(); int product1 = 1; int product2 = 1; for(int i = 0; i < s1.length(); ++i) { product1 *= s1.charAt(i) - 'A' + 1; } for(int i = 0; i < s2.length(); ++i) { product2 *= s2.charAt(i) - 'A' + 1; } if (product1 % 47 == product2 % 47) { writer.println("GO"); } else { writer.println("STAY"); } writer.close(); reader.close(); } }
87b783217165b57dd308d82dcb6c087489c3b5f7
[ "Java" ]
2
Java
ZhengZixiang/USACO-Java-Solution
a65e4181477b9b53551dfa38caed5a5e20f3c9d8
9e65ee8a30cc225f45a4ad83b818893614aef55f
refs/heads/master
<repo_name>hilltop16/basic-rest-api-go<file_sep>/main.go package main import "net/http" func main() { http.HandleFunc("/", serveRest) http.ListenAndServe("localhost:8000", nil) } func serveRest(w http.ResponseWriter, r *http.Request){ }
e2d4663b07f018705c43631ce2d5bb1279fd004b
[ "Go" ]
1
Go
hilltop16/basic-rest-api-go
39c1aabd5c7c185efddf4834c2706714f37b6558
80e6984f9b8a75feeb402cda29ddfbdaaee49a5f
refs/heads/master
<file_sep>//console.log("Hello world!"); var playText = document.getElementById('play-button-text'); var pauseText = document.getElementById('pause-button-text'); var playPause = document.getElementById('play-pause'); var wavesVideo = document.getElementById('waves-video'); //console.log(playText); //console.log(pauseText); //console.log(playPause); //console.log(wavesVideo); playPause.addEventListener("click", playControls); function playControls() { if (wavesVideo.paused) { wavesVideo.play(); playPause.innerHTML = `<i class="material-icons"> pause </i> Pause`; } else { wavesVideo.pause(); playPause.innerHTML = `<i class="material-icons"> play_arrow </i> Play`; } };
e05c6465d3186b3133876cdd9f8f7f53789b2d80
[ "JavaScript" ]
1
JavaScript
kellcore/netflix-replica
d796aa0795a5bb01c6ba96b6b3cbc34f67368b94
480b9748740516b5ebb09e924820138df5f431e0
refs/heads/master
<repo_name>vinkrish/tinyurl<file_sep>/model/db.js var mysql = require('mysql') // require('dotenv').config() var connection = mysql.createConnection({ host : process.env.DB_HOST, user : process.env.DB_USER, password : <PASSWORD>, database : process.env.DB_NAME, port : process.env.DB_PORT }); connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('Connected to database.'); }); // create table url( `id` BIGINT NOT NULL AUTO_INCREMENT, `lengthy_url` varchar(1024), `shortened_url` varchar(16), `hash` varchar(64), PRIMARY KEY (`id`) ); // alter table url AUTO_INCREMENT=1000000 // ALTER TABLE url ADD created_on BIGINT NOT NULL; // SELECT COUNT(*) as count, created_on FROM url GROUP BY created_on; // connection.end() module.exports = connection;<file_sep>/app.js var express = require('express') var cors = require('cors') var bodyParser = require('body-parser') var passport = require('passport') var session = require('express-session') var swaggerUi = require('swagger-ui-express'), swaggerDocument = require('./swagger.json'); require('dotenv').config() var app = express() var port = process.env.PORT || 3000 require('./config/passport')(passport) // set the view engine to ejs app.set('view engine', 'ejs') app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(cors()) app.use(session({ resave: false, saveUninitialized: true, secret: 'secretsession' })) app.use(passport.initialize()) app.use(passport.session()) // persistent login sessions app.get('/', function (req, res) { res.render('pages/index.ejs') }) app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); const apiRouter = require('./routes/apiRoutes')() app.use('/api', apiRouter) require('./routes/route.js')(app, passport) app.listen(port, function () { console.log('app running on port: ', port) }) module.exports = app <file_sep>/README.md # URL Shortener URL Shortener is an application which will convert long URL's to short URL's ## Steps to use the app The application is deployed at Amazon EC2 instance having public DNS: [ec2-54-197-199-83.compute-1.amazonaws.com](ec2-54-197-199-83.compute-1.amazonaws.com) As User: - No login in required for user to acces URL shortener service, hence accessing [ec2-54-197-199-83.compute-1.amazonaws.com](ec2-54-197-199-83.compute-1.amazonaws.com) will be suffice. - User must enter lenghty URL they want to convert. - Optional custom name can be provided to use in shortened URL, if the respective name is available user will get confirmation with shortened URL having custom name else unique alphanumeric URL shortener will be created. - User can now enter returned shortened URL in browser and our application will redirect it to respective original URL. Original URL: [http://www.amazon.com/Kindle-Wireless-Reading-Display-Globally/dp/B003FSUDM4/ref=amb_link_353259562_2?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-10&pf_rd_r=11EYKTN682A79T370AM3&pf_rd_t=201&pf_rd_p=1270985982&pf_rd_i=B002Y27P3M](http://www.amazon.com/Kindle-Wireless-Reading-Display-Globally/dp/B003FSUDM4/ref=amb_link_353259562_2?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=center-10&pf_rd_r=11EYKTN682A79T370AM3&pf_rd_t=201&pf_rd_p=1270985982&pf_rd_i=B002Y27P3M) Shortened URL: [ec2-54-197-199-83.compute-1.amazonaws.com/emjc](ec2-54-197-199-83.compute-1.amazonaws.com/emjc) As Admin: - You need to login first before accessing your dashboard: [ec2-54-197-199-83.compute-1.amazonaws.com/login](ec2-54-197-199-83.compute-1.amazonaws.com/login) - User `<EMAIL>` as email and `<PASSWORD>` as password to login. - Admin will see time series plot of number of URL's shortened over time. - Since we don't have custom domain we can't use google authentication. ## Application Architecture ![Architecture](https://vinkrish-notes.s3-us-west-2.amazonaws.com/img/URL+Shortener+Architecture.png) ### Methodology Following steps describes how the system is designed: To get Shortened URL: - Every new URL will be associated with Primary Key. - 62 alphanumeric characters are used to encode and convert Primary Key into unique base62 characters. - md5 hash of URL is also saved in system in order to reduce time required to search URL if already exist and thus avoiding shortened duplicate url's for same original URL. To get Original URL: - Extract base62 characters from shortened URL and use base62 decode function to find Primary Key used to encode. - User Primary Key to get original URL from database. - Above step is necessary in order to make our system faster, avoiding searching whole database. ### Sequence Diagram ![Sequence Digram](https://vinkrish-notes.s3-us-west-2.amazonaws.com/img/URL+Shortener+Sequence+Diagram.png) ## Developer Documentation API's are documented using SWAGGER, and it can be access with below URL: [ec2-54-197-199-83.compute-1.amazonaws.com/api-docs](ec2-54-197-199-83.compute-1.amazonaws.com/api-docs) <file_sep>/controller/adminController.js let db = require('../model/db') const { promisify } = require('util') const adminController = () => { const getTimeSeriesData = async (req, res) => { let promisifyDB = promisify(db.query).bind(db) const urls = await promisifyDB('SELECT COUNT(*) as count, created_on FROM url GROUP BY created_on') return res.send(JSON.stringify(urls)) } return { getTimeSeriesData: getTimeSeriesData } } module.exports = adminController <file_sep>/controller/urlController.js const crypto = require('crypto') var db = require('../model/db') const { promisify } = require('util') const urlController = () => { const ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" const BASE = ALPHABET.length const getShortUrl = async (req, res) => { const lengthyUrl = req.body.lengthy_url const customName = req.body.custom_name let custom_error, customUrl = '' const hashedUrl = crypto.createHash('md5').update(lengthyUrl).digest("hex") let promisifyDB = promisify(db.query).bind(db) const urls = await promisifyDB(`SELECT * FROM url WHERE hash = '${hashedUrl}'`) if (urls.length && customName) { return res.send({ providedUrl: urls[0].lengthy_url, shortenedUrl: urls[0].shortened_url, custom_error: 'The custom name you have provided is not available. We have created a random one for you instead.' }) } else if (urls.length) { return res.send({ providedUrl: urls[0].lengthy_url, shortenedUrl: urls[0].shortened_url, custom_error }) } let shortenedUrl = '' if (customName) { customUrl = await promisifyDB(`SELECT * FROM url WHERE shortened_url = '${customName}'`) if (customUrl) { shortenedUrl = customName } } let obj = {lengthy_url: lengthyUrl, hash: hashedUrl, created_on: new Date().getTime()} db.query('INSERT INTO url SET ?', obj, function (error, results, fields) { if (error) throw error; if (customUrl && shortenedUrl === "") { custom_error = 'The custom name you have provided is not available. We have created a random one for you instead.' } else { shortenedUrl = encode(results.insertId) } db.query('UPDATE url SET shortened_url=? where id=?', [shortenedUrl, results.insertId], function (error, results, fields) { if (error) throw error; return res.send({ providedUrl: lengthyUrl, shortenedUrl: shortenedUrl, custom_error}) }); }); } const reverseString = str => { return str.split('').reverse().join('') } const encode = num => { let str = ''; while (num > 0) { str = str.concat(ALPHABET[num % BASE]) num = Math.floor(num/BASE) } return reverseString(str) } return { getShortUrl: getShortUrl } } module.exports = urlController <file_sep>/config/passport.js var LocalStrategy = require('passport-local').Strategy var GoogleStrategy = require('passport-google-oauth2').Strategy var configAuth = require('./auth') module.exports = function (passport) { passport.serializeUser(function (user, done) { done(null, user) }) passport.deserializeUser(function (user, done) { done(null, user) }) passport.use('local-login', new LocalStrategy({ usernameField: 'email', passwordField: '<PASSWORD>', passReqToCallback: true }, function (req, email, password, done) { process.nextTick(function () { if (email == '<EMAIL>' && password == '<PASSWORD>') { return done(null, email) } else { return done('error logging in') } }) })) passport.use(new GoogleStrategy({ clientID: configAuth.googleAuth.clientId, clientSecret: configAuth.googleAuth.clientSecret, callbackURL: configAuth.googleAuth.callbackUrl, passReqToCallback: true }, function (request, accessToken, refreshToken, profile, done) { // make the code asynchronous process.nextTick(function () { return done(null, profile.id) }) })) }
9392fa327cbaff4b97e5e50013652b47980cd50a
[ "JavaScript", "Markdown" ]
6
JavaScript
vinkrish/tinyurl
f7953caa5f9672a2c61a381b4e73644b9c8dc47c
1a068e42c5005deffa99d0efb70ba5cf19df26e0
refs/heads/master
<file_sep># -*- coding: utf-8 -*- from openerp import models, fields, api class StudentWizard(models.TransientModel): _name = 'student.wizard' def _get_default_students(self): return self.env['students'].browse(self.env.context.get('active_ids')) student_ids = fields.Many2many('students', string='Student', default=_get_default_students) level = fields.Char('Level') @api.multi def set_student_level(self): for record in self: if record.student_ids: for student in record.student_ids: student.level = self.level @api.model def hide_action(self): if self.env.ref('student_wizard_action'): self.env.ref('student_wizard_action').unlink() <file_sep># odooERP This is about educational ERP website.
46f3301c494c47d06fe548153c735fb44d0144ee
[ "Markdown", "Python" ]
2
Python
poesane/odooERP
3f0bc1cc86231001aa516fe8971e72c1705a7eab
61501f48e3a323cafb0b3aada2646c0268cfbc14
refs/heads/main
<repo_name>ralexwong/front-end-projects<file_sep>/src/projects/StarRating/StarRating.jsx import React, { Fragment, useEffect, useState } from 'react'; import './style/index.scss'; const StarRating = (props) => { const [rating, setRating] = useState(null); const [hover, setHover] = useState(); // having a hook for the star color isn't necessary here but might be for bigger applications const [starColor, ] = useState('yellow') const clickHandler = (val) => { if (val === rating && rating !== null) { setRating(null); } else { setRating(val); } } useEffect(() => { document.title ='Give This Project a Rating!'; }, []) return <Fragment> <div className='stars'> {[...Array(5).keys()].map(n => { const ratingValue = n+1; return ( <span className="star" key={ratingValue} value={ratingValue} onMouseEnter={() => setHover(ratingValue)} onMouseLeave={() => setHover(null)} onClick={() => clickHandler(ratingValue)} style={{ color: ratingValue <= (hover || rating) ? starColor: '' }} > &#9733; </span> ); })} </div> </Fragment>; }; export default StarRating <file_sep>/src/projects/Popover/index.js import Popover from './Popover'; export default Popover; <file_sep>/src/projects/Accordian/Accordian.jsx import React, { useState } from 'react'; import './style/index.scss'; const info = [ { title: 'Accordian Title #1', caption: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." }, { title: 'Accordian Title #2', caption: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." }, { title: 'Accordian Title #3', caption: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." }, ] const Accordian = (props) => { const [currentAccordian, setCurrentAccordian] = useState() const activate = (val) => { if (val === currentAccordian) { return setCurrentAccordian(null) } setCurrentAccordian(val) } return <div className='container'> <div className='accordian'> {info.map((block, i) => { const accordianNumber = i+1 return <div key={i}> <div onClick={() => activate(accordianNumber)} className='accordian__title'> {block.title} <span className={`accordian__button ${ accordianNumber === currentAccordian ? 'accordian__button--open' : '' }`}>V</span> </div> <div className={`accordian__caption ${ accordianNumber === currentAccordian ? 'accordian__caption--open' : '' }`}> {block.caption} </div> </div> })} </div> </div>; }; export default Accordian <file_sep>/src/projects/Calculator/index.js import Calculator from './Calculator'; export default Calculator; <file_sep>/src/projects/Counter/Counter.jsx import React, { Fragment, useState } from 'react'; import styles from './style/index.scss'; const Counter = () => { const [count, setCount] = useState(0) return <Fragment> {count} <button className={styles.button} onClick={() => setCount(count+1)}>Increment</button> <button className={styles.button} onClick={() => setCount(count-1)}>Decrement</button> </Fragment>; }; export default Counter <file_sep>/src/data.js const data = [ { title : 'Star Rating', image : '', url : '/star-rating' }, { title : 'Accordian', image : '', url : '/accordian' }, { title : 'Counter', image : '', url : '/counter' }, { title : 'Calculator', image : '', url : '/calculator' }, { title : 'Popover', image : '', url : '/popover' }, { title : 'TicTacToe', image : '', url : '/tictactoe' }, ] export default data;<file_sep>/src/App.js import React from "react"; import { Router, Route, Switch } from "react-router-dom"; import history from './history'; import NoMatch from './NoMatch' import home from './Home' import StarRating from './projects/StarRating' import Accordian from './projects/Accordian' import Counter from './projects/Counter' import Calculator from './projects/Calculator' import Popover from './projects/Popover' import TicTacToe from './projects/TicTacToe' function App() { return ( <Router history={history}> <div> <Switch> <Route exact path="/" component={home} /> <Route exact path="/star-rating" component={StarRating} /> <Route exact path="/accordian" component={Accordian} /> <Route exact path="/counter" component={Counter} /> <Route exact path="/calculator" component={Calculator} /> <Route exact path="/popover" component={Popover} /> <Route exact path="/tictactoe" component={TicTacToe} /> <Route component={NoMatch} /> </Switch> </div> </Router> ); } export default App;<file_sep>/src/Home.js import React from 'react'; import { Link } from "react-router-dom"; import './home.scss'; import data from './data.js' const Home = () => { return <div> <h1>Front end Projects</h1> <div className='grid-container'> {data.map((project,i) => { return ( <Link to={project.url} key={i}> <div className='grid-item' > <img className='project__image' src={project.image} alt='invalid' /> <p className='project__title'>{project.title}</p> </div> </Link> ) })} </div> </div>; }; export default Home<file_sep>/src/projects/Popover/Popover.jsx import React, { useState } from 'react'; import './style/index.scss'; const data = ['TL', 'T', 'TR', 'L', 'M', 'R', 'BL', 'B', 'BR'] const Popover = () => { return <div className='center'> <div className='popover'> {data.map((box, i) => { return <div className='popover__container'> <div className='popover__box'>{box}</div> <div className={`popover__popover popover__popover--${box}`}>This is the content for {box} box</div> </div> })} </div> </div>; }; export default Popover <file_sep>/src/NoMatch.js import React, { Fragment } from 'react'; const NoMatch = () => { return <Fragment>No Match </Fragment>; }; export default NoMatch<file_sep>/README.md Will be creating these projects to practice my front-end capabilities and fundamanetals ![Optional Text](./project_ideas.png)
303d2c8659d10bd1596b0035ba726d697cb3e285
[ "JavaScript", "Markdown" ]
11
JavaScript
ralexwong/front-end-projects
9de5be6ab045444f4ff0a758cd8fc664ae10d018
f44f5284844f497b615edc7c0d804b1497d2e0d0
refs/heads/master
<file_sep>import Foundation enum Router { case getRepos(query: String, page: Int) case getAllUserRepos(name: String) var scheme: String { return "https" } var host: String { return "api.github.com" } var path: String { switch self { case .getRepos: return "/search/repositories" case .getAllUserRepos(let name): return "/users/\(name)/repos" } } var parameters: [URLQueryItem] { switch self { case .getRepos(let query, let page): return [ URLQueryItem(name: "q", value: query), URLQueryItem(name: "order", value: "asc"), URLQueryItem(name: "sort", value: "stars"), URLQueryItem(name: "page", value: "\(page)") ] case .getAllUserRepos: return [ URLQueryItem(name: "sort", value: "stars"), URLQueryItem(name: "order", value: "asc") ] } } var method: String { return "GET" } } <file_sep>import Foundation extension HTTPURLResponse { func isResponseOK() -> Bool { return (200...299).contains(self.statusCode) } } <file_sep>import Foundation extension String { func intValue() -> Int { return Int(self) ?? 0 } } <file_sep>import Foundation import Network class NetworkMonitor { private var monitor: NWPathMonitor private var queue: DispatchQueue var isAvailable = false private(set) status init() { self.monitor = NWPathMonitor() self.queue = DispatchQueue.global(qos: .background) self.monitor.start(queue: queue) } func startMonitoring() { self.monitor.pathUpdateHandler = { path in self.isAvailable = path.status == .satisfied status = .working } } func stopMonitoring() { self.monitor.cancel() status = .stopped } } <file_sep>import Foundation struct GHData: Decodable { let totalCount: Int let items: [Repo] } struct Repo: Decodable { let name: String let private: Bool let owner: Owner let description: String let createdAt: String let lastUpdate: String let language: String? //At some cases 'language' can be a nill, to avoid runtime errors that property must be optional } struct Owner: Decodable { let login: String let avatarUrl: URL let reposUrl: URL } <file_sep>import Foundation class NetworkService { func request<T: Decodable>(router: Router, completion: @escaping(Result<T, Error>) -> Void) { var components = URLComponents() components.scheme = router.scheme components.host = router.host components.path = router.path components.queryItems = router.parameters guard let url = components.url else { return } var urlRequest = URLRequest(url: url) urlRequest.httpMethod = router.method let urlSession = URLSession(configuration: .default) let dataTask = urlSession.dataTask(with: urlRequest) { (data, response, error) in if let error = error { debugPrint(error.localizedDescription) completion(.failure(error)) } guard let httpResponse = response as? HTTPURLResponse else { return } if !httpResponse.isResponseOK() { debugPrint("Status code different than OK: \(httpResponse.statusCode)") return } guard let data = data else { return } do { let responseObject = try JSONDecoder().decode(T.self, from: data) DispatchQueue.main.async { completion(.success(responseObject)) } } catch { debugPrint(error.localizedDescription) completion(.failure(error)) } } dataTask.resume() } }
7b690fabf7774c5d60e178afd1bd0c551c0fa5ec
[ "Swift" ]
6
Swift
MSlaski/workshop
d59cd54170c7b96f0638f154fe38e3681380f8e3
eac770f0c21f9a1717d3cec8888da1121c193c3a
refs/heads/master
<repo_name>chidiebereojingwa/shoppingPage-withCart<file_sep>/js/app.js //Variables const courses = document.querySelector('#courses-list') //Listeners loadEventListeners(); function loadEventListeners() { // When a new course is added courses.addEventListener('click',buyCourse) } //Functions function buyCourse(e) { e.preventDefault() // Use delegation to find the couse that was added if(e.target.classList.contains('add-to-cart')){ // read the course values const course = e.target.parentElement.parentElement; // read the values getCourseInfo(course); } } // Reads the HTML information of the selected course function getCourseInfo(course) { console.log(course) }
1eb30cdfc9228341ff2903d892074599f0b3d6c8
[ "JavaScript" ]
1
JavaScript
chidiebereojingwa/shoppingPage-withCart
c633835d89701f7b4966771307a7381dc14e417a
7de6cb5b0fa583a9550d30633596f8c1108eee10
refs/heads/master
<file_sep> CODE_GENERATOR_IMAGE := ghcr.io/slok/kube-code-generator:v1.27.0 CRD_GENERATOR_IMAGE := ghcr.io/slok/kube-code-generator:v1.27.0 DIRECTORY := $(PWD) ROOT_DIRECTORY := $(DIRECTORY)/../.. CODE_GENERATOR_PACKAGE := github.com/spotahome/kooper/examples/pod-terminator-operator/v2 generate: generate-client generate-crd generate-client: docker run --rm -it \ -v $(DIRECTORY):/go/src/$(CODE_GENERATOR_PACKAGE) \ -e PROJECT_PACKAGE=$(CODE_GENERATOR_PACKAGE) \ -e CLIENT_GENERATOR_OUT=$(CODE_GENERATOR_PACKAGE)/client/k8s \ -e APIS_ROOT=$(CODE_GENERATOR_PACKAGE)/apis \ -e GROUPS_VERSION="chaos:v1alpha1" \ -e GENERATION_TARGETS="deepcopy,client" \ $(CODE_GENERATOR_IMAGE) generate-crd: docker run -it --rm \ -v $(ROOT_DIRECTORY):/src \ -e GO_PROJECT_ROOT=/src/examples/pod-terminator-operator \ -e CRD_TYPES_PATH=/src/examples/pod-terminator-operator/apis \ -e CRD_OUT_PATH=/src/examples/pod-terminator-operator/manifests \ $(CRD_GENERATOR_IMAGE) update-crd.sh<file_sep>package main import ( "context" "flag" "fmt" "os" "os/signal" "path/filepath" "syscall" "time" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/controller/leaderelection" "github.com/spotahome/kooper/v2/log" kooperlogrus "github.com/spotahome/kooper/v2/log/logrus" ) const ( leaderElectionKey = "leader-election-example-controller" namespaceDef = "default" resyncIntervalSecondsDef = 30 ) // Flags are the flags of the program. type Flags struct { ResyncIntervalSeconds int Namespace string } // NewFlags returns the flags of the commandline. func NewFlags() *Flags { flags := &Flags{} fl := flag.NewFlagSet(os.Args[0], flag.ExitOnError) fl.IntVar(&flags.ResyncIntervalSeconds, "resync-interval", resyncIntervalSecondsDef, "resync seconds of the controller") fl.StringVar(&flags.Namespace, "namespace", namespaceDef, "kubernetes namespace where the controller is running") fl.Parse(os.Args[1:]) return flags } func run() error { // Flags fl := NewFlags() // Initialize logger. logger := kooperlogrus.New(logrus.NewEntry(logrus.New())). WithKV(log.KV{"example": "leader-election-controller"}) // Get k8s client. k8scfg, err := rest.InClusterConfig() if err != nil { // No in cluster? lets try locally kubehome := filepath.Join(homedir.HomeDir(), ".kube", "config") k8scfg, err = clientcmd.BuildConfigFromFlags("", kubehome) if err != nil { return fmt.Errorf("error loading kubernetes configuration: %s", err) } } k8scli, err := kubernetes.NewForConfig(k8scfg) if err != nil { return fmt.Errorf("error creating kubernetes client: %s", err) } // Create our retriever so the controller knows how to get/listen for pod events. retr := controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return k8scli.CoreV1().Pods("").List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return k8scli.CoreV1().Pods("").Watch(context.Background(), options) }, }) // Our domain logic that will print every add/sync/update and delete event we . hand := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { pod := obj.(*corev1.Pod) logger.Infof("Pod added: %s/%s", pod.Namespace, pod.Name) return nil }) // Leader election service. lesvc, err := leaderelection.NewDefault(leaderElectionKey, fl.Namespace, k8scli, logger) if err != nil { return err } // Create the controller and run. cfg := &controller.Config{ Name: "leader-election-controller", Handler: hand, Retriever: retr, LeaderElector: lesvc, Logger: logger, ProcessingJobRetries: 5, ResyncInterval: time.Duration(fl.ResyncIntervalSeconds) * time.Second, ConcurrentWorkers: 1, } ctrl, err := controller.New(cfg) if err != nil { return fmt.Errorf("error creating controller: %w", err) } ctx, cancel := context.WithCancel(context.Background()) defer cancel() errC := make(chan error) go func() { errC <- ctrl.Run(ctx) }() sigC := make(chan os.Signal, 1) signal.Notify(sigC, syscall.SIGTERM, syscall.SIGINT) select { case err := <-errC: if err != nil { logger.Infof("controller finished with error: %s", err) return err } logger.Infof("controller finished successfuly") case s := <-sigC: logger.Infof("signal %s received", s) cancel() } time.Sleep(5 * time.Second) return nil } func main() { if err := run(); err != nil { fmt.Fprintf(os.Stderr, "error executing controller: %s", err) os.Exit(1) } os.Exit(0) } <file_sep>package log import ( "github.com/spotahome/kooper/v2/log" ) // Logger is the interface of the operator logger. This is an example // so our Loggger will be the same as the kooper one. type Logger interface { log.Logger } <file_sep>package main import ( "flag" "os" "path/filepath" "time" "k8s.io/client-go/util/homedir" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/operator" ) // Flags are the controller flags. type Flags struct { flagSet *flag.FlagSet ResyncSec int KubeConfig string Development bool } // OperatorConfig converts the command line flag arguments to operator configuration. func (f *Flags) OperatorConfig() operator.Config { return operator.Config{ ResyncPeriod: time.Duration(f.ResyncSec) * time.Second, } } // NewFlags returns a new Flags. func NewFlags() *Flags { f := &Flags{ flagSet: flag.NewFlagSet(os.Args[0], flag.ExitOnError), } // Get the user kubernetes configuration in it's home directory. kubehome := filepath.Join(homedir.HomeDir(), ".kube", "config") // Init flags. f.flagSet.IntVar(&f.ResyncSec, "resync-seconds", 30, "The number of seconds the controller will resync the resources") f.flagSet.StringVar(&f.KubeConfig, "kubeconfig", kubehome, "kubernetes configuration path, only used when development mode enabled") f.flagSet.BoolVar(&f.Development, "development", false, "development flag will allow to run the operator outside a kubernetes cluster") f.flagSet.Parse(os.Args[1:]) return f } <file_sep>package main import ( "context" "flag" "fmt" "os" "path/filepath" "time" "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/log" kooperlogrus "github.com/spotahome/kooper/v2/log/logrus" ) var ( concurrentWorkers int sleepMS int intervalS int retries int disableResync bool ) func initFlags() error { fg := flag.NewFlagSet(os.Args[0], flag.ExitOnError) fg.IntVar(&concurrentWorkers, "concurrency", 3, "The number of concurrent event handling") fg.IntVar(&sleepMS, "sleep-ms", 25, "The number of milliseconds to sleep on each event handling") fg.IntVar(&intervalS, "interval-s", 45, "The number of seconds to for reconciliation loop intervals") fg.IntVar(&retries, "retries", 3, "The number of retries in case of error") fg.BoolVar(&disableResync, "disable-resync", false, "Disables the resync") err := fg.Parse(os.Args[1:]) if err != nil { return err } return nil } func sleep() { time.Sleep(time.Duration(sleepMS) * time.Millisecond) } func run() error { // Initialize logger. logger := kooperlogrus.New(logrus.NewEntry(logrus.New())). WithKV(log.KV{"example": "controller-concurrency-handling"}) // Init flags. if err := initFlags(); err != nil { return fmt.Errorf("error parsing arguments: %w", err) } // Get k8s client. k8scfg, err := rest.InClusterConfig() if err != nil { // No in cluster? letr's try locally kubehome := filepath.Join(homedir.HomeDir(), ".kube", "config") k8scfg, err = clientcmd.BuildConfigFromFlags("", kubehome) if err != nil { return fmt.Errorf("error loading kubernetes configuration: %w", err) } } k8scli, err := kubernetes.NewForConfig(k8scfg) if err != nil { return fmt.Errorf("error creating kubernetes client: %w", err) } // Create our retriever so the controller knows how to get/listen for pod events. retr := controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return k8scli.CoreV1().Pods("").List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return k8scli.CoreV1().Pods("").Watch(context.Background(), options) }, }) // Our domain logic that will print every add/sync/update and delete event we. hand := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { pod := obj.(*corev1.Pod) sleep() logger.Infof("Pod added: %s/%s", pod.Namespace, pod.Name) return nil }) // Create the controller. cfg := &controller.Config{ Name: "controller-concurrency-handling", Handler: hand, Retriever: retr, Logger: logger, ProcessingJobRetries: retries, ResyncInterval: time.Duration(intervalS) * time.Second, ConcurrentWorkers: concurrentWorkers, DisableResync: disableResync, } ctrl, err := controller.New(cfg) if err != nil { return fmt.Errorf("could not create controller: %w", err) } // Start our controller. ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := ctrl.Run(ctx); err != nil { return fmt.Errorf("error running controller: %w", err) } return nil } func main() { err := run() if err != nil { fmt.Fprintf(os.Stderr, "error running app: %s", err) os.Exit(1) } os.Exit(0) } <file_sep>package controller import ( "context" "fmt" "k8s.io/apimachinery/pkg/runtime" ) // Handler knows how to handle the received resources from a kubernetes cluster. type Handler interface { Handle(context.Context, runtime.Object) error } //go:generate mockery --case underscore --output controllermock --outpkg controllermock --name Handler // HandlerFunc knows how to handle resource adds. type HandlerFunc func(context.Context, runtime.Object) error // Handle satisfies controller.Handler interface. func (h HandlerFunc) Handle(ctx context.Context, obj runtime.Object) error { if h == nil { return fmt.Errorf("handle func is required") } return h(ctx, obj) } <file_sep>package logrus import ( "github.com/sirupsen/logrus" "github.com/spotahome/kooper/v2/log" ) type logger struct { *logrus.Entry } // New returns a new log.Logger for a logrus implementation. func New(l *logrus.Entry) log.Logger { return logger{Entry: l} } func (l logger) WithKV(kv log.KV) log.Logger { newLogger := l.Entry.WithFields(logrus.Fields(kv)) return New(newLogger) } <file_sep>package main import ( "context" "fmt" "os" "os/signal" "syscall" "time" "github.com/sirupsen/logrus" kooperlog "github.com/spotahome/kooper/v2/log" kooperlogrus "github.com/spotahome/kooper/v2/log/logrus" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" podtermk8scli "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/client/k8s/clientset/versioned" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/log" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/operator" ) // Main is the main program. type Main struct { flags *Flags config operator.Config logger log.Logger } // New returns the main application. func New(logger log.Logger) *Main { f := NewFlags() return &Main{ flags: f, config: f.OperatorConfig(), logger: logger, } } // Run runs the app. func (m *Main) Run(ctx context.Context) error { m.logger.Infof("initializing pod termination operator") // Get kubernetes rest client. ptCli, k8sCli, err := m.getKubernetesClients() if err != nil { return err } // Create the operator and run op, err := operator.New(m.config, ptCli, k8sCli, m.logger) if err != nil { return err } return op.Run(ctx) } // getKubernetesClients returns all the required clients to communicate with // kubernetes cluster: CRD type client, pod terminator types client, kubernetes core types client. func (m *Main) getKubernetesClients() (podtermk8scli.Interface, kubernetes.Interface, error) { var err error var cfg *rest.Config // If devel mode then use configuration flag path. if m.flags.Development { cfg, err = clientcmd.BuildConfigFromFlags("", m.flags.KubeConfig) if err != nil { return nil, nil, fmt.Errorf("could not load configuration: %s", err) } } else { cfg, err = rest.InClusterConfig() if err != nil { return nil, nil, fmt.Errorf("error loading kubernetes configuration inside cluster, check app is running outside kubernetes cluster or run in development mode: %s", err) } } // Create clients. k8sCli, err := kubernetes.NewForConfig(cfg) if err != nil { return nil, nil, err } // App CRD k8s types client. ptCli, err := podtermk8scli.NewForConfig(cfg) if err != nil { return nil, nil, err } return ptCli, k8sCli, nil } func main() { logger := kooperlogrus.New(logrus.NewEntry(logrus.New())). WithKV(kooperlog.KV{"example": "pod-terminator-operator"}) ctx, cancel := context.WithCancel(context.Background()) defer cancel() finishC := make(chan error) signalC := make(chan os.Signal, 1) signal.Notify(signalC, syscall.SIGTERM, syscall.SIGINT) m := New(logger) // Run in background the operator. go func() { finishC <- m.Run(ctx) }() select { case err := <-finishC: if err != nil { fmt.Fprintf(os.Stderr, "error running operator: %s", err) os.Exit(1) } case <-signalC: logger.Infof("Signal captured, exiting...") cancel() } time.Sleep(5 * time.Second) } <file_sep>package main import ( "context" "flag" "fmt" "math/rand" "net/http" "os" "path/filepath" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/log" kooperlogrus "github.com/spotahome/kooper/v2/log/logrus" kooperprometheus "github.com/spotahome/kooper/v2/metrics/prometheus" ) const ( metricsPrefix = "metricsexample" metricsAddr = ":7777" prometheusBackend = "prometheus" ) var ( metricsBackend string ) func initFlags() error { fg := flag.NewFlagSet(os.Args[0], flag.ExitOnError) fg.StringVar(&metricsBackend, "metrics-backend", "prometheus", "the metrics backend to use") return fg.Parse(os.Args[1:]) } // sleep will sleep randomly from 0 to 1000 milliseconds. func sleepRandomly() { r := rand.New(rand.NewSource(time.Now().UnixNano())) sleepMS := r.Intn(10) * 100 time.Sleep(time.Duration(sleepMS) * time.Millisecond) } // errRandomly will will err randomly. func errRandomly() error { r := rand.New(rand.NewSource(time.Now().UnixNano())) if r.Intn(10)%3 == 0 { return fmt.Errorf("random error :)") } return nil } // creates prometheus recorder and starts serving metrics in background. func createPrometheusRecorder(logger log.Logger) *kooperprometheus.Recorder { // We could use also prometheus global registry (the default one) // prometheus.DefaultRegisterer instead of creating a new one reg := prometheus.NewRegistry() rec := kooperprometheus.New(kooperprometheus.Config{Registerer: reg}) // Start serving metrics in background. h := promhttp.HandlerFor(reg, promhttp.HandlerOpts{}) go func() { logger.Infof("serving metrics at %s", metricsAddr) http.ListenAndServe(metricsAddr, h) }() return rec } func run() error { // Initialize logger. logger := kooperlogrus.New(logrus.NewEntry(logrus.New())). WithKV(log.KV{"example": "metrics-controller"}) // Init flags. if err := initFlags(); err != nil { return fmt.Errorf("error parsing arguments: %w", err) } // Get k8s client. k8scfg, err := rest.InClusterConfig() if err != nil { // No in cluster? letr's try locally kubehome := filepath.Join(homedir.HomeDir(), ".kube", "config") k8scfg, err = clientcmd.BuildConfigFromFlags("", kubehome) if err != nil { return fmt.Errorf("error loading kubernetes configuration: %w", err) } } k8scli, err := kubernetes.NewForConfig(k8scfg) if err != nil { return fmt.Errorf("error creating kubernetes client: %w", err) } // Create our retriever so the controller knows how to get/listen for pod events. retr := controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return k8scli.CoreV1().Pods("").List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return k8scli.CoreV1().Pods("").Watch(context.Background(), options) }, }) // Our domain logic that will print every add/sync/update and delete event we . hand := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { sleepRandomly() return errRandomly() }) // Create the controller that will refresh every 30 seconds. cfg := &controller.Config{ Name: "metricsControllerTest", Handler: hand, Retriever: retr, MetricsRecorder: createPrometheusRecorder(logger), Logger: logger, ProcessingJobRetries: 3, } ctrl, err := controller.New(cfg) if err != nil { return fmt.Errorf("could not create controller: %w", err) } // Start our controller. ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := ctrl.Run(ctx); err != nil { return fmt.Errorf("error running controller: %w", err) } return nil } func main() { err := run() if err != nil { fmt.Fprintf(os.Stderr, "error running app: %s", err) os.Exit(1) } os.Exit(0) } <file_sep>package prometheus_test import ( "context" "io" "net/http/httptest" "testing" "time" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/stretchr/testify/assert" kooperprometheus "github.com/spotahome/kooper/v2/metrics/prometheus" ) func TestPrometheusRecorder(t *testing.T) { tests := map[string]struct { cfg kooperprometheus.Config addMetrics func(*kooperprometheus.Recorder) expMetrics []string }{ "Incremeneting the total queued resource events should record the metrics.": { addMetrics: func(r *kooperprometheus.Recorder) { ctx := context.TODO() r.IncResourceEventQueued(ctx, "ctrl1", false) r.IncResourceEventQueued(ctx, "ctrl1", false) r.IncResourceEventQueued(ctx, "ctrl2", false) r.IncResourceEventQueued(ctx, "ctrl3", true) r.IncResourceEventQueued(ctx, "ctrl3", true) r.IncResourceEventQueued(ctx, "ctrl3", false) }, expMetrics: []string{ `# HELP kooper_controller_queued_events_total Total number of events queued.`, `# TYPE kooper_controller_queued_events_total counter`, `kooper_controller_queued_events_total{controller="ctrl1",requeue="false"} 2`, `kooper_controller_queued_events_total{controller="ctrl2",requeue="false"} 1`, `kooper_controller_queued_events_total{controller="ctrl3",requeue="false"} 1`, `kooper_controller_queued_events_total{controller="ctrl3",requeue="true"} 2`, }, }, "Observing the duration in queue of events should record the metrics.": { addMetrics: func(r *kooperprometheus.Recorder) { ctx := context.TODO() t0 := time.Now() r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-30*time.Second)) r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-127*time.Millisecond)) r.ObserveResourceInQueueDuration(ctx, "ctrl2", t0.Add(-70*time.Millisecond)) r.ObserveResourceInQueueDuration(ctx, "ctrl2", t0.Add(-35*time.Millisecond)) r.ObserveResourceInQueueDuration(ctx, "ctrl2", t0.Add(-500*time.Millisecond)) r.ObserveResourceInQueueDuration(ctx, "ctrl2", t0.Add(-2*time.Second)) }, expMetrics: []string{ `# HELP kooper_controller_event_in_queue_duration_seconds The duration of an event in the queue.`, `# TYPE kooper_controller_event_in_queue_duration_seconds histogram`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="0.01"} 0`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="0.05"} 0`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="0.1"} 0`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="0.25"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="0.5"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="1"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="3"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="10"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="20"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="60"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="150"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="300"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="+Inf"} 2`, `kooper_controller_event_in_queue_duration_seconds_count{controller="ctrl1"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="0.01"} 0`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="0.05"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="0.1"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="0.25"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="0.5"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="1"} 3`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="3"} 4`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="10"} 4`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="20"} 4`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="60"} 4`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="150"} 4`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="300"} 4`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl2",le="+Inf"} 4`, `kooper_controller_event_in_queue_duration_seconds_count{controller="ctrl2"} 4`, }, }, "Observing the duration in queue of events should record the metrics (Custom buckets).": { cfg: kooperprometheus.Config{ InQueueBuckets: []float64{10, 20, 30, 50}, }, addMetrics: func(r *kooperprometheus.Recorder) { ctx := context.TODO() t0 := time.Now() r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-6*time.Second)) r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-12*time.Second)) r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-25*time.Second)) r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-60*time.Second)) r.ObserveResourceInQueueDuration(ctx, "ctrl1", t0.Add(-70*time.Second)) }, expMetrics: []string{ `# HELP kooper_controller_event_in_queue_duration_seconds The duration of an event in the queue.`, `# TYPE kooper_controller_event_in_queue_duration_seconds histogram`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="10"} 1`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="20"} 2`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="30"} 3`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="50"} 3`, `kooper_controller_event_in_queue_duration_seconds_bucket{controller="ctrl1",le="+Inf"} 5`, `kooper_controller_event_in_queue_duration_seconds_count{controller="ctrl1"} 5`, }, }, "Observing the duration of processing events should record the metrics.": { addMetrics: func(r *kooperprometheus.Recorder) { ctx := context.TODO() t0 := time.Now() r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-3*time.Second)) r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-280*time.Millisecond)) r.ObserveResourceProcessingDuration(ctx, "ctrl2", true, t0.Add(-7*time.Second)) r.ObserveResourceProcessingDuration(ctx, "ctrl2", false, t0.Add(-35*time.Millisecond)) r.ObserveResourceProcessingDuration(ctx, "ctrl2", true, t0.Add(-770*time.Millisecond)) r.ObserveResourceProcessingDuration(ctx, "ctrl2", false, t0.Add(-17*time.Millisecond)) }, expMetrics: []string{ `# HELP kooper_controller_processed_event_duration_seconds The duration for an event to be processed.`, `# TYPE kooper_controller_processed_event_duration_seconds histogram`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.005"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.01"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.025"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.05"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.1"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.25"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="0.5"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="1"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="2.5"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="5"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="10"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="+Inf"} 2`, `kooper_controller_processed_event_duration_seconds_count{controller="ctrl1",success="true"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.005"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.01"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.025"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.05"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.1"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.25"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="0.5"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="1"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="2.5"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="5"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="10"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="false",le="+Inf"} 2`, `kooper_controller_processed_event_duration_seconds_count{controller="ctrl2",success="false"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.005"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.01"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.025"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.05"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.1"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.25"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="0.5"} 0`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="1"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="2.5"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="5"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="10"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl2",success="true",le="+Inf"} 2`, `kooper_controller_processed_event_duration_seconds_count{controller="ctrl2",success="true"} 2`, }, }, "Observing the duration of processing events should record the metrics (Custom buckets).": { cfg: kooperprometheus.Config{ ProcessingBuckets: []float64{10, 20, 30, 50}, }, addMetrics: func(r *kooperprometheus.Recorder) { ctx := context.TODO() t0 := time.Now() r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-6*time.Second)) r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-12*time.Second)) r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-25*time.Second)) r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-60*time.Second)) r.ObserveResourceProcessingDuration(ctx, "ctrl1", true, t0.Add(-70*time.Second)) }, expMetrics: []string{ `# HELP kooper_controller_processed_event_duration_seconds The duration for an event to be processed.`, `# TYPE kooper_controller_processed_event_duration_seconds histogram`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="10"} 1`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="20"} 2`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="30"} 3`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="50"} 3`, `kooper_controller_processed_event_duration_seconds_bucket{controller="ctrl1",success="true",le="+Inf"} 5`, `kooper_controller_processed_event_duration_seconds_count{controller="ctrl1",success="true"} 5`, }, }, "Registering resource queue lenght function should measure the size of the queue.": { cfg: kooperprometheus.Config{}, addMetrics: func(r *kooperprometheus.Recorder) { _ = r.RegisterResourceQueueLengthFunc("ctrl1", func(_ context.Context) int { return 42 }) _ = r.RegisterResourceQueueLengthFunc("ctrl2", func(_ context.Context) int { return 142 }) _ = r.RegisterResourceQueueLengthFunc("ctrl3", func(_ context.Context) int { return 242 }) }, expMetrics: []string{ `# HELP kooper_controller_event_queue_length Length of the controller resource queue.`, `# TYPE kooper_controller_event_queue_length gauge`, `kooper_controller_event_queue_length{controller="ctrl1"} 42`, `kooper_controller_event_queue_length{controller="ctrl2"} 142`, `kooper_controller_event_queue_length{controller="ctrl3"} 242`, }, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) // Create a new prometheus empty registry and a kooper prometheus recorder. reg := prometheus.NewRegistry() test.cfg.Registerer = reg m := kooperprometheus.New(test.cfg) // Add desired metrics test.addMetrics(m) // Ask prometheus for the metrics h := promhttp.HandlerFor(reg, promhttp.HandlerOpts{}) r := httptest.NewRequest("GET", "/metrics", nil) w := httptest.NewRecorder() h.ServeHTTP(w, r) resp := w.Result() // Check all metrics are present. body, _ := io.ReadAll(resp.Body) for _, expMetric := range test.expMetrics { assert.Contains(string(body), expMetric, "metric not present on the result of metrics service") } }) } } <file_sep>#!/bin/bash set -o errexit set -o nounset KUBERNETES_VERSION=v${KUBERNETES_VERSION:-1.27.3} current_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PREVIOUS_KUBECTL_CONTEXT=$(kubectl config current-context) || PREVIOUS_KUBECTL_CONTEXT="" function cleanup { if [ ! -z $PREVIOUS_KUBECTL_CONTEXT ]; then kubectl config use-context $PREVIOUS_KUBECTL_CONTEXT fi echo "=> Removing kind cluster" kind delete cluster } trap cleanup EXIT echo "=> Preparing kind for running integration tests" kind create cluster --image kindest/node:${KUBERNETES_VERSION} kubectl config use-context kind-kind echo "=> Running integration tests" ${current_dir}/integration-test.sh <file_sep>package prometheus import ( "context" "fmt" "strconv" "time" "github.com/prometheus/client_golang/prometheus" "github.com/spotahome/kooper/v2/controller" ) const ( promNamespace = "kooper" promControllerSubsystem = "controller" ) // Config is the Recorder Config. type Config struct { // Registerer is a prometheus registerer, e.g: prometheus.Registry. // By default will use Prometheus default registry. Registerer prometheus.Registerer // InQueueBuckets sets custom buckets for the duration/latency items in queue metrics. // Check https://godoc.org/github.com/prometheus/client_golang/prometheus#pkg-variables InQueueBuckets []float64 // ProcessingBuckets sets custom buckets for the duration/latency processing metrics. // Check https://godoc.org/github.com/prometheus/client_golang/prometheus#pkg-variables ProcessingBuckets []float64 } func (c *Config) defaults() { if c.Registerer == nil { c.Registerer = prometheus.DefaultRegisterer } if c.InQueueBuckets == nil || len(c.InQueueBuckets) == 0 { // Use bigger buckets thant he default ones because the times of waiting queues // usually are greater than the handling, and resync of events can be minutes. c.InQueueBuckets = []float64{.01, .05, .1, .25, .5, 1, 3, 10, 20, 60, 150, 300} } if c.ProcessingBuckets == nil || len(c.ProcessingBuckets) == 0 { c.ProcessingBuckets = prometheus.DefBuckets } } // Recorder implements the metrics recording in a prometheus registry. type Recorder struct { reg prometheus.Registerer queuedEventsTotal *prometheus.CounterVec inQueueEventDuration *prometheus.HistogramVec processedEventDuration *prometheus.HistogramVec } // New returns a new Prometheus implementaiton for a metrics recorder. func New(cfg Config) *Recorder { cfg.defaults() r := &Recorder{ reg: cfg.Registerer, queuedEventsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{ Namespace: promNamespace, Subsystem: promControllerSubsystem, Name: "queued_events_total", Help: "Total number of events queued.", }, []string{"controller", "requeue"}), inQueueEventDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: promNamespace, Subsystem: promControllerSubsystem, Name: "event_in_queue_duration_seconds", Help: "The duration of an event in the queue.", Buckets: cfg.InQueueBuckets, }, []string{"controller"}), processedEventDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{ Namespace: promNamespace, Subsystem: promControllerSubsystem, Name: "processed_event_duration_seconds", Help: "The duration for an event to be processed.", Buckets: cfg.ProcessingBuckets, }, []string{"controller", "success"}), } // Register metrics. r.reg.MustRegister( r.queuedEventsTotal, r.inQueueEventDuration, r.processedEventDuration) return r } // IncResourceEventQueued satisfies controller.MetricsRecorder interface. func (r Recorder) IncResourceEventQueued(ctx context.Context, controller string, isRequeue bool) { r.queuedEventsTotal.WithLabelValues(controller, strconv.FormatBool(isRequeue)).Inc() } // ObserveResourceInQueueDuration satisfies controller.MetricsRecorder interface. func (r Recorder) ObserveResourceInQueueDuration(ctx context.Context, controller string, queuedAt time.Time) { r.inQueueEventDuration.WithLabelValues(controller). Observe(time.Since(queuedAt).Seconds()) } // ObserveResourceProcessingDuration satisfies controller.MetricsRecorder interface. func (r Recorder) ObserveResourceProcessingDuration(ctx context.Context, controller string, success bool, startProcessingAt time.Time) { r.processedEventDuration.WithLabelValues(controller, strconv.FormatBool(success)). Observe(time.Since(startProcessingAt).Seconds()) } // RegisterResourceQueueLengthFunc satisfies controller.MetricsRecorder interface. func (r Recorder) RegisterResourceQueueLengthFunc(controller string, f func(context.Context) int) error { err := r.reg.Register(prometheus.NewGaugeFunc( prometheus.GaugeOpts{ Namespace: promNamespace, Subsystem: promControllerSubsystem, Name: "event_queue_length", Help: "Length of the controller resource queue.", ConstLabels: prometheus.Labels{"controller": controller}, }, func() float64 { return float64(f(context.Background())) }, )) if err != nil { return fmt.Errorf("could not register ResourceQueueLengthFunc metrics: %w", err) } return nil } // Check interfaces implementation. var _ controller.MetricsRecorder = &Recorder{} <file_sep>package chaos import ( "context" "fmt" "math/rand" "reflect" "sort" "sync" "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/kubernetes" chaosv1alpha1 "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/apis/chaos/v1alpha1" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/log" ) // TimeWrapper is a wrapper around time so it can be mocked type TimeWrapper interface { // After is the same as time.After After(d time.Duration) <-chan time.Time // Now is the same as Now. Now() time.Time } type timeStd struct{} func (t *timeStd) After(d time.Duration) <-chan time.Time { return time.After(d) } func (t *timeStd) Now() time.Time { return time.Now() } // PodKiller will kill pods at regular intervals. type PodKiller struct { pt *chaosv1alpha1.PodTerminator k8sCli kubernetes.Interface logger log.Logger time TimeWrapper running bool mutex sync.Mutex stopC chan struct{} } // NewPodKiller returns a new pod killer. func NewPodKiller(pt *chaosv1alpha1.PodTerminator, k8sCli kubernetes.Interface, logger log.Logger) *PodKiller { return &PodKiller{ pt: pt, k8sCli: k8sCli, logger: logger, time: &timeStd{}, } } // NewCustomPodKiller is a constructor that lets you customize everything on the object construction. func NewCustomPodKiller(pt *chaosv1alpha1.PodTerminator, k8sCli kubernetes.Interface, time TimeWrapper, logger log.Logger) *PodKiller { return &PodKiller{ pt: pt, k8sCli: k8sCli, logger: logger, time: time, } } // SameSpec checks if the pod killer has the same spec. func (p *PodKiller) SameSpec(pt *chaosv1alpha1.PodTerminator) bool { return reflect.DeepEqual(p.pt.Spec, pt.Spec) } // Start will run the pod killer at regular intervals. func (p *PodKiller) Start() error { p.mutex.Lock() defer p.mutex.Unlock() if p.running { return fmt.Errorf("already running") } p.stopC = make(chan struct{}) p.running = true go func() { p.logger.Infof("started %s pod killer", p.pt.Name) if err := p.run(); err != nil { p.logger.Errorf("error executing pod killer: %s", err) } }() return nil } // Stop stops the pod killer. func (p *PodKiller) Stop() error { p.mutex.Lock() defer p.mutex.Unlock() if p.running { close(p.stopC) p.logger.Infof("stopped %s pod killer", p.pt.Name) } p.running = false return nil } // run will run the loop that will kill eventually the required pods. func (p *PodKiller) run() error { for { select { case <-p.time.After(time.Duration(p.pt.Spec.PeriodSeconds) * time.Second): if err := p.kill(); err != nil { p.logger.Errorf("error terminating pods: %s", err) } case <-p.stopC: return nil } } } // kill will terminate the required pods. func (p *PodKiller) kill() error { // Get all probable targets. pods, err := p.getProbableTargets() if err != nil { return err } // Select the number to delete and check is safe to terminate. total := len(pods.Items) if total == 0 { p.logger.Warningf("0 pods probable targets") } totalTargets := int(p.pt.Spec.TerminationPercent) * total / 100 // Check if we met the minimum after killing and adjust the targets to met the minimum instance requirement. if (total - totalTargets) < int(p.pt.Spec.MinimumInstances) { totalTargets = total - int(p.pt.Spec.MinimumInstances) if totalTargets < 0 { totalTargets = 0 } p.logger.Infof("%d minimum will not be met after killing, only killing %d targets", p.pt.Spec.MinimumInstances, totalTargets) } // Get random pods. targets := p.getRandomTargets(pods, totalTargets) p.logger.Infof("%s pod killer will kill %d targets", p.pt.Name, len(targets)) // Terminate. for _, target := range targets { if p.pt.Spec.DryRun { p.logger.Infof("pod %s not killed (dry run)", target.Name) } else { // if any error the abort deletion. if err := p.k8sCli.CoreV1().Pods(target.Namespace).Delete(context.Background(), target.Name, metav1.DeleteOptions{}); err != nil { return err } p.logger.Infof("pod %s killed", target.Name) } } return nil } // Gets all the pods filtered that can be a target of termination. func (p *PodKiller) getProbableTargets() (*corev1.PodList, error) { set := labels.Set(p.pt.Spec.Selector) slc := set.AsSelector() opts := metav1.ListOptions{ LabelSelector: slc.String(), } return p.k8sCli.CoreV1().Pods("").List(context.Background(), opts) } // getRandomTargets will get the targets randomly. func (p *PodKiller) getRandomTargets(pods *corev1.PodList, q int) []corev1.Pod { if len(pods.Items) == q { return pods.Items } // TODO: Optimize to pick randomly without duplicates and remove the way of sorting // a whole slice. // Sort targets randomly. randomPods := pods.DeepCopy().Items sort.Slice(randomPods, func(_, _ int) bool { // Create a random number and check if is even, if its true then a < b. r := rand.New(rand.NewSource(p.time.Now().UnixNano())) return r.Intn(1000)%2 == 0 }) // Get the desired quantity. return randomPods[:q] } <file_sep>package controller_test import ( "context" "fmt" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" kubetesting "k8s.io/client-go/testing" "k8s.io/client-go/tools/cache" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/controller/controllermock" "github.com/spotahome/kooper/v2/controller/leaderelection" "github.com/spotahome/kooper/v2/log" ) // NewNamespace returns a Namespace retriever. func newNamespaceRetriever(client kubernetes.Interface) controller.Retriever { return controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return client.CoreV1().Namespaces().List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return client.CoreV1().Namespaces().Watch(context.TODO(), options) }, }) } func onKubeClientListNamespaceReturn(client *fake.Clientset, nss *corev1.NamespaceList) { client.AddReactor("list", "namespaces", func(action kubetesting.Action) (bool, runtime.Object, error) { return true, nss, nil }) } func createNamespaceList(prefix string, q int) (*corev1.NamespaceList, []*corev1.Namespace) { nss := []*corev1.Namespace{} nsl := &corev1.NamespaceList{ ListMeta: metav1.ListMeta{ ResourceVersion: "1", }, Items: []corev1.Namespace{}, } for i := 0; i < q; i++ { nsName := fmt.Sprintf("%s-%d", prefix, i) ns := corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: nsName, ResourceVersion: fmt.Sprintf("%d", i), }, } nsl.Items = append(nsl.Items, ns) nss = append(nss, &ns) } return nsl, nss } func TestGenericControllerHandle(t *testing.T) { nsList, expNSAdds := createNamespaceList("testing", 10) tests := []struct { name string nsList *corev1.NamespaceList expNSAdds []*corev1.Namespace }{ { name: "Listing multiple namespaces should execute the handling for every namespace on list.", nsList: nsList, expNSAdds: expNSAdds, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert := assert.New(t) require := require.New(t) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() resultC := make(chan error) // Mocks kubernetes client. mc := &fake.Clientset{} onKubeClientListNamespaceReturn(mc, test.nsList) // Mock our handler and set expects. callHandling := 0 // used to track the number of calls. mh := &controllermock.Handler{} var mu sync.Mutex for _, ns := range test.expNSAdds { mh.On("Handle", mock.Anything, ns).Once().Return(nil).Run(func(args mock.Arguments) { mu.Lock() defer mu.Unlock() callHandling++ // Check last call, if is the last call expected then stop the controller so // we can assert the expectations of the calls and finish the test. if callHandling == len(test.expNSAdds) { cancelCtx() } }) } c, err := controller.New(&controller.Config{ Name: "test", Handler: mh, Retriever: newNamespaceRetriever(mc), Logger: log.Dummy, }) require.NoError(err) // Run Controller in background. go func() { resultC <- c.Run(ctx) }() // Wait for different results. If no result means error failure. select { case err := <-resultC: if assert.NoError(err) { // Check handles from the controller. mh.AssertExpectations(t) } case <-time.After(1 * time.Second): assert.Fail("timeout waiting for controller handling, this could mean the controller is not receiving resources") } }) } } func TestGenericControllerErrorRetries(t *testing.T) { nsList, _ := createNamespaceList("testing", 11) tests := []struct { name string nsList *corev1.NamespaceList retryNumber int }{ { name: "Retrying N resources with M retries and error on all should be 1 + M processing calls per resource (N+N*M event processing calls).", nsList: nsList, retryNumber: 3, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert := assert.New(t) require := require.New(t) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() resultC := make(chan error) // Mocks kubernetes client. mc := &fake.Clientset{} // Populate cache so we ensure deletes are correctly delivered. onKubeClientListNamespaceReturn(mc, nsList) // Mock our handler and set expects. totalCalls := len(test.nsList.Items) + len(test.nsList.Items)*test.retryNumber mh := &controllermock.Handler{} err := fmt.Errorf("wanted error") // Expect all the retries var mu sync.Mutex for range test.nsList.Items { callsPerNS := test.retryNumber + 1 // initial call + retries. mh.On("Handle", mock.Anything, mock.Anything).Return(err).Times(callsPerNS).Run(func(args mock.Arguments) { mu.Lock() defer mu.Unlock() totalCalls-- // Check last call, if is the last call expected then stop the controller so // we can assert the expectations of the calls and finish the test. if totalCalls <= 0 { cancelCtx() } }) } c, err := controller.New(&controller.Config{ Name: "test", Handler: mh, Retriever: newNamespaceRetriever(mc), ProcessingJobRetries: test.retryNumber, Logger: log.Dummy, }) require.NoError(err) // Run Controller in background. go func() { resultC <- c.Run(ctx) }() // Wait for different results. If no result means error failure. select { case err := <-resultC: if assert.NoError(err) { // Check handles from the controller. mh.AssertExpectations(t) } case <-time.After(1 * time.Second): assert.Fail("timeout waiting for controller handling, this could mean the controller is not receiving resources") } }) } } func TestGenericControllerWithLeaderElection(t *testing.T) { nsList, _ := createNamespaceList("testing", 5) tests := []struct { name string nsList *corev1.NamespaceList retryNumber int }{ { name: "", nsList: nsList, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert := assert.New(t) require := require.New(t) ctx, cancelCtx := context.WithCancel(context.Background()) defer cancelCtx() resultC := make(chan error) // Mocks kubernetes client. mc := fake.NewSimpleClientset(nsList) // Mock our handler and set expects. mh1 := &controllermock.Handler{} mh2 := &controllermock.Handler{} mh3 := &controllermock.Handler{} // Expect the calls on the lead (mh1) and no calls on the other ones. var mu sync.Mutex totalCalls := len(test.nsList.Items) mh1.On("Handle", mock.Anything, mock.Anything).Return(nil).Times(totalCalls).Run(func(args mock.Arguments) { mu.Lock() defer mu.Unlock() totalCalls-- // Check last call, if is the last call expected then stop the controller so // we can assert the expectations of the calls and finish the test. if totalCalls <= 0 { cancelCtx() } }) nsret := newNamespaceRetriever(mc) // Leader election service. rlCfg := &leaderelection.LockConfig{ LeaseDuration: 9999 * time.Second, RenewDeadline: 9998 * time.Second, RetryPeriod: 500 * time.Second, } lesvc1, _ := leaderelection.New("test", "default", rlCfg, mc, log.Dummy) lesvc2, _ := leaderelection.New("test", "default", rlCfg, mc, log.Dummy) lesvc3, _ := leaderelection.New("test", "default", rlCfg, mc, log.Dummy) c1, err := controller.New(&controller.Config{ Name: "test1", Handler: mh1, Retriever: nsret, LeaderElector: lesvc1, ProcessingJobRetries: test.retryNumber, Logger: log.Dummy, }) require.NoError(err) c2, err := controller.New(&controller.Config{ Name: "test2", Handler: mh2, Retriever: nsret, LeaderElector: lesvc2, ProcessingJobRetries: test.retryNumber, Logger: log.Dummy, }) require.NoError(err) c3, err := controller.New(&controller.Config{ Name: "test3", Handler: mh3, Retriever: nsret, LeaderElector: lesvc3, ProcessingJobRetries: test.retryNumber, Logger: log.Dummy, }) require.NoError(err) // Run multiple controller in background. go func() { resultC <- c1.Run(ctx) }() // Let the first controller became the leader. time.Sleep(200 * time.Microsecond) go func() { resultC <- c2.Run(ctx) }() go func() { resultC <- c3.Run(ctx) }() // Wait for different results. If no result means error failure. select { case err := <-resultC: if assert.NoError(err) { // Check handles from the controller. mh1.AssertExpectations(t) mh2.AssertExpectations(t) mh3.AssertExpectations(t) } case <-time.After(1 * time.Second): assert.Fail("timeout waiting for controller handling, this could mean the controller is not receiving resources") } }) } } <file_sep>package controller import ( "context" "errors" "fmt" "sync" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "github.com/spotahome/kooper/v2/controller/leaderelection" "github.com/spotahome/kooper/v2/log" ) var ( // ErrControllerNotValid will be used when the controller has invalid configuration. ErrControllerNotValid = errors.New("controller not valid") ) // Controller is the object that will implement the different kinds of controllers that will be running // on the application. type Controller interface { // Run runs the controller and blocks until the context is `Done`. Run(ctx context.Context) error } // Config is the controller configuration. type Config struct { // Handler is the controller handler. Handler Handler // Retriever is the controller retriever. Retriever Retriever // Leader elector will be used to use only one instance, if no set it will be // leader election will be ignored LeaderElector leaderelection.Runner // MetricsRecorder will record the controller metrics. MetricsRecorder MetricsRecorder // Logger will log messages of the controller. Logger log.Logger // name of the controller. Name string // ConcurrentWorkers is the number of concurrent workers the controller will have running processing events. ConcurrentWorkers int // ResyncInterval is the interval the controller will process all the selected resources. ResyncInterval time.Duration // ProcessingJobRetries is the number of times the job will try to reprocess the event before returning a real error. ProcessingJobRetries int // DisableResync will disable resyncing, if disabled the controller only will react on event updates and resync // all when it runs for the first time. // This is useful for secondary resource controllers (e.g pod controller of a primary controller based on deployments). DisableResync bool } func (c *Config) setDefaults() error { if c.Name == "" { return fmt.Errorf("a controller name is required") } if c.Handler == nil { return fmt.Errorf("a handler is required") } if c.Retriever == nil { return fmt.Errorf("a retriever is required") } if c.Logger == nil { c.Logger = log.NewStd(false) c.Logger.Warningf("no logger specified, fallback to default logger, to disable logging use a explicit Noop logger") } c.Logger = c.Logger.WithKV(log.KV{ "service": "kooper.controller", "controller-id": c.Name, }) if c.MetricsRecorder == nil { c.MetricsRecorder = DummyMetricsRecorder c.Logger.Warningf("no metrics recorder specified, disabling metrics") } if c.ConcurrentWorkers <= 0 { c.ConcurrentWorkers = 3 } if c.ResyncInterval <= 0 { c.ResyncInterval = 3 * time.Minute } if c.DisableResync { c.ResyncInterval = 0 // 0 == resync disabled. } if c.ProcessingJobRetries < 0 { c.ProcessingJobRetries = 0 } return nil } // generic controller is a controller that can be used to create different kind of controllers. type generic struct { queue blockingQueue // queue will have the jobs that the controller will get and send to handlers. informer cache.SharedIndexInformer // informer will notify be inform us about resource changes. processor processor // processor will call the user handler (logic). running bool runningMu sync.Mutex cfg Config metrics MetricsRecorder leRunner leaderelection.Runner logger log.Logger } func listerWatcherFromRetriever(ret Retriever) cache.ListerWatcher { // TODO(slok): pass context when Kubernetes updates its ListerWatchers ¯\_(ツ)_/¯. return &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return ret.List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return ret.Watch(context.TODO(), options) }, } } // New creates a new controller that can be configured using the cfg parameter. func New(cfg *Config) (Controller, error) { // Sets the required default configuration. err := cfg.setDefaults() if err != nil { return nil, fmt.Errorf("could no create controller: %w: %v", ErrControllerNotValid, err) } // Create the queue that will have our received job changes. queue := newRateLimitingBlockingQueue( cfg.ProcessingJobRetries, workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), ) // Measure the queue. queue, err = newMetricsBlockingQueue( cfg.Name, cfg.MetricsRecorder, queue, cfg.Logger, ) if err != nil { return nil, fmt.Errorf("could not measure the queue: %w", err) } // store is the internal cache where objects will be store. store := cache.Indexers{} lw := listerWatcherFromRetriever(cfg.Retriever) informer := cache.NewSharedIndexInformer(lw, nil, cfg.ResyncInterval, store) // Set up our informer event handler. // Objects are already in our local store. Add only keys/jobs on the queue so they can re processed // afterwards. _, err = informer.AddEventHandlerWithResyncPeriod(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { key, err := cache.MetaNamespaceKeyFunc(obj) if err != nil { cfg.Logger.Warningf("could not add item from 'add' event to queue: %s", err) return } queue.Add(context.TODO(), key) }, UpdateFunc: func(_ interface{}, new interface{}) { key, err := cache.MetaNamespaceKeyFunc(new) if err != nil { cfg.Logger.Warningf("could not add item from 'update' event to queue: %s", err) return } queue.Add(context.TODO(), key) }, DeleteFunc: func(obj interface{}) { key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) if err != nil { cfg.Logger.Warningf("could not add item from 'delete' event to queue: %s", err) return } queue.Add(context.TODO(), key) }, }, cfg.ResyncInterval) if err != nil { return nil, fmt.Errorf("could not set event handler on controller: %w", err) } // Create processing chain: processor(+middlewares) -> handler(+middlewares). processor := newIndexerProcessor(informer.GetIndexer(), cfg.Handler) if cfg.ProcessingJobRetries > 0 { processor = newRetryProcessor(cfg.Name, queue, cfg.Logger, processor) } processor = newMetricsProcessor(cfg.Name, cfg.MetricsRecorder, processor) // Create our generic controller object. return &generic{ queue: queue, informer: informer, metrics: cfg.MetricsRecorder, processor: processor, leRunner: cfg.LeaderElector, cfg: *cfg, logger: cfg.Logger, }, nil } func (g *generic) isRunning() bool { g.runningMu.Lock() defer g.runningMu.Unlock() return g.running } func (g *generic) setRunning(running bool) { g.runningMu.Lock() defer g.runningMu.Unlock() g.running = running } // Run will run the controller. func (g *generic) Run(ctx context.Context) error { // Check if leader election is required. if g.leRunner != nil { return g.leRunner.Run(func() error { return g.run(ctx) }) } return g.run(ctx) } // run is the real run of the controller. func (g *generic) run(ctx context.Context) error { if g.isRunning() { return fmt.Errorf("controller already running") } g.logger.Infof("starting controller") // Set state of controller. g.setRunning(true) defer g.setRunning(false) // Shutdown when Run is stopped so we can process the last items and the queue doesn't // accept more jobs. defer g.queue.ShutDown(ctx) // Run the informer so it starts listening to resource events. go g.informer.Run(ctx.Done()) // Wait until our store, jobs... stuff is synced (first list on resource, resources on store and jobs on queue). if !cache.WaitForCacheSync(ctx.Done(), g.informer.HasSynced) { return fmt.Errorf("timed out waiting for caches to sync") } // Start our resource processing worker, if finishes then restart the worker. The workers should // not end. for i := 0; i < g.cfg.ConcurrentWorkers; i++ { go func() { wait.Until(g.runWorker, time.Second, ctx.Done()) }() } // Block while running our workers in a continuous way (and re run if they fail). But // when stop signal is received we must stop. <-ctx.Done() g.logger.Infof("stopping controller") return nil } // runWorker will start a processing loop on event queue. func (g *generic) runWorker() { for { // Process next queue job, if needs to stop processing it will return true. if g.processNextJob() { break } } } // processNextJob job will process the next job of the queue job and returns if // it needs to stop processing. // // If the queue has been closed then it will end the processing. func (g *generic) processNextJob() bool { ctx := context.Background() // Get next job. nextJob, exit := g.queue.Get(ctx) if exit { return true } defer g.queue.Done(ctx, nextJob) key := nextJob.(string) // Process the job. err := g.processor.Process(ctx, key) logger := g.logger.WithKV(log.KV{"object-key": key}) switch { case err == nil: logger.Debugf("object processed") case errors.Is(err, errRequeued): logger.Warningf("error on object processing, retrying: %v", err) default: logger.Errorf("error on object processing: %v", err) } return false } <file_sep>## [unreleased] ## [2.5.0] - 2023-09-04 - Update Kubernetes libraries for 1.28. - Change resource locks from configmaps to leases. ## [2.4.0] - 2023-07-04 - Update Kubernetes libraries for 1.27. ## [2.3.0] - 2022-12-07 - Update Kubernetes libraries for 1.25. ## [2.2.0] - 2021-08-30 - Update Kubernetes libraries for 1.24. ## [2.1.0] - 2021-10-07 - Update Kubernetes libraries for 1.22. ## [2.0.0] - 2020-07-24 NOTE: Breaking release in controllers. - Refactor controller package. - Refactor metrics package. - Refactor log package. - Remove operator concept and remove CRD initialization in favor of using only controllers and let the CRD initialization outside Kooper (e.g CRD yaml). - Default resync time to 3 minutes. - Default workers to 3. - Disable retry handling on controllers in case of error by default. - Remove tracing. - Minimum Go version v1.13 (error wrapping required). - Refactor Logger with structured logging. - Add Logrus helper wrapper. - Refactor to simplify the retrievers. - Refactor metrics recorder implementation including the prometheus backend. - Refactor internal controller queue into a decorator implementation approach. - Remove `Delete` method from `controller.Handler` and simplify to only `Handle` method - Add `DisableResync` flag on controller configuration to disable the resync of all resources. - Update Kubernetes libraries for 1.22. ## [0.8.0] - 2019-12-11 - Support for Kubernetes 1.15. ## [0.7.0] - 2019-11-26 - Support for Kubernetes 1.14. ## [0.6.0] - 2019-06-01 ### Added - Support for Kubernetes 1.12. ### Removed - Glog logger. ## [0.5.1] - 2019-01-19 ### Added - Shortnames on CRD registration. ## [0.5.0] - 2018-10-24 ### Added - Support for Kubernetes 1.11. ## [0.4.1] - 2018-10-07 ### Added - Enable subresources support on CRD registration. - Category support on CRD registration. ## [0.4.0] - 2018-07-21 This release breaks Prometheus metrics. ### Added - Grafana dashboard for the refactored Prometheus metrics. ### Changed - Refactor metrics in favor of less metrics but simpler and more meaningful. ## [0.3.0] - 2018-07-02 This release breaks handler interface to allow passing a context (used to allow tracing). ### Added - Context as first argument to handler interface to pass tracing context (Breaking change). - Tracing through opentracing. - Leader election for controllers and operators. - Let customizing (using configuration) the retries of event processing errors on controllers. - Controllers now can be created using a configuration struct. - Add support for Kubernetes 1.10. ## [0.2.0] - 2018-02-24 This release breaks controllers constructors to allow passing a metrics recorder backend. ### Added - Prometheus metrics backend. - Metrics interface. - Concurrent controller implementation. - Controllers record metrics about queued and processed events. ### Fixed - Fix passing a nil logger to make controllers execution break. ## [0.1.0] - 2018-02-15 ### Added - CRD client check for kubernetes apiserver (>=1.7) - CRD ensure (waits to be present after registering a CRD) - CRD client tooling - multiple CRD and multiple controller operator. - single CRD and single controller operator. - sequential controller implementation. - Dependencies managed by dep and vendored. [unreleased]: https://github.com/spotahome/kooper/compare/v2.5.0...HEAD [2.4.0]: https://github.com/spotahome/kooper/compare/v2.4.0...v2.5.0 [2.4.0]: https://github.com/spotahome/kooper/compare/v2.3.0...v2.4.0 [2.3.0]: https://github.com/spotahome/kooper/compare/v2.2.0...v2.3.0 [2.2.0]: https://github.com/spotahome/kooper/compare/v2.1.0...v2.2.0 [2.1.0]: https://github.com/spotahome/kooper/compare/v2.0.0...v2.1.0 [2.0.0]: https://github.com/spotahome/kooper/compare/v0.8.0...v2.0.0 [0.8.0]: https://github.com/spotahome/kooper/compare/v0.7.0...v0.8.0 [0.7.0]: https://github.com/spotahome/kooper/compare/v0.6.0...v0.7.0 [0.6.0]: https://github.com/spotahome/kooper/compare/v0.5.1...v0.6.0 [0.5.1]: https://github.com/spotahome/kooper/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/spotahome/kooper/compare/v0.4.1...v0.5.0 [0.4.1]: https://github.com/spotahome/kooper/compare/v0.4.0...v0.4.1 [0.4.0]: https://github.com/spotahome/kooper/compare/v0.3.0...v0.4.0 [0.3.0]: https://github.com/spotahome/kooper/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/spotahome/kooper/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/spotahome/kooper/releases/tag/v0.1.0 <file_sep>package cli import ( "fmt" "os" "path/filepath" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" // Load oidc authentication when creating the kubernetes client. "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" ) // GetK8sClient returns k8s client. func GetK8sClient(kubehome string) (kubernetes.Interface, error) { // Try fallbacks. if kubehome == "" { if kubehome = os.Getenv("KUBECONFIG"); kubehome == "" { kubehome = filepath.Join(homedir.HomeDir(), ".kube", "config") } } // Load kubernetes local connection. config, err := clientcmd.BuildConfigFromFlags("", kubehome) if err != nil { return nil, fmt.Errorf("could not load configuration: %s", err) } // Get the client. k8sCli, err := kubernetes.NewForConfig(config) if err != nil { return nil, err } return k8sCli, nil } <file_sep>SERVICE_NAME := kooper SHELL := $(shell which bash) DOCKER := $(shell command -v docker) OSTYPE := $(shell uname) GID := $(shell id -g) UID := $(shell id -u) # cmds UNIT_TEST_CMD := ./hack/scripts/unit-test.sh INTEGRATION_TEST_CMD := ./hack/scripts/integration-test.sh CI_INTEGRATION_TEST_CMD := ./hack/scripts/integration-test-kind.sh GEN_CMD := ./hack/scripts/gen.sh DOCKER_RUN_CMD := docker run --env ostype=$(OSTYPE) -v ${PWD}:/src --rm -it ${SERVICE_NAME} DEPS_CMD := go mod tidy CHECK_CMD := ./hack/scripts/check.sh help: ## Show this help @echo "Help" @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-20s\033[93m %s\n", $$1, $$2}' .PHONY: default default: help .PHONY: build build: ## Build the development docker image. docker build -t $(SERVICE_NAME) --build-arg uid=$(UID) --build-arg gid=$(GID) -f ./docker/dev/Dockerfile . .PHONY: deps deps: ## Updates the required dependencies. $(DEPS_CMD) .PHONY: integration-test integration-test: build ## Runs integration tests out of CI. echo "[WARNING] Requires a kubernetes cluster configured (and running) on your kubeconfig!!" $(INTEGRATION_TEST_CMD) .PHONY: test test: build ## Runs unit tests out of CI. $(DOCKER_RUN_CMD) /bin/sh -c '$(UNIT_TEST_CMD)' .PHONY: check check: build ## Runs checks. @$(DOCKER_RUN_CMD) /bin/sh -c '$(CHECK_CMD)' .PHONY: ci-unit-test ci-unit-test: ## Runs unit tests in CI. $(UNIT_TEST_CMD) .PHONY: ci-integration-test ci-integration-test: ## Runs integration tests in CI. $(CI_INTEGRATION_TEST_CMD) .PHONY: ci ## Runs all tests in CI. ci: ci-unit-test ci-integration-test .PHONY: gen gen: build ## Generates go code. $(DOCKER_RUN_CMD) /bin/sh -c '$(GEN_CMD)' <file_sep>package test const ( GroupName = "chaos.spotahome.com" ) <file_sep>package leaderelection import ( "context" "fmt" "os" "time" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/leaderelection" "k8s.io/client-go/tools/leaderelection/resourcelock" "k8s.io/client-go/tools/record" "github.com/spotahome/kooper/v2/log" ) const ( defLeaseDuration = 15 * time.Second defRenewDeadline = 10 * time.Second defRetryPeriod = 2 * time.Second ) // LockConfig is the configuration for the lock (timing, leases...). type LockConfig struct { // LeaseDuration is the duration that non-leader candidates will // wait to force acquire leadership. This is measured against time of // last observed ack. LeaseDuration time.Duration // RenewDeadline is the duration that the acting master will retry // refreshing leadership before giving up. RenewDeadline time.Duration // RetryPeriod is the duration the LeaderElector clients should wait // between tries of actions. RetryPeriod time.Duration } // Runner knows how to run using the leader election. type Runner interface { // Run will run if the instance takes the lead. It's a blocking action. Run(func() error) error } // runner is the leader election default implementation. type runner struct { key string namespace string k8scli kubernetes.Interface lockCfg *LockConfig resourceLock resourcelock.Interface logger log.Logger } // NewDefault returns a new leader election service with a safe lock configuration. func NewDefault(key, namespace string, k8scli kubernetes.Interface, logger log.Logger) (Runner, error) { return New(key, namespace, nil, k8scli, logger) } // New returns a new leader election service. func New(key, namespace string, lockCfg *LockConfig, k8scli kubernetes.Interface, logger log.Logger) (Runner, error) { // If lock configuration is nil then fallback to defaults. if lockCfg == nil { lockCfg = &LockConfig{ LeaseDuration: defLeaseDuration, RenewDeadline: defRenewDeadline, RetryPeriod: defRetryPeriod, } } r := &runner{ lockCfg: lockCfg, key: key, namespace: namespace, k8scli: k8scli, logger: logger.WithKV(log.KV{ "source-service": "kooper/leader-election", "leader-election-id": fmt.Sprintf("%s/%s", namespace, key), }), } if err := r.validate(); err != nil { return nil, err } if err := r.initResourceLock(); err != nil { return nil, err } return r, nil } func (r *runner) validate() error { // Error if no namespace set. if r.namespace == "" { return fmt.Errorf("running in leader election mode requires the namespace running") } // Key required if r.key == "" { return fmt.Errorf("running in leader election mode requires a key for identification the different instances") } return nil } func (r *runner) initResourceLock() error { // Create the lock resource for the leader election. hostname, err := os.Hostname() if err != nil { return err } id := hostname + "_" + string(uuid.NewUUID()) eventBroadcaster := record.NewBroadcaster() recorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: r.key, Host: id}) rl, err := resourcelock.New( resourcelock.LeasesResourceLock, r.namespace, r.key, r.k8scli.CoreV1(), r.k8scli.CoordinationV1(), resourcelock.ResourceLockConfig{ Identity: id, EventRecorder: recorder, }, ) if err != nil { return fmt.Errorf("error creating lock: %v", err) } r.resourceLock = rl return nil } func (r *runner) Run(f func() error) error { errC := make(chan error, 1) // Channel to get the function returning error. // The function to execute when leader acquired. lef := func(ctx context.Context) { r.logger.Infof("lead acquire, starting...") // Wait until f finishes or leader elector runner stops. select { case <-ctx.Done(): errC <- nil case errC <- f(): } r.logger.Infof("lead execution stopped") } // Create the leader election configuration lec := leaderelection.LeaderElectionConfig{ Lock: r.resourceLock, LeaseDuration: r.lockCfg.LeaseDuration, RenewDeadline: r.lockCfg.RenewDeadline, RetryPeriod: r.lockCfg.RetryPeriod, Callbacks: leaderelection.LeaderCallbacks{ OnStartedLeading: lef, OnStoppedLeading: func() { errC <- fmt.Errorf("leadership lost") }, }, } // Create the leader elector. le, err := leaderelection.NewLeaderElector(lec) if err != nil { return fmt.Errorf("error creating leader election: %s", err) } // Execute! r.logger.Infof("running in leader election mode, waiting to acquire leadership...") go le.Run(context.TODO()) // Wait until stopping the execution returns the result. err = <-errC return err } <file_sep>package controller_test import ( "context" "fmt" "testing" "github.com/spotahome/kooper/v2/controller" "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" ) var ( testPodList = &corev1.PodList{ Items: []corev1.Pod{ {ObjectMeta: metav1.ObjectMeta{Name: "test1"}}, {ObjectMeta: metav1.ObjectMeta{Name: "test2"}}, {ObjectMeta: metav1.ObjectMeta{Name: "test3"}}, {ObjectMeta: metav1.ObjectMeta{Name: "test4"}}, {ObjectMeta: metav1.ObjectMeta{Name: "test5"}}, {ObjectMeta: metav1.ObjectMeta{Name: "test6"}}, {ObjectMeta: metav1.ObjectMeta{Name: "test7"}}, }, } testEventList = []watch.Event{ {Type: watch.Added, Object: &testPodList.Items[0]}, {Type: watch.Added, Object: &testPodList.Items[1]}, {Type: watch.Added, Object: &testPodList.Items[2]}, {Type: watch.Added, Object: &testPodList.Items[3]}, {Type: watch.Added, Object: &testPodList.Items[4]}, {Type: watch.Added, Object: &testPodList.Items[5]}, {Type: watch.Added, Object: &testPodList.Items[6]}, } ) func testPodListFunc(pl *corev1.PodList) cache.ListFunc { return func(options metav1.ListOptions) (runtime.Object, error) { return pl, nil } } func testEventWatchFunc(evs []watch.Event) cache.WatchFunc { return func(options metav1.ListOptions) (watch.Interface, error) { cg := make(chan watch.Event) go func() { for _, ev := range evs { cg <- ev } close(cg) }() return watch.NewProxyWatcher(cg), nil } } func TestRetrieverFromListerWatcher(t *testing.T) { tests := map[string]struct { listerWatcher cache.ListerWatcher expList runtime.Object expListErr bool expWatch []watch.Event expWatchErr bool }{ "A List error or a watch error should be propagated to the upper layer": { listerWatcher: &cache.ListWatch{ ListFunc: func(_ metav1.ListOptions) (runtime.Object, error) { return nil, fmt.Errorf("wanted error") }, WatchFunc: func(_ metav1.ListOptions) (watch.Interface, error) { return nil, fmt.Errorf("wanted error") }, }, expListErr: true, expWatchErr: true, }, "List and watch should call the Kubernetes go clients lister watcher correctly.": { listerWatcher: &cache.ListWatch{ ListFunc: testPodListFunc(testPodList), WatchFunc: testEventWatchFunc(testEventList), }, expList: testPodList, expWatch: testEventList, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { assert := assert.New(t) ret := controller.MustRetrieverFromListerWatcher(test.listerWatcher) // Test list. objs, err := ret.List(context.TODO(), metav1.ListOptions{}) if test.expListErr { assert.Error(err) } else if assert.NoError(err) { assert.Equal(test.expList, objs) } // Test watch. w, err := ret.Watch(context.TODO(), metav1.ListOptions{}) evs := []watch.Event{} if test.expWatchErr { assert.Error(err) } else if assert.NoError(err) { for ev := range w.ResultChan() { evs = append(evs, ev) } assert.Equal(test.expWatch, evs) } }) } } <file_sep># Leader election Kooper comes with support for leader election. A controller can be run with multiple instances in HA and only one will be really running the controller logic (the leader), when the leader stops or loses the leadership another instance will take the leadership and so on. ## Usage The default controllers don't run in leader election mode: - `controller.NewSequential` - `controller.NewConcurrent` To use the leader election you can use: - `controller.New` These method accepts a [`leaderelection.Runner`][leaderelection-src] service that manages the leader election of the controller, if this service is a `nil` object the controller will fallback to a regular controller mode. The leader election comes with two contructors, one that has safe settings for the lock and one that can be configured. Lets take and example of creating using the default leader election service. ```golang import ( ... "github.com/spotahome/kooper/v2/operator/controller/leaderelection" ... ) ... lesvc, err := leaderelection.NewDefault("my-controller", "myControllerNS", k8scli, logger) ctrl := controller.New(cfg, hand, retr, lesvc, nil, logger) ... ``` Another example customizing the lock would be: ```golang import ( ... "github.com/spotahome/kooper/v2/operator/controller/leaderelection" ... ) ... rlCfg := &leaderelection.LockConfig{ LeaseDuration: 20 * time.Second RenewDeadline: 12 * time.Second RetryPeriod: 3 * time.Second } lesvc, err := leaderelection.New("my-controller", "myControllerNS", rlCfg,k8scli, logger) ... ``` ## Important notes ### Lock When using the leader election in a controller, the controller needs the namespace where the controller is running, this is because the lock is made using a configmap (that will be on the namespace where the controller is running). Also because of this, it needs to get, create and update a configmap. This means that if you are using RBAC, the definition would need at least these permissions: ```yaml rules: - apiGroups: - "" resources: - configmaps verbs: - create - get - update ``` ### Losing the leadership When one of the leaders looses the leadership the controller will end its execution (Kubernetes eventually should spin up a new instance) ## Full example For a full example check [this][leaderelection-example] ## Test example in local You can check how it works locally using docker running N controllers in different containers. For example `ctrl1` and `ctrl2`: ```bash docker run --name ctrl1 \ --network bridge \ --rm -it \ -v ${HOME}/.kube:/root/.kube:ro \ -v `pwd`:/go/src/github.com/spotahome/kooper:ro \ golang go run /go/src/github.com/spotahome/kooper/examples/leader-election-controller/main.go ``` ```bash docker run --name ctrl2 \ --network bridge \ --rm -it \ -v ${HOME}/.kube:/root/.kube:ro \ -v `pwd`:/go/src/github.com/spotahome/kooper:ro \ golang go run /go/src/github.com/spotahome/kooper/examples/leader-election-controller/main.go ``` Now you can test disconnecting and connecting them using these commands and checking the results. - `docker network disconnect bridge ctrl2` - `docker network disconnect bridge ctrl1` - `docker network connect bridge ctrl2` - `docker network connect bridge ctrl1` [leaderelection-src]: https://github.com/spotahome/kooper/tree/master/operator/controller/leaderelection [leaderelection-example]: https://github.com/spotahome/kooper/tree/master/examples/leader-election-controller <file_sep>// Package controller contains implementation and defition to create kubernetes controllers. package controller // import "github.com/spotahome/kooper/v2/operator/controller" <file_sep>// +build integration package controller_test import ( "context" "fmt" "sync" "testing" "time" "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/log" ) const ( noResync = 0 controllerRunTimeout = 10 * time.Second // this delta is the max duration delta used on the assertion of controller handling, this is required because // the controller requires some millisecond to bootstrap and sync. maxAssertDurationDelta = 500 * time.Millisecond ) func returnPodList(q int) *corev1.PodList { items := make([]corev1.Pod, q) for i := 0; i < q; i++ { items[i] = corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("pod%d", i), }, } } return &corev1.PodList{ Items: items, } } // runTimedController will run a controller that will handle multiple events and will return the duration // how long it took to process all the events. each handled event will take the desired ammount of time. func runTimedController(sleepDuration time.Duration, concurrencyLevel int, numberOfEvents int, t *testing.T) time.Duration { assert := assert.New(t) // Create the faked retriever that will only return N pods. podList := returnPodList(numberOfEvents) r := controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(_ metav1.ListOptions) (runtime.Object, error) { return podList, nil }, WatchFunc: func(_ metav1.ListOptions) (watch.Interface, error) { return watch.NewFake(), nil }, }) // Create the handler that will wait on each event T duration and will // end when all the wanted quantity of events have been processed. var wg sync.WaitGroup wg.Add(numberOfEvents) h := controller.HandlerFunc(func(_ context.Context, _ runtime.Object) error { time.Sleep(sleepDuration) wg.Done() return nil }) // Create the controller type depending on the concurrency level. cfg := &controller.Config{ Name: "test-controller", Handler: h, Retriever: r, Logger: log.Dummy, ProcessingJobRetries: concurrencyLevel, ResyncInterval: noResync, ConcurrentWorkers: concurrencyLevel, } ctrl, err := controller.New(cfg) if !assert.NoError(err) { return 0 } // Run handling ctx, cancel := context.WithCancel(context.Background()) defer cancel() start := time.Now() go func() { assert.NoError(ctrl.Run(ctx)) }() // Wait until the finish event is received (wait until all events processed), it has a big timeout (it's an integration test). finishC := make(chan struct{}) go func() { wg.Wait() close(finishC) }() select { case <-time.After(controllerRunTimeout): assert.Fail("timeout waiting for controller finish processing events") case <-finishC: } // Return result duration of all the handling. return time.Now().Sub(start) } func TestGenericControllerSequentialVSConcurrent(t *testing.T) { tests := []struct { name string numberOfEvents int concurrencyLevel int sleepDuration time.Duration expSequentialDuration time.Duration expConcurrentDuration time.Duration }{ { name: "100 events with 10ms handling latency should take 1s sequentially and 200ms with 5 workers", numberOfEvents: 100, concurrencyLevel: 5, sleepDuration: 10 * time.Millisecond, expSequentialDuration: 1 * time.Second, expConcurrentDuration: 200 * time.Millisecond, }, { name: "100 events with 20ms handling latency should take 2s sequentially and 400ms with 5 workers", numberOfEvents: 100, concurrencyLevel: 5, sleepDuration: 20 * time.Millisecond, expSequentialDuration: 2 * time.Second, expConcurrentDuration: 400 * time.Millisecond, }, { name: "100 events with 30ms handling latency should take 3s sequentially and 600ms with 5 workers", numberOfEvents: 100, concurrencyLevel: 5, sleepDuration: 30 * time.Millisecond, expSequentialDuration: 3 * time.Second, expConcurrentDuration: 600 * time.Millisecond, }, { name: "100 events with 40ms handling latency should take 4s sequentially and 800ms with 5 workers", numberOfEvents: 100, concurrencyLevel: 5, sleepDuration: 40 * time.Millisecond, expSequentialDuration: 4 * time.Second, expConcurrentDuration: 800 * time.Millisecond, }, { name: "100 events with 50ms handling latency should take 5s sequentially and 1s with 5 workers", numberOfEvents: 100, concurrencyLevel: 5, sleepDuration: 50 * time.Millisecond, expSequentialDuration: 5 * time.Second, expConcurrentDuration: 1 * time.Second, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert := assert.New(t) gotSecDuration := runTimedController(test.sleepDuration, 1, test.numberOfEvents, t) gotConcDuration := runTimedController(test.sleepDuration, test.concurrencyLevel, test.numberOfEvents, t) // Check if the expected time is correct. check expected and got duration are within a max delta (usually controller bootstrapping/sync). assert.InDelta(test.expSequentialDuration, gotSecDuration, float64(maxAssertDurationDelta)) assert.InDelta(test.expConcurrentDuration, gotConcDuration, float64(maxAssertDurationDelta)) }) } } <file_sep>package log import ( "fmt" "log" ) // KV is a helper type for structured logging fields usage. type KV map[string]interface{} // Logger is the interface that the loggers used by the library will use. type Logger interface { Infof(format string, args ...interface{}) Warningf(format string, args ...interface{}) Errorf(format string, args ...interface{}) Debugf(format string, args ...interface{}) WithKV(KV) Logger } // Dummy logger doesn't log anything. const Dummy = dummy(0) type dummy int func (d dummy) Infof(format string, args ...interface{}) {} func (d dummy) Warningf(format string, args ...interface{}) {} func (d dummy) Errorf(format string, args ...interface{}) {} func (d dummy) Debugf(format string, args ...interface{}) {} func (d dummy) WithKV(KV) Logger { return d } // Std is a wrapper for go standard library logger. type std struct { debug bool fields map[string]interface{} } // NewStd returns a Logger implementation with the standard logger. func NewStd(debug bool) Logger { return std{ debug: debug, fields: map[string]interface{}{}, } } func (s std) logWithPrefix(prefix, format string, kv map[string]interface{}, args ...interface{}) { msgFmt := "" if len(kv) == 0 { msgFmt = fmt.Sprintf("%s\t%s", prefix, format) } else { msgFmt = fmt.Sprintf("%s\t%s\t\t%v", prefix, format, kv) } log.Printf(msgFmt, args...) } func (s std) Infof(format string, args ...interface{}) { s.logWithPrefix("[INFO]", format, s.fields, args...) } func (s std) Warningf(format string, args ...interface{}) { s.logWithPrefix("[WARN]", format, s.fields, args...) } func (s std) Errorf(format string, args ...interface{}) { s.logWithPrefix("[ERROR]", format, s.fields, args...) } func (s std) Debugf(format string, args ...interface{}) { if s.debug { s.logWithPrefix("[DEBUG]", format, s.fields, args...) } } func (s std) WithKV(kv KV) Logger { kvs := map[string]interface{}{} for k, v := range s.fields { kvs[k] = v } for k, v := range kv { kvs[k] = v } return std{debug: s.debug, fields: kvs} } <file_sep>Operator tutorial =================== In this tutorial we will learn how to create an operator using Kooper. If you didn't read the [previous tutorial](controller-tutorial.md) about controllers you should read that first. Lets start by remembering what is an operator... Depending who or where you ask you will get different answers, very similar but not the same, but everyone concludes that an operator is just a controller that bases its flow on CRDs or custom resources created by us instead of Kubernetes core resources like pods, services, deployments... In this tutorial we will make an operator that will terminate pods, something like [chaos monkey](https://github.com/Netflix/chaosmonkey) but for pods and very very simple. ## 01 - Description. Our Operator will apply [chaos engineering](http://principlesofchaos.org/) at a very low level. It will delete pods based on the time (interval), quantity, and filtered by labels. It will lack a lot of things and the main purpose of this tutorial is not the domain logic of the operator (the pod terminator, that is cool also and you should read it :)) but how you bootstrap a full working operator with its CRDs using Kooper. The full controller is in [examples/pod-terminator-operator](https://github.com/spotahome/kooper/tree/master/examples/pod-terminator-operator). ## 02 - Operator structure Our example structure is simple ``` ./examples/pod-terminator-operator/ ├── apis │   └── chaos │   ├── register.go │   └── v1alpha1 │   ├── doc.go │   ├── register.go │   ├── types.go │   └── zz_generated.deepcopy.go [AUTOGENERATED CODE] ├── client │   └── k8s │   └── clientset [AUTOGENERATED CODE] ├── cmd │   ├── flags.go │   └── main.go ├── log │   └── log.go ├── Makefile ├── manifest-examples │   ├── nginx-controller.yaml │   └── pause.yaml ├── operator │   ├── config.go │   ├── crd.go │   ├── factory.go │   └── handler.go └── service └── chaos ├── chaos.go ├── podkill.go └── podkill_test.go ``` * apis: There will reside our custom Kubernetes API objects (crds). * client/k8s/clientset: This is a k8s client for our CRDs so it is easy to use them with kubernetes. This code is autogenerated by [code-generator](https://github.com/kubernetes/code-generator). * cmd: The main app that will run our operator. * log: Our logger. * Makefile: Commands to automate stuff for the example (in this case autogenerate our CRD code). * manifest-examples: Some yaml examples of our CRD. * operator: All the kooper library usage to create the operator. * service: our services where also will be our operator domain logic (chaos). ### Unit testing Testing is important. As you see this project has few unit tests. This is because of two things: One, the project is very simple. Two, you can trust Kubernetes and Kooper libraries, they are already tested, you don't need to test these, but you should test your domain logic (and if you want, main and glue code also). In this operator we just tested the service that has our domain logic (the logic that kills the pods). ## 03 - Designing our CRD The first thing that we need to do is to design our CRD. In the case of this example the definition of the resource needs to be something that need to select pods based on labels and periodically kill them, also needs to respect a safe quantity of minimum pods running and lastly a dry run option to check if it's selecting the correct pods to kill. Something like this: ```yaml apiVersion: chaos.spotahome.com/v1alpha1 kind: PodTerminator metadata: name: nginx-controller labels: example: pod-terminator-operator operator: pod-terminator-operator spec: selector: k8s-app: nginx-ingress-controller periodSeconds: 120 TerminationPercent: 25 MinimumInstances: 2 DryRun: true ``` We called `PodTerminator` and its group will be `chaos.spotahome.com/v1alpha1` we selected `v1alpha1` as the version of the group because is the first iteration of our resources, eventually it will end up being `v1` when its stable, but in this example it will be there forever. You can imagine doing this when the example is up and running: ``` $ kubectl get podterminators NAME AGE nginx-controller 1h ``` ### Implementin the CRD We have designed the CRD, but now we need to implement. All of the operator resources are in [apis](https://github.com/spotahome/kooper/tree/master/examples/pod-terminator-operator/apis) directory inside the example, the structure of the CRD follows Kubernetes conventions (group/version). How this structure is placed and how it's implemented its out of the scope of this tutorial, you can check [kubernetes api](https://github.com/kubernetes/api) repository and [this blog post](https://blog.openshift.com/kubernetes-deep-dive-code-generation-customresources/) To summarize a little bit, we have this API structure: ``` ./examples/pod-terminator-operator/apis/ └── chaos ├── register.go └── v1alpha1 ├── doc.go ├── register.go ├── types.go └── zz_generated.deepcopy.go ``` in `types` is our [PodTerminator Go object](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/apis/chaos/v1alpha1/types.go) that describes de API and in `register.go` files there is data to register this types in kubernetes client. With these files kubernetes code-generator will generate the required code for the [clients](https://github.com/spotahome/kooper/tree/master/examples/pod-terminator-operator/client/k8s/clientset) and deepcopy methods ([deepcopy](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/apis/chaos/v1alpha1/zz_generated.deepcopy.go) methods are required by all the kubernetes objects). You can see how its used in the [Makefile](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/Makefile). This will generate all the boilerplate code that is the same in all the kubernetes objects (crds and not crds). At this point we have our PodTerminator CRD go code ready to work with (create, get, delete, list, watch... using kubernetes client). ## 04 - Chaos service Let's start with our domain logic. Our domain logic is a single service called `Chaos`. This service will be responsible for running a number of `podKillers`, and these podkillers will kill pods at regular intervals based on the filters and description described on our manifests (`PodTerminator` CRD). We will not explain the logic of this service as is out of the scope of this operator tutorial. But you can take a look [here]((https://github.com/spotahome/kooper/tree/master/examples/pod-terminator-operator/service/chaos) if you think is interesting. Our service has these methods and are the ones that will be used by our operator. ```golang type ChaosSyncer interface { EnsurePodTerminator(pt *chaosv1alpha1.PodTerminator) error DeletePodTerminator(name string) error } ``` For us, create and update are the same. This means that we need to think as "ensure" or "sync" verbs instead of create/update. ## 05 - Operator ### Config This operator only has the resync period (the interval kubernetes will return us all the resources we are listening to) This can be found in [operator/config.go](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/operator/config.go) ``` type Config struct { // ResyncPeriod is the resync period of the operator. ResyncPeriod time.Duration } ``` ### CRD The first thing that the operator needs is the CRD, the operator will ensure CRD (`PodTerminator`) is registered on kubernetes and also will be reacting to this resource changes (add/update and delete). This can be found in [operator/crd.go](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/operator/crd.go). For the initialization kooper [CRD client](https://github.com/spotahome/kooper/blob/master/client/crd/crd.go) is used. All the stuff required by the `crd.Conf` was added on the implementation and design of the CRD in previous steps. ``` func (p *podTerminatorCRD) Initialize() error { crd := crd.Conf{ Kind: chaosv1alpha1.PodTerminatorKind, NamePlural: chaosv1alpha1.PodTerminatorNamePlural, ShortNames: chaosv1alpha1.PodTerminatorShortNames, Group: chaosv1alpha1.SchemeGroupVersion.Group, Version: chaosv1alpha1.SchemeGroupVersion.Version, Scope: chaosv1alpha1.PodTerminatorScope, } return p.crdCli.EnsurePresent(crd) } ``` You will notice that the lister watcher and the object is like a retriever. This is because a CRD is a retriever but it knows how to initialize, nothing more. As you see on the lister watcher we are using the client that code-generator generated for us in previous steps. ```golang func (p *podTerminatorCRD) GetListerWatcher() cache.ListerWatcher { return &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return p.podTermCli.ChaosV1alpha1().PodTerminators().List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return p.podTermCli.ChaosV1alpha1().PodTerminators().Watch(options) }, } } func (p *podTerminatorCRD) GetObject() runtime.Object { return &chaosv1alpha1.PodTerminator{} } ``` ### Handler The handler is how the operator will react to Kubernetes resource changes/notifications. In this case is very simple because all the domain logic is inside our services (decouple your domain logic and responsibilities :)). This can be found in [operator/handler.go](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/operator/handler.go). ```golang func (h *handler) Add(_ context.Context, obj runtime.Object) error { pt, ok := obj.(*chaosv1alpha1.PodTerminator) if !ok { return fmt.Errorf("%v is not a pod terminator object", obj.GetObjectKind()) } return h.chaosService.EnsurePodTerminator(pt) } func (h *handler) Delete(_ context.Context, name string) error { return h.chaosService.DeletePodTerminator(name) } ``` ### Factory All the pieces are ready, let's glue all together. This can be found in [operator/factory.go](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/operator/factory.go). ```golang func New(cfg Config, podTermCli podtermk8scli.Interface, crdCli crd.Interface, kubeCli kubernetes.Interface, logger log.Logger) (operator.Operator, error) { // Create crd. ptCRD := newPodTermiantorCRD(podTermCli, crdCli, kubeCli) // Create handler. handler := newHandler(kubeCli, logger) // Create controller. ctrl := controller.NewSequential(cfg.ResyncPeriod, handler, ptCRD, nil, logger) // Assemble CRD and controller to create the operator. return operator.NewOperator(ptCRD, ctrl, logger), nil } ``` First the CRD instance is created, next the handler, then with the handler and the CRD the controller (remember that an operator is just a controller + CRD) and finally the operator is created using the controller and the CRD. ## 06 - Finishing After all these steps, a fully operational chaos operator is ready to destroy pods. You can check the [main](https://github.com/spotahome/kooper/blob/master/examples/pod-terminator-operator/cmd/main.go) where the operator is instantiated. Run everything with: ```bash $ go run ./examples/pod-terminator-operator/cmd/* --help ``` And you can test the CRD with the examples or creating yours! ```bash $ kubectl apply -f ./examples/pod-terminator-operator/manifest-examples/nginx-controller.yaml ``` <file_sep>package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // PodTerminator represents a pod terminator. // // +genclient // +genclient:nonNamespaced // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:resource:singular=podterminator,path=podterminators,shortName=pt,scope=Cluster,categories=terminators;killers;gc type PodTerminator struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata // +optional metav1.ObjectMeta `json:"metadata,omitempty"` // Specification of the ddesired behaviour of the pod terminator. // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status // +optional Spec PodTerminatorSpec `json:"spec,omitempty"` } // PodTerminatorSpec is the spec for a PodTerminator resource. type PodTerminatorSpec struct { // Selector is how the target will be selected. Selector map[string]string `json:"selector,omitempty"` // PeriodSeconds is how often (in seconds) to perform the attack. PeriodSeconds int32 `json:"periodSeconds,omitempty"` // TerminationPercent is the percent of pods that will be killed randomly. TerminationPercent int32 `json:"terminationPercent,omitempty"` // MinimumInstances is the number of minimum instances that need to be alive. // +optional MinimumInstances int32 `json:"minimumInstances,omitempty"` // DryRun will set the killing in dryrun mode or not. // +optional DryRun bool `json:"dryRun,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // PodTerminatorList is a list of PodTerminator resources type PodTerminatorList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []PodTerminator `json:"items"` } <file_sep>package prepare import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) // Preparer knows ho to prepare a test case in a kubernetes cluster. type Preparer struct { t *testing.T cli kubernetes.Interface namespace *corev1.Namespace } // New returns a new preparer. func New(cli kubernetes.Interface, t *testing.T) *Preparer { ns := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("kooper-integration-test-%d", time.Now().UTC().UnixNano()), }, } return &Preparer{ t: t, cli: cli, namespace: ns, } } // SetUp will set up all the required preparation for the tests in a Kubernetes cluster. func (p *Preparer) SetUp() { ns, err := p.cli.CoreV1().Namespaces().Create(context.Background(), p.namespace, metav1.CreateOptions{}) require.NoError(p.t, err, "set up failed, can't continue without setting up an environment") p.namespace = ns } // Namespace returns the namespace where the environment is set. func (p *Preparer) Namespace() *corev1.Namespace { return p.namespace } // TearDown will tear down all the required preparation for the tests in a Kubernetes cluster. func (p *Preparer) TearDown() { err := p.cli.CoreV1().Namespaces().Delete(context.Background(), p.namespace.Name, metav1.DeleteOptions{}) require.NoError(p.t, err, "tear down failed, can't continue without destroying an environment") } <file_sep>package main import ( "context" "fmt" "os" "path/filepath" "time" "github.com/sirupsen/logrus" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/log" kooperlogrus "github.com/spotahome/kooper/v2/log/logrus" ) func run() error { // Initialize logger. logger := kooperlogrus.New(logrus.NewEntry(logrus.New())). WithKV(log.KV{"example": "multi-resource-controller"}) // Get k8s client. k8scfg, err := rest.InClusterConfig() if err != nil { // No in cluster? letr's try locally kubehome := filepath.Join(homedir.HomeDir(), ".kube", "config") k8scfg, err = clientcmd.BuildConfigFromFlags("", kubehome) if err != nil { return fmt.Errorf("error loading kubernetes configuration: %w", err) } } k8scli, err := kubernetes.NewForConfig(k8scfg) if err != nil { return fmt.Errorf("error creating kubernetes client: %w", err) } // Our domain logic that will print every add/sync/update and delete event we . hand := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { dep, ok := obj.(*appsv1.Deployment) if ok { logger.Infof("Deployment added: %s/%s", dep.Namespace, dep.Name) return nil } st, ok := obj.(*appsv1.StatefulSet) if ok { logger.Infof("Statefulset added: %s/%s", st.Namespace, st.Name) return nil } return nil }) const ( retries = 5 resyncInterval = 45 * time.Second workers = 1 ) // Create the controller for deployments. ctrlDep, err := controller.New(&controller.Config{ Name: "multi-resource-controller-deployments", Handler: hand, Retriever: controller.MustRetrieverFromListerWatcher( &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return k8scli.AppsV1().Deployments("").List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return k8scli.AppsV1().Deployments("").Watch(context.Background(), options) }, }, ), Logger: logger, ProcessingJobRetries: retries, ResyncInterval: resyncInterval, ConcurrentWorkers: workers, }) if err != nil { return fmt.Errorf("could not create deployment resource controller: %w", err) } // Create the controller for statefulsets. ctrlSt, err := controller.New(&controller.Config{ Name: "multi-resource-controller-statefulsets", Handler: hand, Retriever: controller.MustRetrieverFromListerWatcher( &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return k8scli.AppsV1().StatefulSets("").List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return k8scli.AppsV1().StatefulSets("").Watch(context.Background(), options) }, }, ), Logger: logger, ProcessingJobRetries: retries, ResyncInterval: resyncInterval, ConcurrentWorkers: workers, }) // Start our controllers. ctx, cancel := context.WithCancel(context.Background()) defer cancel() errC := make(chan error) go func() { errC <- ctrlDep.Run(ctx) }() go func() { errC <- ctrlSt.Run(ctx) }() // Wait until one finishes. err = <-errC if err != nil { return fmt.Errorf("error running controllers: %w", err) } return nil } func main() { err := run() if err != nil { fmt.Fprintf(os.Stderr, "error running app: %s", err) os.Exit(1) } os.Exit(0) } <file_sep>package operator import ( "context" "fmt" "time" "github.com/spotahome/kooper/v2/controller" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" chaosv1alpha1 "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/apis/chaos/v1alpha1" podtermk8scli "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/client/k8s/clientset/versioned" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/log" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/service/chaos" ) // Config is the controller configuration. type Config struct { // ResyncPeriod is the resync period of the operator. ResyncPeriod time.Duration } // New returns pod terminator operator. func New(cfg Config, podTermCli podtermk8scli.Interface, kubeCli kubernetes.Interface, logger log.Logger) (controller.Controller, error) { return controller.New(&controller.Config{ Name: "pod-terminator", Handler: newHandler(kubeCli, podTermCli, logger), Retriever: newRetriever(podTermCli), Logger: logger, ResyncInterval: cfg.ResyncPeriod, }) } func newRetriever(cli podtermk8scli.Interface) controller.Retriever { return controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return cli.ChaosV1alpha1().PodTerminators().List(context.Background(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return cli.ChaosV1alpha1().PodTerminators().Watch(context.Background(), options) }, }) } func newHandler(k8sCli kubernetes.Interface, ptCli podtermk8scli.Interface, logger log.Logger) controller.Handler { const finalizer = "finalizer.chaos.spotahome.com/podKiller" chaossvc := chaos.NewChaos(k8sCli, logger) return controller.HandlerFunc(func(ctx context.Context, obj runtime.Object) error { pt, ok := obj.(*chaosv1alpha1.PodTerminator) if !ok { return fmt.Errorf("%v is not a pod terminator object", obj.GetObjectKind()) } switch { // Handle deletion and remove finalizer. case !pt.DeletionTimestamp.IsZero() && stringPresentInSlice(pt.Finalizers, finalizer): logger.Infof("handling pod termination deletion...") err := chaossvc.DeletePodTerminator(pt.ObjectMeta.Name) if err != nil { return fmt.Errorf("could not handle PodTerminator deletion: %w", err) } pt.Finalizers = removeStringFromSlice(pt.Finalizers, finalizer) _, err = ptCli.ChaosV1alpha1().PodTerminators().Update(ctx, pt, metav1.UpdateOptions{}) if err != nil { return fmt.Errorf("could not update pod terminator: %w", err) } return nil // Deletion already handled, don't do anything. case !pt.DeletionTimestamp.IsZero() && !stringPresentInSlice(pt.Finalizers, finalizer): logger.Infof("handling pod termination deletion already handled, skipping...") return nil // Add finalizer to the object. case pt.DeletionTimestamp.IsZero() && !stringPresentInSlice(pt.Finalizers, finalizer): pt.Finalizers = append(pt.Finalizers, finalizer) _, err := ptCli.ChaosV1alpha1().PodTerminators().Update(ctx, pt, metav1.UpdateOptions{}) if err != nil { return fmt.Errorf("could not update pod termiantor: %w", err) } } // Handle. return chaossvc.EnsurePodTerminator(pt) }) } func stringPresentInSlice(ss []string, s string) bool { for _, f := range ss { if f == s { return true } } return false } func removeStringFromSlice(ss []string, s string) []string { for i, f := range ss { if f == s { return append(ss[:i], ss[i+1:]...) } } return ss } <file_sep>package chaos import ( "sync" "k8s.io/client-go/kubernetes" chaosv1alpha1 "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/apis/chaos/v1alpha1" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/log" ) // Syncer is the interface that every chaos service implementation // needs to implement. type Syncer interface { // EnsurePodTerminator will ensure that the pod terminator is running and working. EnsurePodTerminator(pt *chaosv1alpha1.PodTerminator) error // DeletePodTerminator will stop and delete the pod terminator. DeletePodTerminator(name string) error } // Chaos is the service that will ensure that the desired pod terminator CRDs are met. // Chaos will have running instances of PodDestroyers. type Chaos struct { k8sCli kubernetes.Interface reg sync.Map logger log.Logger } // NewChaos returns a new Chaos service. func NewChaos(k8sCli kubernetes.Interface, logger log.Logger) *Chaos { return &Chaos{ k8sCli: k8sCli, reg: sync.Map{}, logger: logger, } } // EnsurePodTerminator satisfies ChaosSyncer interface. func (c *Chaos) EnsurePodTerminator(pt *chaosv1alpha1.PodTerminator) error { pkt, ok := c.reg.Load(pt.Name) var pk *PodKiller // We are already running. if ok { pk = pkt.(*PodKiller) // If not the same spec means options have changed, so we don't longer need this pod killer. if !pk.SameSpec(pt) { c.logger.Infof("spec of %s changed, recreating pod killer", pt.Name) if err := c.DeletePodTerminator(pt.Name); err != nil { return err } } else { // We are ok, nothing changed. return nil } } // Create a pod killer. ptCopy := pt.DeepCopy() pk = NewPodKiller(ptCopy, c.k8sCli, c.logger) c.reg.Store(pt.Name, pk) return pk.Start() } // DeletePodTerminator satisfies ChaosSyncer interface. func (c *Chaos) DeletePodTerminator(name string) error { pkt, ok := c.reg.Load(name) if !ok { return nil } pk := pkt.(*PodKiller) if err := pk.Stop(); err != nil { return err } c.reg.Delete(name) return nil } <file_sep>package controller import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" ) // Retriever is how a controller will retrieve the events on the resources from // the APÎ server. // // A Retriever is bound to a single type. type Retriever interface { List(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) Watch(ctx context.Context, options metav1.ListOptions) (watch.Interface, error) } type listerWatcherRetriever struct { lw cache.ListerWatcher } // RetrieverFromListerWatcher returns a Retriever from a Kubernetes client-go cache.ListerWatcher. // If the received lister watcher is nil it will error. func RetrieverFromListerWatcher(lw cache.ListerWatcher) (Retriever, error) { if lw == nil { return nil, fmt.Errorf("listerWatcher can't be nil") } return listerWatcherRetriever{lw: lw}, nil } // MustRetrieverFromListerWatcher returns a Retriever from a Kubernetes client-go cache.ListerWatcher // if there is an error it will panic. func MustRetrieverFromListerWatcher(lw cache.ListerWatcher) Retriever { r, err := RetrieverFromListerWatcher(lw) if lw == nil { panic(err) } return r } func (l listerWatcherRetriever) List(_ context.Context, options metav1.ListOptions) (runtime.Object, error) { return l.lw.List(options) } func (l listerWatcherRetriever) Watch(_ context.Context, options metav1.ListOptions) (watch.Interface, error) { return l.lw.Watch(options) } <file_sep>// Package kooper is a Go library to create simple and flexible Kubernetes controllers/operators easily. // Is as simple as this: // // // Create our retriever so the controller knows how to get/listen for pod events. // retr := controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ // ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { // return k8scli.CoreV1().Pods("").List(options) // }, // WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { // return k8scli.CoreV1().Pods("").Watch(options) // }, // }) // // // Our domain logic that will print all pod events. // hand := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { // pod := obj.(*corev1.Pod) // logger.Infof("Pod event: %s/%s", pod.Namespace, pod.Name) // return nil // }) // // // Create the controller with custom configuration. // cfg := &controller.Config{ // Name: "example-controller", // Handler: hand, // Retriever: retr, // Logger: logger, // } // ctrl, err := controller.New(cfg) // if err != nil { // return fmt.Errorf("could not create controller: %w", err) // } // // // Start our controller. // ctx, cancel := context.WithCancel(context.Background()) // defer cancel() // ctrl.Run(ctx) package kooper <file_sep>//go:build integration // +build integration package controller_test import ( "context" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/cache" "github.com/spotahome/kooper/v2/controller" "github.com/spotahome/kooper/v2/log" "github.com/spotahome/kooper/v2/test/integration/helper/cli" "github.com/spotahome/kooper/v2/test/integration/helper/prepare" ) // TestControllerHandleEvents will test the controller receives the resources list and watch // events are received and handled correctly. func TestControllerHandleEvents(t *testing.T) { tests := []struct { name string addServices []*corev1.Service updateServices []string expAddedServices []string }{ { name: "If a controller is watching services it should react to the service change events.", addServices: []*corev1.Service{ { ObjectMeta: metav1.ObjectMeta{Name: "svc1"}, Spec: corev1.ServiceSpec{ Type: "ClusterIP", Ports: []corev1.ServicePort{ {Name: "port1", Port: 8080}, }, }, }, { ObjectMeta: metav1.ObjectMeta{Name: "svc2"}, Spec: corev1.ServiceSpec{ Type: "ClusterIP", Ports: []corev1.ServicePort{ {Name: "port1", Port: 8080}, }, }, }, }, updateServices: []string{"svc1"}, expAddedServices: []string{"svc1", "svc2", "svc1"}, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) assert := assert.New(t) resync := 30 * time.Second ctx, cancel := context.WithCancel(context.Background()) defer cancel() var gotAddedServices []string // Create the kubernetes client. k8scli, err := cli.GetK8sClient("") require.NoError(err, "kubernetes client is required") // Prepare the environment on the cluster. prep := prepare.New(k8scli, t) prep.SetUp() defer prep.TearDown() // Create the retriever. rt := controller.MustRetrieverFromListerWatcher(cache.NewListWatchFromClient(k8scli.CoreV1().RESTClient(), "services", prep.Namespace().Name, fields.Everything())) // Call times are the number of times the handler should be called before sending the termination signal. stopCallTimes := len(test.addServices) + len(test.updateServices) calledTimes := 0 var mx sync.Mutex // Create the handler. hl := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { mx.Lock() calledTimes++ mx.Unlock() svc := obj.(*corev1.Service) gotAddedServices = append(gotAddedServices, svc.Name) if calledTimes >= stopCallTimes { cancel() } return nil }) // Create a Pod controller. cfg := &controller.Config{ Name: "test-controller", Handler: hl, Retriever: rt, Logger: log.Dummy, ResyncInterval: resync, } ctrl, err := controller.New(cfg) require.NoError(err, "controller is required, can't have error on creation") go ctrl.Run(ctx) // Create the required services. for _, svc := range test.addServices { _, err := k8scli.CoreV1().Services(prep.Namespace().Name).Create(context.Background(), svc, metav1.CreateOptions{}) assert.NoError(err) time.Sleep(1 * time.Second) } for _, svc := range test.updateServices { origSvc, err := k8scli.CoreV1().Services(prep.Namespace().Name).Get(context.Background(), svc, metav1.GetOptions{}) if assert.NoError(err) { // Change something origSvc.Spec.Ports = append(origSvc.Spec.Ports, corev1.ServicePort{Name: "updateport", Port: 9876}) _, err := k8scli.CoreV1().Services(prep.Namespace().Name).Update(context.Background(), origSvc, metav1.UpdateOptions{}) assert.NoError(err) time.Sleep(1 * time.Second) } } // Wait until we have finished. select { // Timeout. case <-time.After(20 * time.Second): // Finished. case <-ctx.Done(): } // Check. assert.Equal(test.expAddedServices, gotAddedServices) }) } } <file_sep>package controller import ( "context" "fmt" "sync" "time" "k8s.io/client-go/util/workqueue" "github.com/spotahome/kooper/v2/log" ) // blockingQueue is a queue that any of its implementations should // implement a blocking get mechanism. type blockingQueue interface { // Add will add an item to the queue. Add(ctx context.Context, item interface{}) // Requeue will add an item to the queue in a requeue mode. // If doesn't accept requeueing or max requeue have been reached // it will return an error. Requeue(ctx context.Context, item interface{}) error // Get is a blocking operation, if the last object usage has not been finished (`done`) // being used it will block until this has been done. Get(ctx context.Context) (item interface{}, shutdown bool) // Done marks the item being used as done. Done(ctx context.Context, item interface{}) // ShutDown stops the queue from accepting new jobs ShutDown(ctx context.Context) // Len returns the size of the queue. Len(ctx context.Context) int } var ( errMaxRetriesReached = fmt.Errorf("max retries reached") ) type rateLimitingBlockingQueue struct { maxRetries int queue workqueue.RateLimitingInterface } func newRateLimitingBlockingQueue(maxRetries int, queue workqueue.RateLimitingInterface) blockingQueue { return rateLimitingBlockingQueue{ maxRetries: maxRetries, queue: queue, } } func (r rateLimitingBlockingQueue) Add(_ context.Context, item interface{}) { r.queue.Add(item) } func (r rateLimitingBlockingQueue) Requeue(_ context.Context, item interface{}) error { // If there was an error and we have retries pending then requeue. if r.queue.NumRequeues(item) < r.maxRetries { r.queue.AddRateLimited(item) return nil } r.queue.Forget(item) return errMaxRetriesReached } func (r rateLimitingBlockingQueue) Get(_ context.Context) (item interface{}, shutdown bool) { return r.queue.Get() } func (r rateLimitingBlockingQueue) Done(_ context.Context, item interface{}) { r.queue.Done(item) } func (r rateLimitingBlockingQueue) ShutDown(_ context.Context) { r.queue.ShutDown() } func (r rateLimitingBlockingQueue) Len(_ context.Context) int { return r.queue.Len() } // metricsQueue is a wrapper for a metrics measured queue. type metricsBlockingQueue struct { mu sync.Mutex name string mrec MetricsRecorder itemsQueuedAt map[interface{}]time.Time logger log.Logger queue blockingQueue } func newMetricsBlockingQueue(name string, mrec MetricsRecorder, queue blockingQueue, logger log.Logger) (blockingQueue, error) { // Register func/callback based metrics. These are controlled by the MetricsRecorder. err := mrec.RegisterResourceQueueLengthFunc(name, func(ctx context.Context) int { return queue.Len(ctx) }) if err != nil { return nil, err } return &metricsBlockingQueue{ name: name, mrec: mrec, itemsQueuedAt: map[interface{}]time.Time{}, logger: logger, queue: queue, }, nil } func (m *metricsBlockingQueue) Add(ctx context.Context, item interface{}) { m.mu.Lock() if _, ok := m.itemsQueuedAt[item]; !ok { m.itemsQueuedAt[item] = time.Now() } m.mu.Unlock() m.mrec.IncResourceEventQueued(ctx, m.name, false) m.queue.Add(ctx, item) } func (m *metricsBlockingQueue) Requeue(ctx context.Context, item interface{}) error { m.mu.Lock() if _, ok := m.itemsQueuedAt[item]; !ok { m.itemsQueuedAt[item] = time.Now() } m.mu.Unlock() m.mrec.IncResourceEventQueued(ctx, m.name, true) return m.queue.Requeue(ctx, item) } func (m *metricsBlockingQueue) Get(ctx context.Context) (interface{}, bool) { // Here should get blocked, warning with the mutexes. item, shutdown := m.queue.Get(ctx) if shutdown { return item, shutdown } m.mu.Lock() queuedAt, ok := m.itemsQueuedAt[item] if ok { m.mrec.ObserveResourceInQueueDuration(ctx, m.name, queuedAt) delete(m.itemsQueuedAt, item) } else { m.logger.WithKV(log.KV{"object-key": item}). Infof("could not measure item because item is not present on metricsMeasuredQueue.itemsQueuedAt map") } m.mu.Unlock() return item, shutdown } func (m *metricsBlockingQueue) Done(ctx context.Context, item interface{}) { m.queue.Done(ctx, item) } func (m *metricsBlockingQueue) ShutDown(ctx context.Context) { m.queue.ShutDown(ctx) } func (m *metricsBlockingQueue) Len(ctx context.Context) int { // Measurement controlled by the metrics recorder, so is implemented in callback // mode, should be already registered, check factory. This is NOOP. return m.queue.Len(ctx) } <file_sep>#!/usr/bin/env sh set -o errexit set -o nounset go test `go list ./... | grep test/integration` -v -tags='integration'<file_sep>package chaos_test import ( "fmt" "testing" "time" "github.com/spotahome/kooper/v2/log" "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/fake" kubetesting "k8s.io/client-go/testing" chaosv1alpha1 "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/apis/chaos/v1alpha1" "github.com/spotahome/kooper/examples/pod-terminator-operator/v2/service/chaos" ) type timeMock struct { after chan time.Time now time.Time } func (t *timeMock) After(_ time.Duration) <-chan time.Time { return t.after } func (t *timeMock) Now() time.Time { return t.now } func TestPodKillerSameSpec(t *testing.T) { defaultPT := &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ PeriodSeconds: 300, MinimumInstances: 2, TerminationPercent: 50, Selector: map[string]string{ "label1": "value1", "label2": "label2", }, DryRun: true, }, } tests := []struct { name string pt *chaosv1alpha1.PodTerminator newPT *chaosv1alpha1.PodTerminator expRes bool }{ { name: "Giving the same podTerminator should return that are the same.", pt: defaultPT, newPT: defaultPT, expRes: true, }, { name: "Giving the same podTerminator should return that are the same.", pt: defaultPT, newPT: &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ PeriodSeconds: 300, MinimumInstances: 2, TerminationPercent: 50, Selector: map[string]string{ "label1": "value1", "label2": "label2", "label3": "label3", }, DryRun: true, }, }, expRes: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert := assert.New(t) // Mocks. mk8s := fake.NewSimpleClientset() // Call the logic to test. pk := chaos.NewPodKiller(test.pt, mk8s, log.Dummy) gotRes := pk.SameSpec(test.newPT) // Check. assert.Equal(test.expRes, gotRes) }) } } func getProbableTargets(n int) *corev1.PodList { targets := make([]corev1.Pod, n) for i := 0; i < n; i++ { targets[i] = corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("podtarget-%d", i), }, } } return &corev1.PodList{ Items: targets, } } func onKubeClientListPods(client *fake.Clientset, pdl *corev1.PodList, callChan chan struct{}) { client.AddReactor("list", "pods", func(action kubetesting.Action) (bool, runtime.Object, error) { // Notify that was called. go func() { callChan <- struct{}{} }() return true, pdl, nil }) } func TestPodKillerPodKill(t *testing.T) { tests := []struct { name string pt *chaosv1alpha1.PodTerminator probableTargets *corev1.PodList expDeletions int }{ { name: "Having a quantity of probable targets and meeting the minimum instances and not dry run mode it should kill the desired percent targets.", pt: &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ MinimumInstances: 2, TerminationPercent: 50, DryRun: false, }, }, probableTargets: getProbableTargets(10), expDeletions: 5, }, { name: "Having a quantity of probable targets and meeting the minimum instances in dry run mode it should not kill any target.", pt: &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ MinimumInstances: 2, TerminationPercent: 50, DryRun: true, }, }, probableTargets: getProbableTargets(10), expDeletions: 0, }, { name: "Having a quantity of probable targets and not meeting the minimum instances and not dry run mode it should kill less targets that the ones we wanted.", pt: &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ MinimumInstances: 7, TerminationPercent: 50, DryRun: false, }, }, probableTargets: getProbableTargets(10), expDeletions: 3, }, { name: "With no targets should not kill anything.", pt: &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ MinimumInstances: 2, TerminationPercent: 50, DryRun: false, }, }, probableTargets: getProbableTargets(0), expDeletions: 0, }, { name: "The 25% of 3 is not an instance, it should not kill anything.", pt: &chaosv1alpha1.PodTerminator{ Spec: chaosv1alpha1.PodTerminatorSpec{ MinimumInstances: 2, TerminationPercent: 25, DryRun: false, }, }, probableTargets: getProbableTargets(3), expDeletions: 0, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { assert := assert.New(t) // Mock time mtimeC := make(chan time.Time, 1) mtimeC <- time.Now() mtime := &timeMock{after: mtimeC} // Mocks kubernetes. listPodcalled := make(chan struct{}) mk8s := &fake.Clientset{} onKubeClientListPods(mk8s, test.probableTargets, listPodcalled) // Call the logic to test. pk := chaos.NewCustomPodKiller(test.pt, mk8s, mtime, log.Dummy) err := pk.Start() defer pk.Stop() if assert.NoError(err) { select { case <-time.After(100 * time.Millisecond): assert.Fail("timeout waiting for pod list call") return case <-listPodcalled: // Ready to check. } // Wait until pod killing <-time.After(5 * time.Millisecond) // Get deletions. var gotDeletions int for _, act := range mk8s.Actions() { if act.Matches("delete", "pods") { gotDeletions++ } } assert.Equal(test.expDeletions, gotDeletions) } }) } } <file_sep>FROM golang:1.20.3 ARG GOLANGCI_LINT_VERSION="1.53.3" ARG MOCKERY_VERSION="2.30.16" ARG ostype=Linux RUN apt-get update && apt-get install -y \ git \ bash \ zip RUN wget https://github.com/golangci/golangci-lint/releases/download/v${GOLANGCI_LINT_VERSION}/golangci-lint-${GOLANGCI_LINT_VERSION}-linux-amd64.tar.gz && \ tar zxvf golangci-lint-${GOLANGCI_LINT_VERSION}-linux-amd64.tar.gz --strip 1 -C /usr/local/bin/ && \ rm golangci-lint-${GOLANGCI_LINT_VERSION}-linux-amd64.tar.gz && \ \ wget https://github.com/vektra/mockery/releases/download/v${MOCKERY_VERSION}/mockery_${MOCKERY_VERSION}_Linux_x86_64.tar.gz && \ tar zxvf mockery_${MOCKERY_VERSION}_Linux_x86_64.tar.gz -C /tmp && \ mv /tmp/mockery /usr/local/bin/ && \ rm mockery_${MOCKERY_VERSION}_Linux_x86_64.tar.gz # Create user. ARG uid=1000 ARG gid=1000 RUN bash -c 'if [ ${ostype} == Linux ]; then addgroup -gid $gid app; else addgroup app; fi && \ adduser --disabled-password -uid $uid --ingroup app --gecos "" app && \ chown app:app -R /go' # Fill go mod cache. RUN mkdir /tmp/cache COPY go.mod /tmp/cache COPY go.sum /tmp/cache RUN chown app:app -R /tmp/cache USER app RUN cd /tmp/cache && \ go mod download WORKDIR /src <file_sep>package controller import ( "context" "time" ) // MetricsRecorder knows how to record metrics of a controller. type MetricsRecorder interface { // IncResourceEvent increments in one the metric records of a queued event. IncResourceEventQueued(ctx context.Context, controller string, isRequeue bool) // ObserveResourceInQueueDuration measures how long takes to dequeue a queued object. If the object is already in queue // it will be measured once, since the first time it was added to the queue. ObserveResourceInQueueDuration(ctx context.Context, controller string, queuedAt time.Time) // ObserveResourceProcessingDuration measures how long it takes to process a resources (handling). ObserveResourceProcessingDuration(ctx context.Context, controller string, success bool, startProcessingAt time.Time) // RegisterResourceQueueLengthFunc will register a function that will be called // by the metrics recorder to get the length of a queue at a given point in time. RegisterResourceQueueLengthFunc(controller string, f func(context.Context) int) error } // DummyMetricsRecorder is a dummy metrics recorder. var DummyMetricsRecorder = dummy(0) var _ MetricsRecorder = DummyMetricsRecorder type dummy int func (dummy) IncResourceEventQueued(context.Context, string, bool) {} func (dummy) ObserveResourceInQueueDuration(context.Context, string, time.Time) {} func (dummy) ObserveResourceProcessingDuration(context.Context, string, bool, time.Time) {} func (dummy) RegisterResourceQueueLengthFunc(controller string, f func(context.Context) int) error { return nil } <file_sep>package controller import ( "context" "fmt" "time" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/cache" "github.com/spotahome/kooper/v2/log" ) // processor knows how to process object keys. type processor interface { Process(ctx context.Context, key string) error } // processorFunc a helper to create processors. type processorFunc func(ctx context.Context, key string) error func (p processorFunc) Process(ctx context.Context, key string) error { return p(ctx, key) } // newIndexerProcessor returns a processor that processes a key that will get the kubernetes object // from a cache called indexer were the kubernetes watch updates have been indexed and stored // by the listerwatchers from the informers. func newIndexerProcessor(indexer cache.Indexer, handler Handler) processor { return processorFunc(func(ctx context.Context, key string) error { // Get the object obj, exists, err := indexer.GetByKey(key) if err != nil { return err } if !exists { return nil } return handler.Handle(ctx, obj.(runtime.Object)) }) } var errRequeued = fmt.Errorf("requeued after receiving error") // newRetryProcessor returns a processor that will delegate the processing of a key to the // received processor, in case the processing/handling of this key fails it will add the key // again to a queue if it has retrys pending. // // If the processing errored and has been retried, it will return a `errRequeued` error. func newRetryProcessor(name string, queue blockingQueue, logger log.Logger, next processor) processor { return processorFunc(func(ctx context.Context, key string) error { err := next.Process(ctx, key) if err != nil { // Retry if possible. requeueErr := queue.Requeue(ctx, key) if requeueErr != nil { return fmt.Errorf("could not retry: %s: %w", requeueErr, err) } logger.WithKV(log.KV{"object-key": key}).Warningf("item requeued due to processing error: %s", err) return nil } return nil }) } // newMetricsProcessor returns a processor that measures everything related with the processing logic. func newMetricsProcessor(name string, mrec MetricsRecorder, next processor) processor { return processorFunc(func(ctx context.Context, key string) (err error) { defer func(t0 time.Time) { mrec.ObserveResourceProcessingDuration(ctx, name, err == nil, t0) }(time.Now()) return next.Process(ctx, key) }) } <file_sep># Kooper [![CI](https://github.com/spotahome/kooper/actions/workflows/ci.yaml/badge.svg?branch=master)](https://github.com/spotahome/kooper/actions/workflows/ci.yaml) [![Go Report Card](https://goreportcard.com/badge/github.com/spotahome/kooper)](https://goreportcard.com/report/github.com/spotahome/kooper) [![Apache 2 licensed](https://img.shields.io/badge/license-Apache2-blue.svg)](https://raw.githubusercontent.com/spotahome/kooper/master/LICENSE) [![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/spotahome/kooper)](https://github.com/spotahome/kooper/releases/latest) ![Kubernetes release](https://img.shields.io/badge/Kubernetes-v1.28-green?logo=Kubernetes&style=flat&color=326CE5&logoColor=white) Kooper is a Go library to create simple and flexible Kubernetes [controllers]/operators, in a fast, decoupled and easy way. In other words, is a small alternative to big frameworks like [Kubebuilder] or [operator-framework]. **Library refactored (`v2`), for `v2` use `import "github.com/spotahome/kooper/v2"`** ## Features - Easy usage and fast to get it working. - Extensible (Kooper doesn't get in your way). - Simple core concepts - `Retriever` + `Handler` is a `controller` - An `operator` is also a `controller`. - Metrics (extensible with Prometheus already implementated). - Ready for core Kubernetes resources (pods, ingress, deployments...) and CRDs. - Optional leader election system for controllers. ## V0 vs V2 First of all, we used `v2` instead of `v[01]`, because it changes the library as a whole, theres no backwards compatibility, `v0` is stable and used in production, although you eventually will want to update to `v2` becasuse `v0` will not be updated. Import with: ```golang import "github.com/spotahome/kooper/v2" ``` Regarding the changes... To know all of them check the changelog but mainly we simplified everything. The most relevant changes you will need to be aware and could impact are: - Before there were concepts like `operator` and `controller`, now only `controller` (this is at library level, you can continue creating controllers/operators). - Before the CRD management was inside the library, now this should be managed outside Kooper. - You can use [this][kube-code-generator] to generate these manifests to register outside Kooper. - This is because controllers and CRDs have different lifecycles. - Refactored Prometheus metrics to be more reliable, so you will need to change dashboards/alerts. - `Delete` event removed because wasn't reliable (Check `Garbage-collection` section). ## Getting started The simplest example that prints pods would be this: ```go // Create our retriever so the controller knows how to get/listen for pod events. retr := controller.MustRetrieverFromListerWatcher(&cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { return k8scli.CoreV1().Pods("").List(options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { return k8scli.CoreV1().Pods("").Watch(options) }, }) // Our domain logic that will print all pod events. hand := controller.HandlerFunc(func(_ context.Context, obj runtime.Object) error { pod := obj.(*corev1.Pod) logger.Infof("Pod event: %s/%s", pod.Namespace, pod.Name) return nil }) // Create the controller with custom configuration. cfg := &controller.Config{ Name: "example-controller", Handler: hand, Retriever: retr, Logger: logger, } ctrl, err := controller.New(cfg) if err != nil { return fmt.Errorf("could not create controller: %w", err) } // Start our controller. ctx, cancel := context.WithCancel(context.Background()) defer cancel() ctrl.Run(ctx) ``` ## Kubernetes version compatibility Kooper at this moment uses as base `v1.17`. But [check the integration test in CI][ci] to know the supported versions. ## When should I use Kooper? ### Alternatives What is the difference between kooper and alternatives like [Kubebuilder] or [operator-framework]? Kooper embraces the Go philosophy of having small simple components/libs and use them as you wish in combination of others, instead of trying to solve every use case and imposing everything by sacriying flexbility and adding complexity. As an example using the web applications world as reference: We could say that Kooper is more like Go HTTP router/libs, on the other side, Kubebuilder and operator-framework are like Ruby on rails/Django style frameworks. For example Kubebuilder comes with: - Admission webhooks. - Folder/package structure conventions. - CRD clients generation. - RBAC manifest generation. - Not pluggable/flexible usage of metrics, logging, HTTP/K8s API clients... - ... Kooper instead solves most of the core controller/operator problems but as a simple, small and flexible library, and let the other problems (like admission webhooks) be solved by other libraries specialiced on that. e.g - Use whatever you want to create your CRD clients, maybe you don't have CRDs at all! (e.g [kube-code-generator]). - You can setup your admission webhooks outside your controller by using other libraries like (e.g [Kubewebhook]). - You can create your RBAC manifests as you wish and evolve while you develop your controller. - Set you prefered logging system/style (comes with logrus implementation). - Implement your prefered metrics backend (comes with Prometheus implementaion). - Use your own Kubernetes clients (Kubernetes go library, implemented by your own for a special case...). - ... ### Simplicty VS optimization Kooper embraces simplicity over optimization, it favors small APIs, simplicity and easy to use/test methods. Some examples: - Each Kooper controller is independent, don't share anything unless the user says explicitly (e.g. 2 controllers receive the same handler). - Kooper uses a different resource/event cache internally for each controller (less bugs/corner cases but less optimized). - Kooper handler receives the K8s resource, the responsibility of how this object is used is on the user. - Multiresource controllers are made with independent controllers on the same app. ## More examples On the [examples] folder you have different examples, like regular controllers, operators, metrics based, leader election, multiresource type controllers... ## Core concepts Concept doesn't do a distinction between Operators and controllers, all are controllers, the difference of both is on what resources are retrieved. A controller is based on 3 simple concepts: ### Retriever The component that lists and watch the resources the controller will handle when there is a change. Kooper comes with some helpers to create fast retrievers: - `Retriever`: The core retriever it needs to implement list (list objects), and watch, subscribe to object changes. - `RetrieverFromListerWatcher`: Converts a Kubernetes ListerWatcher into a kooper Retriever. The `Retriever` can be based on Kubernetes base resources (Pod, Deployment, Service...) or based on CRDs, theres no distinction. The `Retriever` is an interface so you can use the middleware/wrapper/decorator pattern to extend (e.g add custom metrics). ### Handler Kooper handles all the events on the same handler: - `Handler`: The interface that knows how to handle kubernetes objects. - `HandlerFunc`: A helper that gets a `Handler` from a function so you don't need to create a new type to define your `Handler`. The `Handler` is an interface so you can use the middleware/wrapper/decorator pattern to extend (e.g add custom metrics). ### Controller The controller is the component that uses the `Handler` and `Retriever` to start a feedback loop controller process: - On the first start it will use `controller.Retriever.List` to get all the resources and pass them to the `controller.Handler`. - Then it will call `controller.Handler` for every change done in the resources using the `controller.Retriever.Watcher`. - At regular intervals (3 minute by default) it will call `controller.Handler` with all resources in case we have missed a `Watch` event. ## Other concepts ### Leader election Check [Leader election](docs/leader-election.md). ### Garbage collection Kooper only handles the events of resources that exist, these are triggered when the resources being watched are updated or created. There is no delete event, so in order to clean the resources you have 2 ways of doing these: - If your controller creates as a side effect new Kubernetes resources you can use [owner references][owner-ref] on the created objects. - If you want a more flexible clean up process (e.g clean from a database or a 3rd party service) you can use [finalizers], check the [pod-terminator-operator][finalizer-example] example. ### Multiresource or secondary resources Sometimes we have controllers that work on a main or primary resource and we also want to handle the events of a secondary resource that is based on the first one. For example, a deployment controller that watches the pods (secondary) that belong to the deployment (primary) handled. After using multiresource controllers/retrievers, we though that we don't need a multiresource controller, this is not necesary becase: - Adds complexity. - Adds corner cases, this translates in bugs, e.g - Internal object cache based on IDs of `{namespace}/{name}` scheme (ignoring types). - Receiving a deletion watch event of one type removes the other type object with the same name from the cache (service and deployment have same ns and same name). - The different resources that share name and ns, will be only process one of the types (sometimes is useful, others adds bugs and corner cases). - An error on one of the retrieval types stops all the controller handling process and not only the one based on that type. - Programatically speaking, you can reuse the `Handler` in multiple controllers. The solution to these problems, is to embrace simplicity once again, and mainly is creating multiple controllers using the same `Handler`, each controller with a different `ListerWatcher`. The `Handler` API is easy enough to reuse it across multiple controllers, check an [example][multiresource-example]. Also, this comes with extra benefits: - Different controller interval depending on the type (fast changing secondary objects can reconcile faster than the primary one, or viceversa). - Wrap the controller handler with a middlewre only for a particular type. - One of the type retrieval fails, the other type controller continues working (running in degradation mode). - Flexibility, e.g leader election for the primary type, no leader election for the secondary type. - Controller config has a handy flag to disable resync (`DisableResync`), sometimes this can be useful on secondary resources (only act on changes). [travis-image]: https://travis-ci.org/spotahome/kooper.svg?branch=master [travis-url]: https://travis-ci.org/spotahome/kooper [goreport-image]: https://goreportcard.com/badge/github.com/spotahome/kooper [goreport-url]: https://goreportcard.com/report/github.com/spotahome/kooper [godoc-image]: https://pkg.go.dev/badge/github.com/spotahome/kooper/v2 [godoc-url]: https://pkg.go.dev/github.com/spotahome/kooper/v2 [examples]: examples/ [grafana-dashboard]: https://grafana.com/dashboards/7082 [controllers]: https://kubernetes.io/docs/concepts/architecture/controller/ [kubebuilder]: https://github.com/kubernetes-sigs/kubebuilder [operator-framework]: https://github.com/operator-framework [kubewebhook]: https://github.com/slok/kubewebhook [kube-code-generator]: https://github.com/slok/kube-code-generator [owner-ref]: https://kubernetes.io/docs/concepts/workloads/controllers/garbage-collection/#owners-and-dependents [finalizers]: https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#finalizers [finalizer-example]: examples/pod-terminator-operator/operator/operator.go [multiresource-example]: examples/multi-resource-controller [ci]: https://github.com/spotahome/kooper/actions <file_sep>#!/usr/bin/env sh set -o errexit set -o nounset go test -race -coverprofile=.test_coverage.txt ./... go tool cover -func=.test_coverage.txt | tail -n1 | awk '{print "Total test coverage: " $3}'
f0746250f9e54632304b7b262c887127e9374a13
[ "Markdown", "Makefile", "Go", "Dockerfile", "Shell" ]
42
Makefile
spotahome/kooper
7e6a38864f016ed9300fe61772c57d91717cfd5a
d136bbf3cc41b8fe1aa4d48796e7af2df1337028
refs/heads/master
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SchedSectionComponent } from './sched-section.component'; describe('SchedSectionComponent', () => { let component: SchedSectionComponent; let fixture: ComponentFixture<SchedSectionComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SchedSectionComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SchedSectionComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HeaderComponent } from './header/header.component'; import { IntroSectionComponent } from './intro-section/intro-section.component'; import { SectionMainComponent } from './section-main/section-main.component'; import { SchedSectionComponent } from './sched-section/sched-section.component'; import { HotelsSectionComponent } from './hotels-section/hotels-section.component'; import { VenueSectionComponent } from './venue-section/venue-section.component'; import { GallerySectionComponent } from './gallery-section/gallery-section.component'; import { HistorySectionComponent } from './history-section/history-section.component'; import { FooterComponent } from './footer/footer.component'; import { FaqSectionComponent } from './faq-section/faq-section.component'; import { MyTeamComponent } from './my-team/my-team.component'; import { RegisterSignInComponent } from './register-sign-in/register-sign-in.component'; import { HomeComponent } from './home/home.component'; @NgModule({ declarations: [ AppComponent, HeaderComponent, IntroSectionComponent, SectionMainComponent, SchedSectionComponent, HotelsSectionComponent, VenueSectionComponent, GallerySectionComponent, HistorySectionComponent, FooterComponent, FaqSectionComponent, MyTeamComponent, RegisterSignInComponent, HomeComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RegisterSignInComponent } from './register-sign-in.component'; describe('RegisterSignInComponent', () => { let component: RegisterSignInComponent; let fixture: ComponentFixture<RegisterSignInComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ RegisterSignInComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(RegisterSignInComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
fe45e49a222e1d64e57857674423281c1ff478a9
[ "TypeScript" ]
3
TypeScript
NeilKennethLSapungan/AWDFinalProject
8d7d5fc098cbcf1f63f1296156a94179095093d2
404cfb62079b78c044e30d92cef852ce77bc4939
refs/heads/master
<repo_name>hao1000/Todo_List<file_sep>/src/components/TaskItem.js import React, { Component } from 'react'; class TaskItem extends Component { render() { var {task} = this.props; return ( <tr> <td>{task.name}</td> </tr> ); } } export default TaskItem;<file_sep>/src/components/TaskForm.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import * as actions from './../actions/index' class TaskForm extends Component { constructor(props){ super(props); this.state={ id:'', name:'', } } onChange =(event) => { var target = event.target; var name = target.name; var value =target.value; this.setState({ [name] : value }); } onSubmit = (event) => { event.preventDefault(); // Do not load Form this.props.onAddTask(this.state); this.onClear(); } onClear = () =>{ this.setState({ name:'', }); } render() { return ( <div className="input-group" > <form onSubmit={this.onSubmit}> <input type="text ps-5" className="form-control-right mr-5" placeholder="Add to list" name="name" value={this.state.name} onChange={this.onChange} ></input> <div className="text-right"> <button type="submit" className="btn btn-warning btn-5"> <span className="fa fa-plus "></span> Add </button> </div> </form> </div> ); } } const mapStateToProps = (state) => { // Vì có 1 tham số nên có thể bỏ () // Phải trả về 1 object return { } }; // Gửi tới Reducer // Chuyển dispath thành props const mapDispatchToProps = (dispath,props) => { return{ onAddTask:( task) => { dispath(actions.addTask(task)); // Từ action đã import } } } // Connect : tham số thứ 2 là 1 action export default connect(mapStateToProps,mapDispatchToProps)(TaskForm);<file_sep>/src/components/TaskList.js import React, { Component } from 'react'; import TaskItem from './TaskItem'; import {connect } from 'react-redux'; // Ket noi voi Store de len lay xuong class TaskList extends Component { onChange=(event)=>{ var targets = event.target; var name = targets.name; var value = targets.value; this.setState({ [name]:value }); } render() { var tasks = this.props.tasks_get;// var tasks =this.props.tasks var elmTaskItem = tasks.map((task, index) => { return <TaskItem key={task.id} task={task} /> }); return ( <table className="table table-bordered table-hover" > <tbody> {elmTaskItem} </tbody> </table> ); } } const mapStatetoProps =(state) => { //store of state return { tasks_get: state.tasks // Key : tasks / value : state( trong store - reducer) // get tasks from Store } }; export default connect(mapStatetoProps,null) (TaskList);
6cf76022730b67a5a3f00746636a766cde11ed37
[ "JavaScript" ]
3
JavaScript
hao1000/Todo_List
b7d693626c23e9f4834b5e6127c3aec4d595893b
04b6162b6c15fd3c5a8f01eb17ece77222433f54
refs/heads/master
<file_sep>#!/usr/bin/env python # encoding: utf-8 """ test.py Created by <NAME> on 2012-05-12. Copyright (c) 2012 valdergallo. All rights reserved. """ import sys import threading import time _Event = threading._Event class Event(_Event): # Event from Celery if not hasattr(threading._Event, "is_set"): is_set = _Event.isSet class ThereadTest(threading.Thread): def __init__(self, threadID=1, name='threding-1'): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.count_runner = 1 self.is_shutdown = Event() def stop(self): print 'STOOPED \n' sys.exit() def start(self): self.is_shutdown.set() while True: print '%s - Break with the random power!!! \n' % self.count_runner if self.count_runner == 3: self.stop() self.count_runner += 1 time.sleep(1) def main(): beat = ThereadTest() beat.daemon = True beat.start() if __name__ == '__main__': main() <file_sep>Django Twitter Beat ==================== Twitter Beat subprocess to follow Twitters from one username TO INSTALL ---------- pip install twitterbeat or 1. Download zip file 2. Extract it 3. Execute in the extracted directory: python setup.py install Add on project settings INSTALLED_APPS = ( ... 'twitterbeat' ) CONFIGURE --------- Go to django admin on app twitterbeat you will see Accounts. Set your username and save and start daemon with command. USAGE ----- - Starting subprocess to get Twitters ```python python manage.py twitter_beat --start ``` - Restart subprocess ```python python manage.py twitter_beat --restart ``` - Stop subprocess ```python python manage.py twitter_beat --stop ``` Requirements ------------ - django 1.2.x or higher - python-twitter==0.8.2 - feedparser==5.1.2 TODO ---- - Test daemon on Windows - CSS to default twitter list <file_sep>#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by <NAME> on 2012-05-09. Copyright (c) 2012 valdergallo. All rights reserved. """ from django.conf.urls import patterns, include, url from django.views.generic import ListView from twitterbeat.models import Tweet from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', ListView.as_view( model=Tweet, )), )<file_sep>#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by <NAME> on 2012-05-10. Copyright (c) 2012 valdergallo. All rights reserved. """ import time import re from datetime import datetime import twitter import feedparser from django.conf import settings from twitterbeat.models import Account, Tweet, ConnectionError from twitterbeat.daemon import Daemon from django.contrib.admin.models import LogEntry, ADDITION from django.contrib.contenttypes.models import ContentType class TwitterBeat(Daemon): def __init__(self, pidfile, *args, **kwargs): super(TwitterBeat, self).__init__(self, *args, **kwargs) self.KeepAlive = True self.pidfile = pidfile user_id = getattr(settings, 'TWITTER_USER_ID', Account.objects.filter(active=True).latest('id').id) self.twitter_user = Account.objects.get(id=user_id, active=True) self.twitter_rss = 'http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=%s' \ % self.twitter_user.username @staticmethod def _get_status_id_from_link(link): item = re.findall(r'/(\d+)', link) if len(item): return item.pop() else: return None @staticmethod def _convert_datetime(created_at_string): """Convert string to datetime""" fmt = '%a %b %d %H:%M:%S +0000 %Y' #Tue Apr 26 08:57:55 +0000 2011 return datetime.strptime(created_at_string, fmt) def parse_rss(self): """ #fields t.entries[0].published_parsed #created_at t.entries[0].link #urls t.entries[0].id #id - need parse t.entries[0].summary #text t.entries[0].title #title """ tweets = feedparser.parse(self.twitter_rss) parsed = [] for tweet in tweets.entries: parsed.append({ 'created_at': tweet.published_parsed, 'link': tweet.link, 'text': tweet.summary.replace('%s:' % self.twitter_user.username, ''), 'status_id': self._get_status_id_from_link(tweet.link), }) return parsed def parse_tweet(self): """ #fields tweet.text tweet.created_at tweet.urls tweet.user.name tweet.id """ api = twitter.Api() try: tweets = api.GetUserTimeline(self.twitter_user, count=10) except Exception, e: ConnectionError.objects.create(text=e) return self.parse_rss() parsed = [] for tweet in tweets: parsed.append({ 'created_at': self._convert_datetime(tweet.created_at), 'link': "https://twitter.com/#!/%s/status/%s" % (tweet.user.name, tweet.id), 'text': tweet.text, 'status_id': tweet.id, }) return parsed def handle(self): tweets = self.parse_tweet() for tweet in tweets: tw , created = Tweet.objects.get_or_create(**tweet) if created: LogEntry.objects.log_action( user_id = self.twitter_user.pk, content_type_id = ContentType.objects.get_for_model(Tweet).pk, object_repr = 'twitterbeat', object_id = tw.pk, action_flag = ADDITION ) time.sleep(60) def stop(self): self.KeepAlive = False super(TwitterBeat, self).stop() def run(self): while True: if self.twitter_user.active: self.handle() else: self.stop() if __name__ == "__main__": beat = TwitterBeat('./twitterbeat.pid') beat.start() <file_sep>#!/usr/bin/env python # encoding: utf-8 """ twitter_beat.py Created by <NAME> on 2012-05-05. Copyright (c) 2012 valdergallo. All rights reserved. """ from django.core.management.base import BaseCommand, CommandError from optparse import make_option from twitterbeat import TwitterBeat from django.conf import settings options = ( make_option('--start', action="store_true", dest='start', default=False, help='Start service to twitter check'), make_option('--restart', action="store_true", dest='restart', default=False, help='Restart service to twitter check'), make_option('--stop', action='store_true',dest='stop', default=False, help='Close service'), ) TWITTER_BEAT = TwitterBeat('./twitterbeat.pid') class Command(BaseCommand): help = 'Twitter Beat is one service active on background to check updates on status from one user' option_list = BaseCommand.option_list + options def handle(self, *args, **options): if options['start']: TWITTER_BEAT.start() elif options['restart']: TWITTER_BEAT.restart() elif options['stop']: TWITTER_BEAT.stop() else: print self.help <file_sep>#!/usr/bin/env python # encoding: utf-8 """ admin.py Created by <NAME> on 2012-05-05. Copyright (c) 2012 valdergallo. All rights reserved. """ from django.contrib import admin from twitterbeat.models import Tweet, Account, ConnectionError admin.site.register(Tweet) admin.site.register(Account) admin.site.register(ConnectionError)<file_sep>#!/usr/bin/env python # encoding: utf-8 """ __init__.py Created by <NAME> on 2012-05-05. Copyright (c) 2012 valdergallo. All rights reserved. """ from django.db import models class Tweet(models.Model): status_id = models.BigIntegerField() text = models.TextField(blank=True) link = models.CharField(max_length=255) created_at = models.DateTimeField(null=True, blank=True) class Meta: ordering = ('-status_id',) def __unicode__(self): return self.text class Account(models.Model): username = models.CharField(max_length=255) active = models.BooleanField(default=True) def __unicode__(self): return self.username class ConnectionError(models.Model): text = models.TextField() created_at = models.DateTimeField(auto_now=True) def __unicode__(self): return self.text
1edf09ba6a175c9c1860d80d83b4ce14329ed999
[ "Markdown", "Python" ]
7
Python
valdergallo/twitterbeat
666f9fc10c296f301e4774c07c04a58fb27603bd
e46b0d2404c3b4088b7fa1fc8fea32ebd1382c32
refs/heads/master
<repo_name>shivil/rails_authentication_server<file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user add_flash_types :error, :success private def current_user session[:user_id] end def session_expiry expire_time = session[:expires_at] || Time.current @time_left = (expire_time - Time.current).to_i unless @time_left > 0 reset_session flash[:error] = 'Please login to continue' end end def login_required if session[:user_id] # set current user object to @current_user object variable @current_user = current_user return true else redirect_to login_path, error:"Please login to continue" return false end end end <file_sep>/db/migrate/20140516192144_add_user_id_to_app_detail.rb class AddUserIdToAppDetail < ActiveRecord::Migration def change add_column :app_details, :user_id, :integer, after: :name add_index :app_details, :user_id end end <file_sep>/db/migrate/20140516211354_change_column_name_app_detail_id_to_user_id.rb class ChangeColumnNameAppDetailIdToUserId < ActiveRecord::Migration def change rename_column :tokens, :app_detail_id, :user_id end end <file_sep>/Gemfile source 'https://rubygems.org' group :development do gem 'rspec' gem 'rake' gem 'guard' gem 'guard-rspec' gem 'simplecov' gem 'yard' gem 'ci_reporter' gem 'simplecov-rcov' gem 'rdiscount' gem 'rspec-rails', '~> 2.6' gem 'rails_best_practices' gem 'thin' gem 'sqlite3' end group :test do # Pretty printed test output gem 'turn', '0.8.2', :require => false gem 'rspec-rails', '~> 2.6' gem 'sqlite3' end group :osx do gem 'growl' gem 'rb-fsevent' end group :linux do gem 'rb-inotify' gem 'libnotify' end group :doc do # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', require: false end # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.0.0' gem 'mysql2' # Use LESS for stylesheets gem 'less-rails', '~> 2.5.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~> 4.0.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 1.2' # See https://github.com/sstephenson/execjs#readme for more supported runtimes gem 'therubyracer', :platforms => :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Use ActiveModel has_secure_password gem 'bcrypt-ruby', '~> 3.0.0' # Use debugger # gem 'debugger', group: [:development, :test] gem 'twitter-bootstrap-rails', :git => 'git://github.com/seyhunak/twitter-bootstrap-rails.git' gem 'coffee-script' <file_sep>/app/models/token.rb class Token < ActiveRecord::Base belongs_to :app_detail before_create :generate_tokens def generate_api_code end private def generate_tokens begin self.access_token = SecureRandom.hex(10) end while self.class.exists?(access_token: access_token) begin self.code = SecureRandom.hex(10) end while self.class.exists?(code: code) end end <file_sep>/TODO.md ## TODO * Test with a full stack Rails app. ## CHANGES 20120115 (<EMAIL>) * Replacing test/unit with Rspec * Guardfile, Rakefile, bundler imports from MobME * README.md * No coffeescript or SASS <file_sep>/app/views/app_details/index.json.jbuilder json.array!(@app_details) do |app_detail| json.extract! app_detail, :id, :name, :redirect_url, :client_id, :secret_code json.url app_detail_url(app_detail, format: :json) end <file_sep>/app/controllers/app_details_controller.rb class AppDetailsController < ApplicationController before_action :login_required before_action :set_app_detail, only: [:show, :edit, :update, :destroy] # GET /app_details # GET /app_details.json def index @app_details = AppDetail.all end # GET /app_details/1 # GET /app_details/1.json def show end # GET /app_details/new def new @app_detail = AppDetail.new end # GET /app_details/1/edit def edit end # POST /app_details # POST /app_details.json def create @app_detail = AppDetail.new(app_detail_params.merge(user_id: session[:user_id])) respond_to do |format| if @app_detail.save format.html { redirect_to @app_detail, notice: 'App detail was successfully created.' } format.json { render action: 'show', status: :created, location: @app_detail } else format.html { render action: 'new' } format.json { render json: @app_detail.errors, status: :unprocessable_entity } end end end # PATCH/PUT /app_details/1 # PATCH/PUT /app_details/1.json def update respond_to do |format| if @app_detail.update(app_detail_params) format.html { redirect_to @app_detail, notice: 'App detail was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @app_detail.errors, status: :unprocessable_entity } end end end # DELETE /app_details/1 # DELETE /app_details/1.json def destroy @app_detail.destroy respond_to do |format| format.html { redirect_to app_details_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_app_detail @app_detail = AppDetail.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def app_detail_params params.require(:app_detail).permit(:name, :redirect_url, :client_id, :secret_code) end end <file_sep>/spec/routing/app_details_routing_spec.rb require "spec_helper" describe AppDetailsController do describe "routing" do it "routes to #index" do get("/app_details").should route_to("app_details#index") end it "routes to #new" do get("/app_details/new").should route_to("app_details#new") end it "routes to #show" do get("/app_details/1").should route_to("app_details#show", :id => "1") end it "routes to #edit" do get("/app_details/1/edit").should route_to("app_details#edit", :id => "1") end it "routes to #create" do post("/app_details").should route_to("app_details#create") end it "routes to #update" do put("/app_details/1").should route_to("app_details#update", :id => "1") end it "routes to #destroy" do delete("/app_details/1").should route_to("app_details#destroy", :id => "1") end end end <file_sep>/app/models/user.rb require 'digest/md5' class User < ActiveRecord::Base has_one :token has_many :app_details before_validation :prep_email has_secure_password validates :email, uniqueness: true, presence: true validates :name, presence: true validates :password_digest, presence: true def self.authenticate_user params user = where(email: params[:email]).first rescue nil if user && user.authenticate(params[:password]) return user else return false end end private def prep_email self.email = self.email.strip.downcase if self.email end end <file_sep>/README.md Rails Oauth Authentication Server ========= Rails Based authentication server How To Install -------------- ```sh git clone https://github.com/shivil/rails_authentication_server.git rails_authentication_server cd rails_authentication_server Edit database.yml configuration bundle exec rake db:setup ### Running Rails bundle exec rails s ``` Application Flow --- Sign up a new user and register a new client application. Then you will get the new app_secret, client_id Login API requires client_id, app_secret, and redirect_uri as the parameters **Login API** ```sh http://0.0.0.0:3000/api/request/new?client_id=<client_id>&app_secret=app_secret&redirect_uri=<url> ``` then after successful user login, redirects the user to the redirect_uri with the code **Callback API** ```sh http://0.0.0.0:3000/api/request/callback?code=<code> ``` The Authentication server will issue the access token as a JSON response to the client request <file_sep>/config/initializers/session_store.rb # Be sure to restart your server when you modify this file. AuthenticationServer::Application.config.session_store :cookie_store, key: '_mobme_session' <file_sep>/Rakefile #!/usr/bin/env rake # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require File.expand_path('../config/application', __FILE__) AuthenticationServer::Application.load_tasks unless ENV['RAILS_ENV'].to_s == 'production' require 'yard' require 'yard/rake/yardoc_task' require 'ci/reporter/rake/rspec' YARD::Rake::YardocTask.new(:yard) do |y| y.options = %w(--output-dir yardoc) end namespace :yardoc do desc 'generates yardoc files to yardoc/' task :generate => :yard do puts 'Yardoc files generated at yardoc/' end desc 'genartes and publish yardoc files to yardoc.mobme.in' task :publish => :generate do project_name = `git config remote.origin.url`.match(/(git@git.mobme.in:|git:\/\/gits.mobme.in\/)(.*).git/).captures.last.split('/').join('-') system "rsync -avz yardoc/ mobme@yardoc.mobme.in:/home/mobme/deploy/yardoc.mobme.in/current/#{project_name}" puts "Documentation published to http://yardoc.mobme.in/#{project_name}" end end end <file_sep>/app/controllers/api/request_controller.rb class Api::RequestController < ApplicationController def new @authenticate = AppDetail.authenticate_app(params) if @authenticate.is_a?(Hash) render json: @authenticate else @redirect_uri = params[:redirect_uri] end end def create user = User.authenticate_user params if user token = if user.token.blank? Token.create(user_id: user.id) else user.token end url = params[:redirect_uri] url += "?" unless params[:redirect_uri].include?("?") url += {code: token.code}.to_param redirect_to url else render 'new', :redirect_uri => params[:redirect_uri] end end def callback response = begin token = Token.where(code: params[:code]).first {status: true, access_token: token.access_token} rescue Exception => e {status: false, reason: "Invalid Request"} end render json: response end end <file_sep>/db/migrate/20140516170220_change_column_name_secret_code_to_app_secret.rb class ChangeColumnNameSecretCodeToAppSecret < ActiveRecord::Migration def change rename_column :app_details, :secret_code, :app_secret end end <file_sep>/app/models/app_detail.rb class AppDetail < ActiveRecord::Base belongs_to :user before_create :generate_token def self.authenticate_app params if valid_url? params[:redirect_uri] begin details = where(client_id: params[:client_id], app_secret: params[:app_secret]).first return details rescue Exception => e return {status: false, reason: "Invalid App Details"} end else return {status: false, reason: "Invalid URI"} end end protected def generate_token self.app_secret = loop do random_code = SecureRandom.urlsafe_base64(nil, false) break random_code unless AppDetail.exists?(app_secret: random_code) end self.client_id = loop do random_id = SecureRandom.hex(12) break random_id unless AppDetail.exists?(client_id: random_id) end end def self.valid_url? url begin uri = URI.parse(url) return uri.kind_of?(URI::HTTP) rescue Exception => e return false end end def generate_temp_code end end <file_sep>/app/controllers/sessions_controller.rb class SessionsController < ApplicationController layout 'login' def new if current_user redirect_to app_details_path and return end end def create user = User.authenticate_user params if user session[:user_id] = user.id redirect_to app_details_path, success: "Logged in!" else redirect_to root_url, error: "Invalid Email/Password" end end def destroy session[:user_id] = nil redirect_to root_url, notice: "Logged Out" end end
7f60e953c04e3b26ff90ce1b84984e2a6749b08b
[ "Markdown", "Ruby" ]
17
Ruby
shivil/rails_authentication_server
675e947362e4f8383f527a10de4ea1eba36deed1
e285efe4180332aca77ae38c50692b47e1ce912f
refs/heads/main
<repo_name>kiteday/review-test<file_sep>/week1/testfile.py test version 2.0 2020.12.27 <file_sep>/README.md # review-test 깃허브에 익숙하지 않은 사람 연습 공간 <file_sep>/week1/13458_시험감독_kiteday.py import cv2 #this is test #테스트 #테st<file_sep>/week1/testfile.c test 2020.12.27 빠밤
4a421ac32f8c6bd6706eda12005fa390f4c07faa
[ "Markdown", "C", "Python" ]
4
Python
kiteday/review-test
404aa1162fc6796c517894b932e547e67c2b9931
3307e1ec5df4d4a624d429b216d1119206f90cde
refs/heads/master
<repo_name>shahas1/stratagemofsagacity<file_sep>/SoS/Map.cs using System; using System.Collections.Generic; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; namespace SoS { public class Map { int width, height; Color backgroundColor = Color.Beige; Texture2D background; Rectangle spriteRect; int mapHeight, mapWidth; List<Obstacle> obs = new List<Obstacle>(); public Map(String _map, GraphicsDeviceManager _graphics, Texture2D wallSprite){ readMapFromFile(_map, _graphics, wallSprite); } public Map(int _width, int _height, Color _background) { width = _width; height = _height; backgroundColor = _background; } public Map(int _width, int _height, Texture2D _background) { width = _width; height = _height; background = _background; spriteRect = new Rectangle(0, 0, _background.Width, _background.Height); } public bool loadObstacles(List<Obstacle> obstacles) { obs.AddRange(obstacles); return true; } public void draw(SpriteBatch batch, Rectangle scope) { batch.GraphicsDevice.Clear(backgroundColor); if (background != null && scope.Intersects(new Rectangle(0,0,background.Width,background.Height))) { int picWidth = scope.Width, picHeight = scope.Height; if (picWidth > background.Width - scope.X) picWidth = background.Width - scope.X; if (picHeight > background.Height - scope.Y) picHeight = background.Height - scope.Y; batch.Draw(background, new Rectangle(0, 0, picWidth, picHeight), new Rectangle(scope.X,scope.Y, picWidth, picHeight), Color.White); } foreach (Obstacle o in obs) { if (o.getRectangle().Intersects(scope)) o.draw(batch, scope); } } public void drawMini(SpriteBatch batch, Rectangle scope, Rectangle mini) { if (background != null && scope.Intersects(new Rectangle(0, 0, background.Width, background.Height))) { int picWidth = scope.Width, picHeight = scope.Height; double factor = scope.Width / mini.Width; if (picWidth > background.Width - scope.X) picWidth = background.Width - scope.X; if (picHeight > background.Height - scope.Y) picHeight = background.Height - scope.Y; batch.Draw(background, new Rectangle(mini.X, mini.Y, (int)(picWidth/factor), (int)(picHeight/factor)), new Rectangle(scope.X, scope.Y, picWidth, picHeight), Color.White); } foreach (Obstacle o in obs) { if (o.getRectangle().Intersects(scope)) o.drawMini(batch,scope,mini); } } public int getWidth() { return width; } public int getHeight() { return height; } protected void readMapFromFile(String _map, GraphicsDeviceManager graphics, Texture2D wallSprite) { StreamReader sr = File.OpenText(_map); //Open the text file Console.Write(_map); String[,] map; mapWidth = Convert.ToInt32(sr.ReadLine()); //Get the height mapHeight = Convert.ToInt32(sr.ReadLine()); //Get the width height = mapHeight * 4; //Convert to height in pixels width = mapWidth * 4; //if (height < 450) // height = 450; //if (width < 450) // width = 450;//Convert to width in pixels //graphics.PreferredBackBufferHeight = height; //Change viewport height based on map file height //graphics.PreferredBackBufferWidth = width; //Change viewport width based on map file width map = new String[mapHeight, mapWidth]; //Initialize the 2d array of Strings for (int i = 0; i < mapHeight - 1; i++) //Go through the whole map file storing each individual //character as a string in "map" { String temp = sr.ReadLine(); Char[] tempArray = temp.ToCharArray(); for (int j = 0; j < mapWidth; j++) { map[i, j] = tempArray[j].ToString(); //Console.Write(map[i, j]); } //Console.WriteLine(" "); } sr.Close(); //Close connection to map file int currentX = 0; int currentY = 0; for (int i = 0; currentY < 300; i += wallSprite.Height) //Go through the map array and translate into the player //object and the array of GameObjects { for (int j = 0; currentX < 300; j += wallSprite.Width) { if (map[currentX, currentY].Equals("x")) obs.Add(new Wall(wallSprite, i, j, 1, 1)); currentX++; } currentX = 0; currentY++; } Console.WriteLine("Map Done"); } public List<Obstacle> getObs() { return obs; } public bool remove(Obstacle ob) { return obs.Remove(ob); } } } <file_sep>/SoS/Game2.cs using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Media; using GameStateManagement; namespace SoS { /// <summary> /// This is the main type for your game /// </summary> public class Game2 : Microsoft.Xna.Framework.Game { int time = 1800; // 30 seconds const int menuState = 0, pausedState = 1, playState = 2, optionsState = 3, introState =4; StateMachine stateMachine = new StateMachine(0); SpriteFont font; KeyboardState oldKeyState, newKeyState; GraphicsDeviceManager graphics; //Default graphics device SpriteBatch spriteBatch; //Sprite Batch for drawing graphics Texture2D BG; //Background int xOffset = 30; int yOffset = 40; String[] menuItems; int selected = 0; InputState input = new InputState(); Song hellRaider; public Game2() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 800; graphics.PreferredBackBufferHeight = 537; Content.RootDirectory = "Content"; hellRaider = Content.Load<Song>("hellRaider"); MediaPlayer.Play(hellRaider); } protected override void Initialize() { // TODO: Add your initialization logic here Window.Title = "Stratagem of Sagacity - v 0.1 Pre-Alpha"; base.Initialize(); } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); BG = Content.Load<Texture2D>("bg"); font = Content.Load<SpriteFont>("TimesNewRoman"); menuItems = new String[4]{"play", "options", "intro", "exit"}; } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); updateMenu(gameTime); base.Update(gameTime); } public void updateMenu(GameTime gameTime) { handleInput(input); } public void handleInput(InputState input) { oldKeyState = newKeyState; newKeyState = Keyboard.GetState(); if (oldKeyState.IsKeyUp(Keys.Down) && newKeyState.IsKeyDown(Keys.Down)) { if (selected < menuItems.Length) selected++; if (selected == menuItems.Length) selected = 0; //Console.WriteLine(selected); } else if (oldKeyState.IsKeyUp(Keys.Up) && newKeyState.IsKeyDown(Keys.Up)) { if (selected == 0) selected = menuItems.Length; if (selected > 0) selected--; //Console.WriteLine(selected); } if (oldKeyState.IsKeyUp(Keys.Enter) && newKeyState.IsKeyDown(Keys.Enter)) changePlayState(); if (oldKeyState.IsKeyUp(Keys.Escape) && newKeyState.IsKeyDown(Keys.Escape)) stateMachine.changeState(1); } public void changePlayState(){ switch(menuItems[selected]){ case "play": stateMachine.changeState(2); break; case "options": stateMachine.changeState(3); break; case "intro": stateMachine.changeState(4); break; case "exit": this.Exit(); break; } } protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(SpriteBlendMode.AlphaBlend); switch (stateMachine.getState()) { case menuState: drawMenu(gameTime); break; case playState: spriteBatch.Draw(BG, Vector2.Zero, Color.White); break; case pausedState: spriteBatch.Draw(BG, Vector2.Zero, Color.White); break; case introState: break; } spriteBatch.End(); base.Draw(gameTime); } public void drawMenu(GameTime gameTime) { spriteBatch.Draw(BG, Vector2.Zero, Color.White); String name = "<NAME>"; spriteBatch.DrawString(font, name, new Vector2(graphics.PreferredBackBufferWidth / 2 - font.MeasureString(name).X / 2, 0), Color.GreenYellow); for (int c = 0; c < menuItems.Length; c++) { if (selected == c) spriteBatch.DrawString(font, menuItems[c], new Vector2(xOffset, 100 + c * yOffset), Color.Yellow); else spriteBatch.DrawString(font, menuItems[c], new Vector2(xOffset, 100 + c * yOffset), Color.White); } } } } <file_sep>/SoS/BoxBeing.cs using System; using System.Collections.Generic; using System.Text; using SOS; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace SoS { class BoxBeing : Being { float xInit, yInit; int sideLength; public BoxBeing(float x, float y, Texture2D _pic,float _scale, int side) : base(x,y,_pic,_scale) { //defaults xInit = x; yInit = y; sideLength = side; } public override void UpdateMove(Microsoft.Xna.Framework.GameTime gameTime) { double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds; pos.X += (float)(xVel * elapsedTime); pos.Y += (float)(yVel * elapsedTime); if ((pos.X - xInit >= sideLength && xVel > 0) || ((pos.X - xInit <= 0) && (xVel < 0))) { if ((pos.X - xInit >= sideLength && xVel > 0)) { pos.Y += (pos.X - xInit) - sideLength; pos.X = xInit + sideLength; } else if ((pos.X - xInit <= 0) && (xVel < 0)) { pos.Y += pos.X - xInit; pos.X = xInit; } yVel = xVel; xVel = 0; } if ((pos.Y - yInit >= sideLength && yVel > 0) || ((pos.Y - yInit <= 0) && (yVel < 0))) { if (pos.Y - yInit >= sideLength && yVel > 0) { pos.X -= (pos.Y - yInit) - sideLength; pos.Y = yInit + sideLength; } else if ((pos.Y - yInit <= 0) && (yVel < 0)) { pos.X -= pos.Y - yInit; pos.Y = yInit; } xVel = -yVel; yVel = 0; } picRect.X = (int)pos.X; picRect.Y = (int)pos.Y; } public void setOrigPoint(Vector2 orig) { xInit = orig.X; yInit = orig.Y; } public override Being Predict(GameTime gameTime) { BoxBeing futureSelf = new BoxBeing(pos.X, pos.Y,pic,scale,sideLength); futureSelf.setVelocity(new Vector2(xVel, yVel)); futureSelf.setOrigPoint(new Vector2(xInit, yInit)); futureSelf.UpdateMove(gameTime); return (Being)futureSelf; } public override Matrix getMatrix() { return Matrix.CreateTranslation(new Vector3(pos, 0.0f)); } } } <file_sep>/SoS/Wall.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; /*Wall Class by <NAME> * * Class that represents a wall in the tank buster game */ namespace SoS { class Wall : Obstacle { int width, height;//all in units //Texture2D sprite; private bool visible = true; Color color = Color.White; bool showRect = false; public Wall(Texture2D _sprite,float _x, float _y) { pos.X = _x; pos.Y = _y; width = 1; height = 1; pic = _sprite; //there is sprite, so just sprite bounds picRect = new Rectangle((int)pos.X, (int)pos.Y, pic.Width, pic.Height); } public Wall(Texture2D _sprite, float _x, float _y, int _width, int _height) { pos.X = _x; pos.Y = _y; width = _width; height = _height; pic = _sprite; //more than 1 sprite in sequence, total bounds picRect = new Rectangle((int)pos.X, (int)pos.Y, pic.Width * width, pic.Height * height); } public bool isVisible() { return visible; } public void setVisible(bool visibility) { visible = visibility; } public void setColor(Color newColor) { color = newColor; } public override void draw(SpriteBatch batch,Rectangle scope) { if (!visible) return; int curX = (int)pos.X - scope.X, curY = (int)pos.Y - scope.Y; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Rectangle current = new Rectangle(curX, curY, pic.Width, pic.Height); batch.Draw(pic, current, color); curX += pic.Width; } curX = (int)pos.X - scope.X; curY += pic.Height; } if (showRect) { Rectangle rect = getBoundRect(); Rectangle rect2 = picRect; batch.Draw(pic, new Rectangle(rect.Left, rect.Top, rect.Width, 5), Color.Black); batch.Draw(pic, new Rectangle(rect.Left, rect.Bottom, rect.Width, 5), Color.Black); batch.Draw(pic, new Rectangle(rect.Left, rect.Top, 5, rect.Height), Color.Black); batch.Draw(pic, new Rectangle(rect.Right, rect.Top, 5, rect.Height), Color.Black); batch.Draw(pic, new Rectangle(rect2.Left, rect2.Top, rect2.Width, 5), Color.Red); batch.Draw(pic, new Rectangle(rect2.Left, rect2.Bottom, rect2.Width, 5), Color.Red); batch.Draw(pic, new Rectangle(rect2.Left, rect2.Top, 5, rect2.Height), Color.Red); batch.Draw(pic, new Rectangle(rect2.Right, rect2.Top, 5, rect2.Height), Color.Red); } /*top.X -= scope.X; top.Y -= scope.Y; bottom.X -= scope.X; bottom.Y -= scope.Y; left.X -= scope.X; left.Y -= scope.Y; right.X -= scope.X; right.Y -= scope.Y; batch.Draw(sprite, top, Color.Red); batch.Draw(sprite, bottom, Color.Red); batch.Draw(sprite, left, Color.Red); batch.Draw(sprite, right, Color.Red);*/ } public override void drawMini(SpriteBatch batch, Rectangle scope, Rectangle mini) { //Console.WriteLine("drawMini: " + width + " " + height); if (!visible) return; double factor = scope.Width / mini.Width; int curX = (int)pos.X - scope.X, curY = (int)pos.Y - scope.Y; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Rectangle current = new Rectangle((int)(mini.X + (curX / factor)), (int)(mini.Y + (curY / factor)), (int)(pic.Width / factor), (int)(pic.Height / factor)); batch.Draw(pic, current, color); curX += pic.Width; } curX = (int)pos.X - scope.X; curY += pic.Height; } } public override Rectangle getBoundRect() { return picRect; } public override bool collides(Collideable other) { int curX = (int)pos.X; int curY = (int)pos.Y; Rectangle tempRec = picRect; Vector2 tempPos = pos; bool collide = false; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { picRect = new Rectangle(curX, curY, pic.Width, pic.Height); pos = new Vector2((float)curX,(float)curY); collide = base.collides(other); if (collide) { picRect = tempRec; pos = tempPos; return true; } curX += pic.Width; } curX = (int)pos.X; curY += pic.Height; } picRect = tempRec; pos = tempPos; return collide; } } } <file_sep>/SoS/Being.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using SoS; namespace SOS { public class Being : Collideable { //protected Texture2D pic; //protected Vector2 pos; protected float xVel = .1f, yVel = 0f; protected bool canMoveUp = true, canMoveDown = true, canMoveLeft = true, canMoveRight = true; //protected float rotation; //in degrees protected Color color; protected float health; //protected float scale; protected int width, height; bool showRect = false; KeyboardState keyboard; public Being(float x, float y, Texture2D _pic,float _scale) { //defaults pic = _pic; pos = new Vector2(x, y); scale = _scale; width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); //prevPicRect = new Rectangle(x, y, 50, 50); ????? rotation = 0.0f; //velocity = 0; health = 1.0f; color = Color.White; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } public Being(Texture2D _pic, Rectangle rect, Color c) { pic = _pic; pos = new Vector2((float)rect.X, (float)rect.Y); rotation = 0.0f; width = rect.Width; height = rect.Height; scale = (((float)width/pic.Width) + ((float)height/pic.Height)) / 2.0f; //velocity = 0; health = 1.0f; color = c; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } public Being(Texture2D _pic, Rectangle _picRect, float _rotation,float _health, Color _color) { pic = _pic; pos = new Vector2((float)_picRect.X, (float)_picRect.Y); width = _picRect.Width; height = _picRect.Height; scale = (((float)width / pic.Width) + ((float)height / pic.Height)) / 2.0f; rotation = _rotation; // velocity = _velocity; health = _health; color = _color; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } public virtual void UpdateMove(GameTime gameTime) { double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds; if((xVel > 0 && canMoveRight) || (xVel < 0 && canMoveLeft)) pos.X += (float)(xVel * elapsedTime); if((yVel > 0 && canMoveDown) || (yVel < 0 && canMoveUp)) pos.Y += (float)(yVel * elapsedTime); if (pos.X <= 0) { pos.X += 2 * (0 - pos.X); xVel *= -1f; } if (pos.Y <= 0) { pos.Y += 2 * (0 - pos.Y); yVel *= -1f; } if (pos.X + pic.Width >= Game1.map.getWidth()) { pos.X -= 2 * (pos.X + picRect.Width - Game1.map.getWidth()); xVel *= -1f; } if (pos.Y + pic.Height >= Game1.map.getHeight()) { pos.Y -= 2 * (pos.Y + picRect.Height - Game1.map.getHeight()); yVel *= -1f; } canMoveUp = true; canMoveDown = true; canMoveLeft = true; canMoveRight = true; picRect.X = (int)pos.X; picRect.Y = (int)pos.Y; //????????????????????????????????????? /*if (gameTime.TotalGameTime.Seconds >= 2) { prevPicRect = picRect; } */ /*if (keyboard.IsKeyDown(Keys.Up)) { picRect.Y += velocity * elapsedTime; } if (keyboard.IsKeyDown(Keys.Down)) { picRect.Y -= velocity * elapsedTime; } if (keyboard.IsKeyDown(Keys.Left)) { picRect.X -= velocity * elapsedTime; } if (keyboard.IsKeyDown(Keys.Right)) { picRect.X += velocity * elapsedTime; } */ //????????????????????????????????????? /*if (keyboard.IsKeyUp(Keys.Up) && keyboard.IsKeyUp(Keys.Down) && keyboard.IsKeyUp(Keys.Left) && keyboard.IsKeyUp(Keys.Right)) { velocity /= 10; }*/ } public void setSprite(Texture2D newSprite) { pic = newSprite; } public virtual void Draw(Rectangle scope, SpriteBatch spriteBatch) { spriteBatch.Draw(pic, getPos(scope), null, color, rotation,origin,scale, SpriteEffects.None, 0f); if (showRect) { Rectangle rect = getBoundRect(); Rectangle rect2 = picRect; spriteBatch.Draw(pic, new Rectangle(rect.Left, rect.Top, rect.Width, 5), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect.Left, rect.Bottom, rect.Width, 5), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect.Left, rect.Top, 5, rect.Height), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect.Right, rect.Top, 5, rect.Height), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect2.Left, rect2.Top, rect2.Width, 5), Color.Red); spriteBatch.Draw(pic, new Rectangle(rect2.Left, rect2.Bottom, rect2.Width, 5), Color.Red); spriteBatch.Draw(pic, new Rectangle(rect2.Left, rect2.Top, 5, rect2.Height), Color.Red); spriteBatch.Draw(pic, new Rectangle(rect2.Right, rect2.Top, 5, rect2.Height), Color.Red); } //spriteBatch.Draw(pic, new Rectangle(picRect.X - scope.X, picRect.Y - scope.Y, pic.Width, pic.Height), Color.White); //spriteBatch.Draw(pic,new Rectangle(picRect.X - scope.X, picRect.Y - scope.Y, picRect.Width, picRect.Height), null, // color, rotation,new Vector2(pic.Width/2,pic.Height/2), SpriteEffects.None, 0f); } public virtual Being Predict(GameTime gameTime) { /* Rectangle _picRect = new Rectangle(picRect.X, picRect.Y, picRect.Width, picRect.Height); Being being = new Being(pic, picRect, rotation, velocity, health, color); int slope = (_picRect.Y - picRect.Y) / (_picRect.X - picRect.X); being.picRect.X += _picRect.X - picRect.X; being.picRect.Y += _picRect.Y - picRect.Y; picRect = new Rectangle(_picRect.X, _picRect.Y, _picRect.Width, _picRect.Height); return being; */ Being futureSelf = new Being(pos.X, pos.Y, pic,scale); futureSelf.setVelocity(new Vector2(xVel, yVel)); futureSelf.UpdateMove(gameTime); return futureSelf; } public virtual void drawMini(SpriteBatch batch, Rectangle scope, Rectangle mini) { double factor = scope.Width / mini.Width; //batch.Draw(pic, new Rectangle((int)(mini.X + ((picRect.X - scope.X) / factor)), (int)(mini.Y + ((picRect.Y - scope.Y) / factor)), (int)(picRect.Width / factor), (int)(picRect.Height / factor)), Color.White); // batch.Draw(pic, new Rectangle((int)(mini.X + ((picRect.X - scope.X) / factor)), (int)(mini.Y + ((picRect.Y - scope.Y) / factor)), (int)(picRect.Width / factor), (int)(picRect.Height / factor)), null, // color, rotation, new Vector2(pic.Width / 2, pic.Height / 2), SpriteEffects.None, 0f); batch.Draw(pic, new Vector2((float)(mini.X + ((pos.X - scope.X) / factor)),(float)( mini.Y + ((pos.Y - scope.Y) / factor))), null, color, rotation, new Vector2(pic.Width / 2, pic.Height / 2),(float)(scale/factor), SpriteEffects.None, 0f); } public override void collidedWith(Collideable other) { canMoveUp = false; canMoveDown = false; canMoveLeft = false; canMoveRight = false; //setVelocity(new Vector2(0, 0)); } public void setVelocity(Vector2 vel) { xVel = vel.X; yVel = vel.Y; } public Vector2 getVelocity() { return new Vector2(xVel, yVel); } public Vector2 getPos()//get actual point on Map { return pos; } public Vector2 getPos(Rectangle scope)//get point within scope { return new Vector2(pos.X - scope.X, pos.Y - scope.Y); } public void setMoveUp(bool b) { canMoveUp = b; } public void setMoveDown(bool b) { canMoveDown = b; } public void setMoveLeft(bool b) { canMoveLeft = b; } public void setMoveRight(bool b) { canMoveRight = b; } } } <file_sep>/SoS/StateMachine.cs using System; using System.Collections.Generic; using System.Text; namespace SoS { class StateMachine { int state, prevState; public StateMachine(int startingState) { state = startingState; prevState = startingState; } public void changeState(int newState) { prevState = state; state = newState; } public int getState() { return state; } public int getPrevState() { return prevState; } } } <file_sep>/SoS/Collideable.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace SoS { public abstract class Collideable : Object { protected Rectangle picRect; public abstract bool collides(Collideable other); public abstract void collidedWith(Collideable other); public virtual Rectangle getRectangle() { return picRect; } public Point getQuad(Collideable o) { Point pos = new Point(o.getRectangle().X, o.getRectangle().Y); int numQuads = 100; return new Point(pos.X/100, pos.Y/100); } } } <file_sep>/SoS/Player.cs using System; using System.Collections.Generic; using System.Text; using SOS; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SoS { class Player : Being { float speed = .2f; Game1 game; bool isMouseDown; List<List<Texture2D>> playerMovement; Point playerMovementState = new Point(0, 0); public Player(float x,float y, Texture2D _pic,float _scale,Game1 _game) : base(x,y,_pic,_scale) { xVel = 0f; yVel = 0f; game = _game; isMouseDown = false; } public Player(Texture2D _pic, Rectangle rect, Color c, Game1 _game) : base(_pic, rect, c) { xVel = 0f; yVel = 0f; game = _game; isMouseDown = false; } public Player(Texture2D _pic, Rectangle _picRect, float _rotation, float _health, Color _color, Game1 _game) : base(_pic,_picRect,_rotation,_health,_color) { xVel = 0f; yVel = 0f; game = _game; isMouseDown = false; } public void loadMovementList(List<List<Texture2D>> pm) { playerMovement = pm; } public override void UpdateMove(GameTime gameTime) { double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds; //MouseState mouse = Mouse.GetState(); //rotation = -(float)Math.Atan2((((picRect.X + (picRect.Width / 2))) - mouse.X) * (Math.PI / 180), (((picRect.Y + (picRect.Height / 2))) - mouse.Y) * (Math.PI / 180)); KeyboardState keyState = Keyboard.GetState(); MouseState mouse = Mouse.GetState(); float mX, mY, pX, pY; mX = mouse.X; mY = mouse.Y; pX = pos.X - game.getCamera().X; pY = pos.Y - game.getCamera().Y; rotation = -(float)Math.Atan2((double)(pX - mX),(double)(pY -mY)); xVel = 0f; yVel = 0f; if (keyState.IsKeyDown(Keys.W) && canMoveUp) { yVel = -speed; if (playerMovement != null) { playerMovementState.X = 1; playerMovementState.Y++; if (playerMovementState.Y >= playerMovement[playerMovementState.X].Count) { playerMovementState.Y = 0; } setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); picRect = new Rectangle((int)pos.X, (int)pos.Y, (int)width, (int)height); } } if (keyState.IsKeyDown(Keys.S) && canMoveDown) { yVel = speed; if (playerMovement != null) { playerMovementState.X = 1; playerMovementState.Y++; if (playerMovementState.Y >= playerMovement[playerMovementState.X].Count) { playerMovementState.Y = 0; } setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); } } if (keyState.IsKeyDown(Keys.A) && canMoveLeft) { xVel = -speed; if (playerMovement != null) { playerMovementState.X = 1; playerMovementState.Y++; if (playerMovementState.Y >= playerMovement[playerMovementState.X].Count) { playerMovementState.Y = 0; } setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); } } if (keyState.IsKeyDown(Keys.D) && canMoveRight) { xVel = speed; //if (playerMovement != null) //{ playerMovementState.X = 1; playerMovementState.Y++; if (playerMovementState.Y >= playerMovement[playerMovementState.X].Count) { playerMovementState.Y = 0; } setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); //} } if (keyState.IsKeyUp(Keys.W) && keyState.IsKeyUp(Keys.A) && keyState.IsKeyUp(Keys.S) && keyState.IsKeyUp(Keys.D)) { playerMovementState.X = 0; playerMovementState.Y = 0; //setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); //picRect = new Rectangle(picRect.X, picRect.Y, pic.Width / 2, pic.Height / 2); } if (mouse.LeftButton == ButtonState.Pressed) { if (!isMouseDown) { float shotX = pos.X + (float)((width + 20) * Math.Sin(rotation)); float shotY = pos.Y + (float)((height + 20)* -Math.Cos(rotation)); Projectile shot = new Projectile(shotX,shotY,"pShot", .3f,21,21,game); shot.setRotation(rotation); game.addProjectile(shot); //Graphics if (playerMovement != null) { playerMovementState.X = 2; playerMovementState.Y++; if (playerMovementState.Y >= playerMovement[playerMovementState.X].Count) { playerMovementState.Y = 0; } setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); } game.playGunfire(); isMouseDown = true; } } if (mouse.LeftButton == ButtonState.Released) { isMouseDown = false; playerMovementState.X = 0; playerMovementState.Y = 0; setSprite(playerMovement[playerMovementState.X][playerMovementState.Y]); width = (int)(pic.Width * scale); height = (int)(pic.Height * scale); picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); } pos.X += (float)(xVel * elapsedTime); pos.Y += (float)(yVel * elapsedTime); if (pos.X <= 0) { pos.X = 0; } if (pos.Y <= 0) { pos.Y = 0; } if (pos.X + width >= Game1.map.getWidth()) { pos.X = Game1.map.getWidth() - width; } if (pos.Y + height >= Game1.map.getHeight()) { pos.Y = Game1.map.getHeight() - height; } picRect.X = (int)pos.X; picRect.Y = (int)pos.Y; canMoveUp = true; canMoveDown = true; canMoveLeft = true; canMoveRight = true; } public override Being Predict(GameTime gameTime) { Player futureSelf = new Player(pic, picRect, color,game); futureSelf.setVelocity(new Vector2(xVel, yVel)); futureSelf.setRotation(rotation); return (Being)futureSelf; } public float getSpeed() { return speed; } public override void collidedWith(Collideable other) { } } } <file_sep>/SoS/Character.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; namespace SOS { class Character : Being { public Character() { Content.RootDirectory = "Content"; pic = Content.Load<Texture2D>("WizardSquare"); picRect = new Rectangle(0, 0, 50, 50); } public void Draw(SpriteBatch spriteBatch) { spriteBatch.Draw(pic, picRect, Color.Chocolate); } } } <file_sep>/SoS/Game1.cs using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using SOS; using GameStateManagement; using Microsoft.Xna.Framework.Media; namespace SoS { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public static Map map; MouseState mouseState; Texture2D wallSprite, background, mouseSprite, enemySprite, playerSprite; Rectangle camera = new Rectangle(0,0, WIDTH, HEIGHT); int xCamBuffer = 100, yCamBuffer = 100; //cameraSpeed = 1; const int future = 2000; public static Texture2D pixel; public static int WIDTH = 800, HEIGHT = 537; int miniNum = 3; Player player; //Movement List<List<Texture2D>> playerMovement = new List<List<Texture2D>>(); List<Being> beings = new List<Being>(); List<Projectile> projectiles = new List<Projectile>(); //Menu stuff int time = 1800; // 30 seconds const int menuState = 0, pausedState = 1, playState = 2, optionsState = 3, introState = 4, controlsState = 5; StateMachine stateMachine = new StateMachine(0); bool pauseHeld = false; SpriteFont font; KeyboardState oldKeyState, newKeyState; Texture2D BG; //Background int xOffset = 30; int yOffset = 40; String[] menuItems, optionsMenuItems; int selected = 0; InputState input = new InputState(); //SoundEffect hellRaider; Song hellRaider, gunfireSound; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = WIDTH; graphics.PreferredBackBufferHeight = HEIGHT; hellRaider = Content.Load<Song>("Final-calpomat-4566_hifi"); MediaPlayer.Play(hellRaider); //hellRaider.Play(); gunfireSound = Content.Load<Song>("3-burst-Diode111-8773_hifi"); } public void playGunfire() { MediaPlayer.Play(gunfireSound); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here Window.Title = "Stratagem of Sagacity - v 0.1 Pre-Alpha"; base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); wallSprite = Content.Load<Texture2D>("box"); pixel = Content.Load<Texture2D>("blankPixel"); background = Content.Load<Texture2D>("floor"); mouseSprite = Content.Load<Texture2D>("crosshair"); enemySprite = Content.Load<Texture2D>("Enemy/standing"); playerSprite = Content.Load<Texture2D>("Player/standing"); map = new Map("F:/XNA/Sos2/trunk/SoS/Content/map.txt", graphics, wallSprite); List<Obstacle> walls = new List<Obstacle>(); //walls.Add(new Wall(wallSprite, 10, 10, 2, 5)); //walls.Add(new Wall(wallSprite, 100, 300, 10, 1)); //walls.Add(new Wall(wallSprite, 1000, 100, 3, 3)); //walls.Add(new Wall(wallSprite, 100, 700, 1, 1)); map.loadObstacles(walls); player = new Player(playerSprite, new Rectangle(100,100,playerSprite.Width/2,playerSprite.Height/2),Color.White, this); beings.Add(new Being(100, 10, enemySprite)); beings.Add(new BoxBeing(950, 60, enemySprite, 200)); beings.Add(player); //Movement //0=standing; 1=walking; 2=shooting; 3=dead playerMovement.Add(new List<Texture2D> {Content.Load<Texture2D>("Player/standing")}); playerMovement.Add(new List<Texture2D> {Content.Load<Texture2D>("Player/frame 2_walking"), Content.Load<Texture2D>("Player/frame 1 and 3_walking"), Content.Load<Texture2D>("Player/frame 4_walking")}); playerMovement.Add(new List<Texture2D> {Content.Load<Texture2D>("Player/aiming"), Content.Load<Texture2D>("Player/frame 2_firing"), Content.Load<Texture2D>("Player/firing gunfire 1"), Content.Load<Texture2D>("Player/firing gunfire 2"), Content.Load<Texture2D>("Player/frame 2_firing"), Content.Load<Texture2D>("Player/frame 1 and 3_firing"), Content.Load<Texture2D>("Player/aiming")}); playerMovement.Add(new List<Texture2D> {Content.Load<Texture2D>("Player/dead")}); player.loadMovementList(playerMovement); //Menu Stuff spriteBatch = new SpriteBatch(GraphicsDevice); BG = Content.Load<Texture2D>("bg"); font = Content.Load<SpriteFont>("TimesNewRoman"); menuItems = new String[4] { "play", "options", "intro", "exit" }; optionsMenuItems = new String[2] { "controls", "back" }; // TODO: use this.Content to load your game content here } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if (Keyboard.GetState().IsKeyDown(Keys.Escape)) { if (stateMachine.getState() != pausedState && !pauseHeld && stateMachine.getState() != menuState) stateMachine.changeState(pausedState); else if (stateMachine.getState() == pausedState && !pauseHeld) stateMachine.changeState(stateMachine.getPrevState()); pauseHeld = true; /*if (stateMachine.getState() != pausedState && stateMachine.getPrevState() != pausedState) stateMachine.changeState(pausedState); if stateMachine.changeState(playState);*/ } else pauseHeld = false; if (stateMachine.getState() == playState) { int elapsedTime = (int)gameTime.ElapsedGameTime.TotalMilliseconds; foreach (Being b in beings) { b.UpdateMove(gameTime); } foreach (Projectile p in projectiles) { p.UpdateMove(gameTime); } mouseState = Mouse.GetState(); if (player.getPoint(camera).X < xCamBuffer) camera.X -= (int)(player.getSpeed() * elapsedTime); // xCamBuffer - mouseState.X; if (player.getPoint(camera).X > WIDTH - xCamBuffer) camera.X += (int)(player.getSpeed() * elapsedTime); // mouseState.X - (WIDTH - xCamBuffer); if (player.getPoint(camera).Y < yCamBuffer) camera.Y -= (int)(player.getSpeed() * elapsedTime); //yCamBuffer - mouseState.Y; if (player.getPoint(camera).Y > HEIGHT - yCamBuffer) camera.Y += (int)(player.getSpeed() * elapsedTime); // mouseState.Y - (HEIGHT - yCamBuffer); if (camera.X < 0) camera.X = 0; if (camera.X + WIDTH > map.getWidth()) camera.X = map.getWidth() - WIDTH; if (camera.Y < 0) camera.Y = 0; if (camera.Y + HEIGHT > map.getHeight()) camera.Y = map.getHeight() - HEIGHT; // TODO: Add your update logic here checkCollisions(); } else if (stateMachine.getState() == menuState) { updateMenu(gameTime); } else if (stateMachine.getState() == optionsState) { updateOptionsMenu(gameTime); } else if (stateMachine.getState() == controlsState) { updateControlsMenu(gameTime); } base.Update(gameTime); } public void checkCollisions() { //put everything on screen in one list List<Collideable> all = addAll(); for (int i = 0; i < all.Count; i++) { for (int j = i + 1; j < all.Count; j++) { Collideable me = all[i]; Collideable him = all[j]; //Console.WriteLine("Him: " + him.ToString() + " Me: " + me.ToString()); //if (me.getQuad(me).Equals(him.getQuad(him))) //{ //if (me.collides(him)) //{ // him.collidedWith(me); //me.collidedWith(him); //} //} } } } private List<Collideable> addAll() { List<Collideable> all = new List<Collideable>(); foreach (Being b in beings) { all.Add(b); } foreach (Projectile p in projectiles) { all.Add(p); } foreach (Obstacle o in map.getObs()) { all.Add(o); } return all; } public void updateControlsMenu(GameTime gameTime) { oldKeyState = newKeyState; newKeyState = Keyboard.GetState(); if (oldKeyState.IsKeyUp(Keys.Down) && newKeyState.IsKeyDown(Keys.Down)) { if (selected < optionsMenuItems.Length) selected++; if (selected == optionsMenuItems.Length) selected = 0; Console.WriteLine(selected); } else if (oldKeyState.IsKeyUp(Keys.Up) && newKeyState.IsKeyDown(Keys.Up)) { if (selected == 0) selected = optionsMenuItems.Length; if (selected > 0) selected--; Console.WriteLine(selected); } if (oldKeyState.IsKeyUp(Keys.Enter) && newKeyState.IsKeyDown(Keys.Enter)) changePlayState(); } public void updateOptionsMenu(GameTime gameTime) { oldKeyState = newKeyState; newKeyState = Keyboard.GetState(); if (oldKeyState.IsKeyUp(Keys.Down) && newKeyState.IsKeyDown(Keys.Down)) { if (selected < optionsMenuItems.Length) selected++; if (selected == optionsMenuItems.Length) selected = 0; Console.WriteLine(selected); } else if (oldKeyState.IsKeyUp(Keys.Up) && newKeyState.IsKeyDown(Keys.Up)) { if (selected == 0) selected = optionsMenuItems.Length; if (selected > 0) selected--; Console.WriteLine(selected); } if (oldKeyState.IsKeyUp(Keys.Enter) && newKeyState.IsKeyDown(Keys.Enter)) changeOptionsState(); } public void updateMenu(GameTime gameTime) { oldKeyState = newKeyState; newKeyState = Keyboard.GetState(); if (oldKeyState.IsKeyUp(Keys.Down) && newKeyState.IsKeyDown(Keys.Down)) { if (selected < menuItems.Length) selected++; if (selected == menuItems.Length) selected = 0; Console.WriteLine(selected); } else if (oldKeyState.IsKeyUp(Keys.Up) && newKeyState.IsKeyDown(Keys.Up)) { if (selected == 0) selected = menuItems.Length; if (selected > 0) selected--; Console.WriteLine(selected); } if (oldKeyState.IsKeyUp(Keys.Enter) && newKeyState.IsKeyDown(Keys.Enter)) changePlayState(); } public void changePlayState() { switch (menuItems[selected]) { case "play": stateMachine.changeState(2); break; case "options": stateMachine.changeState(3); break; case "intro": stateMachine.changeState(4); break; case "exit": this.Exit(); break; } } public void changeOptionsState() { switch (optionsMenuItems[selected]) { case "controls": stateMachine.changeState(5); break; case "back": stateMachine.changeState(0); break; } } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { //graphics.GraphicsDevice.Clear(Color.CornflowerBlue); if (stateMachine.getState() == menuState) { graphics.GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(SpriteBlendMode.AlphaBlend); switch (stateMachine.getState()) { case menuState: drawMenu(gameTime); break; case playState: spriteBatch.Draw(BG, Vector2.Zero, Color.White); MediaPlayer.Stop(); break; case pausedState: spriteBatch.Draw(BG, Vector2.Zero, Color.White); break; case introState: break; } spriteBatch.End(); } else if (stateMachine.getState() == optionsState) { graphics.GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(SpriteBlendMode.AlphaBlend); switch (stateMachine.getState()) { case controlsState: drawOptionsMenu(gameTime); break; } spriteBatch.End(); } else if (stateMachine.getState() == playState) { Rectangle miniMap = new Rectangle((int)(WIDTH - (WIDTH / miniNum)), (int)(HEIGHT - (HEIGHT / miniNum)), (int)(WIDTH / miniNum), (int)(HEIGHT / miniNum)); spriteBatch.Begin(); map.draw(spriteBatch, camera); foreach (Being b in beings) { b.Draw(camera, spriteBatch); } foreach (Projectile p in projectiles) { p.Draw(camera, spriteBatch); } spriteBatch.Draw(mouseSprite, new Rectangle(mouseState.X - 5, mouseState.Y - 5, 10, 10), Color.White); //After everything else is drawn //Draw mini map map.drawMini(spriteBatch, camera, miniMap); for (int i = miniMap.X; i < miniMap.X + miniMap.Width; i++) { spriteBatch.Draw(pixel, new Rectangle(i, miniMap.Y, 1, 1), Color.Black); } for (int i = miniMap.Y; i < miniMap.Y + miniMap.Height; i++) { spriteBatch.Draw(pixel, new Rectangle(miniMap.X, i, 1, 1), Color.Black); } GameTime futureTime = new GameTime(new TimeSpan(0, 0, 0, 0, future), new TimeSpan(0, 0, 0, 0, future), new TimeSpan(0, 0, 0, 0, future), new TimeSpan(0, 0, 0, 0, future)); foreach (Being b in beings) { Being fB = b.Predict(futureTime); if (fB.getRectangle().Intersects(camera)) { fB.drawMini(spriteBatch, camera, miniMap); } } foreach (Projectile p in projectiles) { Projectile fP = p.Predict(futureTime); if (fP.intersects(camera)) { fP.drawMini(spriteBatch, camera, miniMap); } } spriteBatch.End(); } if (stateMachine.getState() == pausedState) { String message = "PAUSED"; Vector2 mSize = font.MeasureString(message); spriteBatch.Begin(); spriteBatch.DrawString(font,message,new Vector2((WIDTH/2f)-mSize.X,(HEIGHT/2f)-mSize.Y),Color.White); spriteBatch.End(); } // TODO: Add your drawing code here base.Draw(gameTime); } public void drawOptionsMenu(GameTime gameTime) { spriteBatch.Draw(BG, Vector2.Zero, Color.White); String name = "<NAME>"; spriteBatch.DrawString(font, name, new Vector2(graphics.PreferredBackBufferWidth / 2 - font.MeasureString(name).X / 2, 0), Color.GreenYellow); for (int c = 0; c < optionsMenuItems.Length; c++) { if (selected == c) spriteBatch.DrawString(font, optionsMenuItems[c], new Vector2(xOffset, 100 + c * yOffset), Color.Yellow); else spriteBatch.DrawString(font, optionsMenuItems[c], new Vector2(xOffset, 100 + c * yOffset), Color.White); } } public void drawMenu(GameTime gameTime) { spriteBatch.Draw(BG, Vector2.Zero, Color.White); String name = "<NAME>"; spriteBatch.DrawString(font, name, new Vector2(graphics.PreferredBackBufferWidth / 2 - font.MeasureString(name).X / 2, 0), Color.GreenYellow); for (int c = 0; c < menuItems.Length; c++) { if (selected == c) spriteBatch.DrawString(font, menuItems[c], new Vector2(xOffset, 100 + c * yOffset), Color.Yellow); else spriteBatch.DrawString(font, menuItems[c], new Vector2(xOffset, 100 + c * yOffset), Color.White); } } public bool remove(Collideable other) { if (other is Being) { return beings.Remove((Being)other); } else if(other is Projectile) { return projectiles.Remove((Projectile)other); } else if (other is Obstacle) { return map.remove((Obstacle)other); } return false; } public void addProjectile(Projectile p) { p.setPic(Content.Load<Texture2D>(p.getPicName())); projectiles.Add(p); } public Rectangle getCamera() { return camera; } } } <file_sep>/SoS/Enemy.cs using System; using System.Collections.Generic; using System.Text; namespace SOS { class Enemy : Being { } } <file_sep>/SoS/Obstacle.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using SOS; namespace SoS { public abstract class Obstacle : Collideable { //Texture2D sprite; int x, y; Color miniColor = Color.Black; protected Rectangle top, bottom, left, right; protected int size = 5; public Obstacle() { } public Obstacle(Texture2D _pic,int _x, int _y) { x = _x; y = _y; pic = _pic; rotation = 0f; pos = new Vector2((float)x, (float)y); origin = new Vector2(0f,0f); } public virtual void draw(SpriteBatch batch, Rectangle scope) { batch.Draw(pic, new Rectangle(x-scope.X, y-scope.Y, pic.Width, pic.Height), Color.White); } public virtual void drawMini(SpriteBatch batch, Rectangle scope, Rectangle mini) { double factor = scope.Width / mini.Width; batch.Draw(pic, new Rectangle((int)(mini.X + ((x - scope.X) / factor)), (int)(mini.Y + ((y - scope.Y) / factor)), (int)(pic.Width / factor), (int)(pic.Height / factor)), Color.White); } public override void collidedWith(Collideable other) { if (other is Being) { Being b = (Being)other; //Rectangle top, bottom, left, right; //int size = 5; //top = new Rectangle(picRect.X, picRect.Y, picRect.Width, size); //bottom = new Rectangle(picRect.X, picRect.Y + picRect.Height - size, picRect.Width, size); //left = new Rectangle(picRect.X, picRect.Y, size, picRect.Height); //right = new Rectangle(picRect.X + picRect.Width - size, picRect.Y, size, picRect.Height); /*if(other.getBoundRect().Intersects(top)) b.setMoveDown(false); if (other.getBoundRect().Intersects(bottom)) b.setMoveUp(false); if (other.getBoundRect().Intersects(left)) b.setMoveRight(false); if (other.getBoundRect().Intersects(right)) b.setMoveLeft(false);*/ if (b.getVelocity().Y > 0) { b.setMoveDown(false); // b.set } } } } } <file_sep>/SoS/Projectile.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace SoS { public class Projectile : Collideable { //protected Texture2D pic; protected string picName; //Rectangle prevPicRect;???????? protected float speed; //protected float rotation; //in degrees protected Color color; protected float power; protected Game1 game; bool showRect = false; //protected Vector2 pos; //protected float scale; protected int width, height; public Projectile(float x, float y, Texture2D _pic, float _speed, Game1 _game) { //defaults pic = _pic; pos = new Vector2(x, y); scale = 1; picRect = new Rectangle((int)x,(int) y, pic.Width, pic.Height); //prevPicRect = new Rectangle(x, y, 50, 50); ????? rotation = 0.0f; speed = _speed; power = 1.0f; color = Color.White; game = _game; origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } public Projectile(Texture2D _pic, Rectangle rect, float _speed, Color c, Game1 _game) { pic = _pic; pos = new Vector2((float)rect.X, (float)rect.Y); width = rect.Width; height = rect.Height; scale = (((float)width / pic.Width) + ((float)height / pic.Height)) / 2.0f; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); rotation = 0.0f; speed = _speed; power = 1.0f; color = c; game = _game; origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } public Projectile(Texture2D _pic, Rectangle _picRect, float _rotation, int _velocity, float _power, float _speed, Color _color, Game1 _game) { pic = _pic; pos = new Vector2((float)_picRect.X, (float)_picRect.Y); width = _picRect.Width; height = _picRect.Height; scale = (((float)width / pic.Width) + ((float)height / pic.Height)) / 2.0f; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); rotation = _rotation; speed = _speed; power = _power; color = _color; game = _game; origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } public Projectile(string name, Rectangle rect, float _speed, Color c, Game1 _game) { picName = name; pos = new Vector2((float)rect.X, (float)rect.Y); scale = 1f; width = rect.Width; height = rect.Height; picRect = rect; rotation = 0.0f; speed = _speed; power = 1.0f; color = c; game = _game; origin = new Vector2(width / 2f, height / 2f); } public Projectile(float x, float y, string name, float _speed,int _width, int _height, Game1 _game) { picName = name; pic = null; pos = new Vector2(x, y); width = _width; height = _height; scale = 1f; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); rotation = 0.0f; speed = _speed; power = 1.0f; color = Color.White; game = _game; origin = new Vector2(width / 2f, height / 2f); } public Projectile(string name, Rectangle _picRect, float _rotation, int _velocity, float _power, Color _color) { picName = name; pic = null; pos = new Vector2((float)_picRect.X, (float)_picRect.Y); width = _picRect.Width; height = _picRect.Height; scale = 1f; picRect = _picRect; //prevPicRect = _picRect;?????? rotation = _rotation; //speed = _speed; power = _power; color = _color; origin = new Vector2(width / 2f, height / 2f); } public virtual void UpdateMove(GameTime gameTime) { double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds; pos.X += (float)(speed * Math.Sin(rotation ) * elapsedTime); pos.Y += (float)(speed * -Math.Cos(rotation ) * elapsedTime); picRect.X = (int)pos.X; picRect.Y = (int)pos.Y; } public virtual void Draw(Rectangle scope, SpriteBatch spriteBatch) { //spriteBatch.Draw(pic, new Rectangle(picRect.X - scope.X, picRect.Y - scope.Y, picRect.Width, picRect.Height), null, // color, rotation, new Vector2(pic.Width / 2, pic.Height / 2), SpriteEffects.None, 0f); spriteBatch.Draw(pic, new Vector2(pos.X - scope.X, pos.Y - scope.Y), null, color, rotation, origin, scale,SpriteEffects.None, 0f); if (showRect) { Rectangle rect = getBoundRect(); Rectangle rect2 = picRect; spriteBatch.Draw(pic, new Rectangle(rect.Left, rect.Top, rect.Width, 5), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect.Left, rect.Bottom, rect.Width, 5), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect.Left, rect.Top, 5, rect.Height), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect.Right, rect.Top, 5, rect.Height), Color.Black); spriteBatch.Draw(pic, new Rectangle(rect2.Left, rect2.Top, rect2.Width, 5), Color.Red); spriteBatch.Draw(pic, new Rectangle(rect2.Left, rect2.Bottom, rect2.Width, 5), Color.Red); spriteBatch.Draw(pic, new Rectangle(rect2.Left, rect2.Top, 5, rect2.Height), Color.Red); spriteBatch.Draw(pic, new Rectangle(rect2.Right, rect2.Top, 5, rect2.Height), Color.Red); } } public virtual Projectile Predict(GameTime gameTime) { Projectile futureSelf = new Projectile(pos.X, pos.Y, pic,speed, game); futureSelf.setRotation(rotation); futureSelf.UpdateMove(gameTime); return futureSelf; } public virtual void drawMini(SpriteBatch batch, Rectangle scope, Rectangle mini) { float factor = scope.Width / mini.Width; //batch.Draw(pic, new Rectangle((int)(mini.X + ((picRect.X - scope.X) / factor)), (int)(mini.Y + ((picRect.Y - scope.Y) / factor)), (int)(picRect.Width / factor), (int)(picRect.Height / factor)), Color.White); //batch.Draw(pic, new Rectangle((int)(mini.X + ((picRect.X - scope.X) / factor)), (int)(mini.Y + ((picRect.Y - scope.Y) / factor)), (int)(picRect.Width / factor), (int)(picRect.Height / factor)), null, // color, rotation, new Vector2(pic.Width / 2, pic.Height / 2), SpriteEffects.None, 0f); batch.Draw(pic, new Vector2(mini.X + ((pos.X - scope.X) / factor), mini.Y + ((pos.Y - scope.Y) / factor)), null, color, rotation, origin,1f/factor, SpriteEffects.None, 0f); } public override void collidedWith(Collideable other) { game.remove(other); game.remove(this); } public string getPicName() { return picName; } public void setPic(Texture2D _pic) { pic = _pic; scale = (((float)width / pic.Width) + ((float)height / pic.Height)) / 2.0f; picRect = new Rectangle((int)pos.X, (int)pos.Y, width, height); origin = new Vector2(pic.Width / 2f, pic.Height / 2f); } } }
ef4e228b6ae3373b2c0c2c7cc4d6ea738c514b89
[ "C#" ]
13
C#
shahas1/stratagemofsagacity
f2035f94faa648c873f0869b0992205426dbcb0f
8b9175c0e4334d9c3bac122ec69af1628f5b067d
refs/heads/master
<repo_name>kaheglar/knockout-binding-label<file_sep>/lib/main.spec.js 'use strict'; define([ './main' ], function(ko) { describe('Module knockout-binding-control', function () { it('initialised the correct property bindings on the element.', function () { var viewModel = { id: ko.observable('1'), label: ko.observable('Forename') } document.body.innerHTML = '<label data-bind="label: $data">' ko.applyBindings(viewModel) var label = document.querySelector('label') expect(label.getAttribute('for')).toEqual('1-control') expect(label.innerHTML).toEqual('Forename') }) }) }) <file_sep>/README.md [![Build Status](https://secure.travis-ci.org/kaheglar/knockout-binding-label.png)](https://travis-ci.org/kaheglar/knockout-binding-label) # knockout-binding-label Knockout binding for <label> element. ## Installation bower i knockout-binding-label=kaheglar/knockout-binding-label --save ## License MIT <file_sep>/lib/main.js 'use strict'; require.config({ paths: { knockout: '../bower_components/knockout.js/knockout.debug' } }) define([ 'knockout' ], function (ko) { // define ko binding ko.bindingHandlers.label = { init: function(element, valueAccessor) { var model = ko.utils.unwrapObservable(valueAccessor()) ko.applyBindingsToNode(element, { text: model.label, attr:{ for: ko.computed(function () { return ko.utils.unwrapObservable(model.id) + '-control' }) } }) // tell ko not to bind decendents otherwise they will be bound twice return { controlsDescendantBindings: true } } } // export return ko })
6aa7fc64202743e858eb54862925738911cbaa76
[ "JavaScript", "Markdown" ]
3
JavaScript
kaheglar/knockout-binding-label
6a7a29a1d9462b982a8097445042c2d46810e9e5
e8faa474c854ce261a092d9bb06e4ac8dfff22f7
refs/heads/master
<file_sep>using System.Text.RegularExpressions; using Jabbot.Models; using Jabbot.Sprockets.Core; namespace Jabbot.Sprockets { public abstract class RegexSprocket : ISprocket { public abstract Regex Pattern { get; } public bool Handle(ChatMessage message, IBot bot) { if (Pattern == null) { return false; } Match match; if (!(match = Pattern.Match(message.Content)).Success) { return false; } ProcessMatch(match, message, bot); return true; } protected abstract void ProcessMatch(Match match, ChatMessage message, IBot bot); } } <file_sep>using System; using System.ComponentModel.Composition; namespace Jabbot.Sprockets.Core { /// <summary> /// Announcements are tasks that occur periodically, and can manipulate an active Bot /// </summary> [InheritedExport] public interface IAnnounce { TimeSpan Interval { get; } void Execute(Bot bot); } } <file_sep>using System.ComponentModel.Composition;  namespace Jabbot.Sprockets.Core { [InheritedExport] public interface ISprocketInitializer { void Initialize(Bot bot); } } <file_sep>using System; using Jabbot; namespace JabbrConsoleTest { class Program { const string ServerUrl = "http://jabbr.net"; const string RoomName = "Code52-testing-tw"; static void Main() { Console.WriteLine("Connecting to {0}...", ServerUrl); var bot = new Bot(ServerUrl, "cyberzed-jibbr", "<PASSWORD>"); bot.PowerUp(); if (!TryCreateRoomIfNotExists(RoomName, bot)) { Console.Write("Could not create room {0}. Exiting..."); bot.ShutDown(); return; } bot.Say("Hello world!", RoomName); Console.Write("Press any key to quit..."); Console.ReadKey(); bot.ShutDown(); } private static bool TryCreateRoomIfNotExists(string roomName, Bot bot) { try { bot.CreateRoom(roomName); } catch (AggregateException e) { if (!e.GetBaseException().Message.Equals(string.Format("The room '{0}' already exists", roomName), StringComparison.OrdinalIgnoreCase)) { return false; } } return true; } } } <file_sep>using System.ComponentModel.Composition; namespace Jabbot { [InheritedExport] public interface ILogger { void WriteMessage(string message); void Write(string format, params object[] parameters); } } <file_sep>using System; using System.Collections.Generic; using System.Net; using Jabbot.Models; using Jabbot.Sprockets.Core; namespace Jabbot { public interface IBot { string Name { get; } ICredentials Credentials { get; set; } /// <summary> /// List of rooms the bot is in. /// </summary> IEnumerable<string> Rooms { get; } event Action Disconnected; event Action<ChatMessage> MessageReceived; /// <summary> /// Add a sprocket to the bot instance /// </summary> void AddSprocket(ISprocket sprocket); /// <summary> /// Remove a sprocket from the bot instance /// </summary> void RemoveSprocket(ISprocket sprocket); /// <summary> /// Add a sprocket to the bot instance /// </summary> void AddUnhandledMessageSprocket(IUnhandledMessageSprocket sprocket); /// <summary> /// Remove a sprocket from the bot instance /// </summary> void RemoveUnhandledMessageSprocket(IUnhandledMessageSprocket sprocket); /// <summary> /// Remove all sprockets /// </summary> void ClearSprockets(); /// <summary> /// Connects to the chat session /// </summary> void PowerUp(IEnumerable<ISprocketInitializer> sprocketInitializers = null); /// <summary> /// Creates a new room /// </summary> /// <param name="room">room to create</param> void CreateRoom(string room); /// <summary> /// Joins a chat room. Changes this to the active room for future messages. /// </summary> void Join(string room); /// <summary> /// Leaves a chat room. /// </summary> void Leave(string room); /// <summary> /// Sets the Bot's gravatar email /// </summary> /// <param name="gravatarEmail"></param> void Gravatar(string gravatarEmail); /// <summary> /// Say something to the active room. /// </summary> /// <param name="what">what to say</param> /// <param name="room">the room to say it to</param> void Say(string what, string room); /// <summary> /// Reply to someone /// </summary> /// <param name="who">the person you want the bot to reply to</param> /// <param name="what">what you want the bot to say</param> /// <param name="room">the room to say it to</param> void Reply(string who, string what, string room); void PrivateReply(string who, string what); IEnumerable<object> GetUsers(string room); dynamic GetUserInfo(string room, string user); IEnumerable<string> GetRoomOwners(string room); dynamic GetRooms(); void ChangeNote(string note); void Nudge(string user); void SendAdministrativeCommand(string command); /// <summary> /// Disconnect the bot from the chat session. Leaves all rooms the bot entered /// </summary> void ShutDown(); } }<file_sep>namespace Jabbot { public static class BotExtensions { public static void SayToAllRooms(this IBot bot, string what) { foreach (var room in bot.Rooms) { bot.Say(what, room); } } } } <file_sep>using System.ComponentModel.Composition; namespace Jabbot.Sprockets.Core { /// <summary> /// This interface is used to allow messages not handled by the primary message flow /// a "last chance" before the message goes unhandled /// </summary> [InheritedExport] public interface IUnhandledMessageSprocket : IMessageHandler { } } <file_sep>Will have a closer look at the server behaviour of JabbR and see if i can diagnose it locally, hoping its something glaring. ## Repro steps - Open sln, build and run - User should receive a HTTP 500 response on the "/nick {username} {password}" invoke. - If that succeeds, the user should receive a "Use '/join room' to join a room" response on the say invoke (this is after joining successfully) ## Environment details SignalR.Client built from this version, includes pdbs: https://github.com/SignalR/SignalR/commit/585cded973c0d4db57a1d0adcecb7f9d694a8fda Jabbot source included so that you can step through code. <file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Threading.Tasks; using Jabbot.Models; using Jabbot.Sprockets.Core; using SignalR.Client.Hubs; using SignalR.Client.Transports; namespace Jabbot { public class Bot : IBot { readonly HubConnection _connection; readonly IHubProxy _chat; readonly string _password; readonly List<ISprocket> _sprockets = new List<ISprocket>(); readonly List<IUnhandledMessageSprocket> _unhandledMessageSprockets = new List<IUnhandledMessageSprocket>(); readonly HashSet<string> _rooms = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public Bot(string url, string name, string password) { Name = name; _password = <PASSWORD>; _connection = new HubConnection(url); _chat = _connection.CreateProxy("JabbR.Chat"); } public string Name { get; private set; } public ICredentials Credentials { get { return _connection.Credentials; } set { _connection.Credentials = value; } } public event Action Disconnected { add { _connection.Closed += value; } remove { _connection.Closed -= value; } } public event Action<ChatMessage> MessageReceived; /// <summary> /// Add a sprocket to the bot instance /// </summary> public void AddSprocket(ISprocket sprocket) { _sprockets.Add(sprocket); } /// <summary> /// Remove a sprocket from the bot instance /// </summary> public void RemoveSprocket(ISprocket sprocket) { _sprockets.Remove(sprocket); } /// <summary> /// Add a sprocket to the bot instance /// </summary> public void AddUnhandledMessageSprocket(IUnhandledMessageSprocket sprocket) { _unhandledMessageSprockets.Add(sprocket); } /// <summary> /// Remove a sprocket from the bot instance /// </summary> public void RemoveUnhandledMessageSprocket(IUnhandledMessageSprocket sprocket) { _unhandledMessageSprockets.Remove(sprocket); } /// <summary> /// Remove all sprockets /// </summary> public void ClearSprockets() { _sprockets.Clear(); } /// <summary> /// Connects to the chat session /// </summary> public void PowerUp(IEnumerable<ISprocketInitializer> sprocketInitializers = null) { if (!_connection.IsActive) { _chat.On<dynamic, string>("addMessage", ProcessMessage); _chat.On<string, string, string>("sendPrivateMessage", ProcessPrivateMessage); _chat.On("leave", OnLeave); _chat.On("addUser", OnJoin); _chat.On<IEnumerable<string>>("logOn", OnLogOn); _chat.On<dynamic, string>("addUser", ProcessRoomArrival); // Start the connection and wait _connection.Start(new LongPollingTransport()).Wait(); // Join the chat var success = _chat.Invoke<bool>("Join").Result; if (!success) { // Setup the name of the bot Send(String.Format("/nick {0} {1}", Name, _password)); if (sprocketInitializers != null) IntializeSprockets(sprocketInitializers); } } } /// <summary> /// Creates a new room /// </summary> /// <param name="room">room to create</param> public void CreateRoom(string room) { Send("/create " + room); // Add the room to the list _rooms.Add(room); } /// <summary> /// Joins a chat room. Changes this to the active room for future messages. /// </summary> public void Join(string room) { if (_rooms.Contains(room)) return; Send("/join " + room); // Add the room to the list _rooms.Add(room); } /// <summary> /// Leaves a chat room. /// </summary> public void Leave(string room) { if (!_rooms.Contains(room)) return; Send("/leave " + room); // Add the room to the list _rooms.Remove(room); } /// <summary> /// Sets the Bot's gravatar email /// </summary> /// <param name="gravatarEmail"></param> public void Gravatar(string gravatarEmail) { Send("/gravatar " + gravatarEmail); } /// <summary> /// Say something to the active room. /// </summary> /// <param name="what">what to say</param> /// <param name="room">the room to say it to</param> public void Say(string what, string room) { try { // Set the active room _chat["activeRoom"] = room; Say(what); } finally { // Reset the active room to null _chat["activeRoom"] = null; } } /// <summary> /// Reply to someone /// </summary> /// <param name="who">the person you want the bot to reply to</param> /// <param name="what">what you want the bot to say</param> /// <param name="room">the room to say it to</param> public void Reply(string who, string what, string room) { if (who == null) { throw new ArgumentNullException("who"); } if (what == null) { throw new ArgumentNullException("what"); } Say(String.Format("@{0} {1}", who, what), room); } public void PrivateReply(string who, string what) { if (who == null) { throw new ArgumentNullException("who"); } if (what == null) { throw new ArgumentNullException("what"); } Send(String.Format("/msg {0} {1}", who, what)); } /// <summary> /// List of rooms the bot is in. /// </summary> public IEnumerable<string> Rooms { get { return _rooms; } } public IEnumerable<dynamic> GetUsers(string room) { var users = new List<dynamic>(); var result = _chat.Invoke<dynamic>("getRoomInfo", room).Result; if (result == null) throw new Exception("Invalid Room"); var dynamicusers = result.Users; if (dynamicusers == null) { return users; } foreach (var u in dynamicusers) { users.Add(u); } return users; } public dynamic GetUserInfo(string room, string user) { var users = new Dictionary<string, dynamic>(); var dynamicusers = GetUsers(room); foreach (var u in dynamicusers) { users.Add(u.Name.ToString(), u); } if (!users.ContainsKey(user)) return null; return users[user]; } public IEnumerable<string> GetRoomOwners(string room) { var owners = new List<string>(); var result = _chat.Invoke<dynamic>("getRoomInfo", room).Result; if (result == null) throw new Exception("Invalid Room"); foreach (var owner in result.Owners) { owners.Add(owner.ToString()); } return owners; } public dynamic GetRooms() { var result = _chat.Invoke<dynamic>("getRooms").Result; return result; } public void ChangeNote(string note) { Send(String.Format("/note {0}", note)); } public void Nudge(string user) { Send(String.Format("/nudge {0}", user)); } public void SendAdministrativeCommand(string command) { if (!command.StartsWith("/")) { throw new InvalidOperationException("Only commands are allowed"); } Send(command); } /// <summary> /// Disconnect the bot from the chat session. Leaves all rooms the bot entered /// </summary> public void ShutDown() { // Leave all the rooms ever joined foreach (var room in _rooms) { Send(String.Format("/leave {0}", room)); } _connection.Stop(); } private void Say(string what) { if (what == null) { throw new ArgumentNullException("what"); } if (what.StartsWith("/")) { throw new InvalidOperationException("Commands are not allowed"); } Send(what); } private void ProcessPrivateMessage(string sender, string receiver, string message) { if (sender.Equals(receiver)) { return; } var chatMessage = new ChatMessage(WebUtility.HtmlDecode(message), sender, receiver); ProcessChatMessages(chatMessage); } private void ProcessMessage(dynamic message, string room) { // Run this on another thread since the signalr client doesn't like it // when we spend a long time processing messages synchronously string content = message.Content; string name = message.User.Name; // Ignore replies from self if (name.Equals(Name, StringComparison.OrdinalIgnoreCase)) { return; } // We're going to process commands for the bot here var chatMessage = new ChatMessage(WebUtility.HtmlDecode(content), name, room); ProcessChatMessages(chatMessage); } private void ProcessChatMessages(ChatMessage message) { Task.Factory.StartNew(() => { Debug.WriteLine(string.Format("PCM: {0} - {1} - {2}", message.Sender, message.Receiver, message.Content)); if (MessageReceived != null) { MessageReceived(message); } var handled = false; foreach (var handler in _sprockets) { if (handler.Handle(message, this)) { handled = true; break; } } if (!handled) { // Loop over the unhandled message sprockets foreach (var handler in _unhandledMessageSprockets) { // Stop at the first one that handled the message if (handler.Handle(message, this)) { break; } } } }) .ContinueWith(task => { // Just write to debug output if it failed if (task.IsFaulted) { var aggregateException = task.Exception; if (aggregateException != null) Debug.WriteLine("JABBOT: Failed to process messages. {0}", aggregateException.GetBaseException()); } }); } private void ProcessRoomArrival(dynamic message, string room) { string name = message.Name; Task.Factory.StartNew(() => { Debug.WriteLine(string.Format("PCM: {0} - {1}", name, room)); var handled = false; foreach (var handler in _sprockets) { if (handler.Handle(new ChatMessage("[JABBR] - " + name + " just entered " + room, name, room), this)) { handled = true; break; } } if (!handled) { // Loop over the unhandled message sprockets foreach (var handler in _unhandledMessageSprockets) { // Stop at the first one that handled the message if (handler.Handle(message, this)) { break; } } } }) .ContinueWith(task => { // Just write to debug output if it failed if (task.IsFaulted) { var aggregateException = task.Exception; if (aggregateException != null) Debug.WriteLine("JABBOT: Failed to process messages. {0}", aggregateException.GetBaseException()); } }); } private void OnLeave(dynamic user) { } private void OnJoin(dynamic user) { } private void OnLogOn(IEnumerable<string> rooms) { foreach (var room in rooms) { _rooms.Add(room); } } private void IntializeSprockets(IEnumerable<ISprocketInitializer> sprockets) { // Run all sprocket initializers foreach (var sprocketInitializer in sprockets) { try { sprocketInitializer.Initialize(this); } catch (Exception ex) { Trace.WriteLine(String.Format("Unable to Initialize {0}:{1}", sprocketInitializer.GetType().Name, ex.GetBaseException().Message)); } } } private void Send(string command) { #if DEBUG Console.WriteLine("DEBUG: Sending command {0}", command); #endif _chat.Invoke("send", command).Wait(); } } } <file_sep>using Jabbot.Models; namespace Jabbot.Sprockets.Core { public interface IMessageHandler { /// <summary> /// Allows the user to handle a message incoming from the bot's room /// </summary> /// <param name="message">Incoming message</param> /// <param name="bot">bot instance</param> /// <returns>true if handled, false if not</returns> bool Handle(ChatMessage message, IBot bot); } } <file_sep>namespace Jabbot.Models { public class ChatMessage { public ChatMessage(string content, string sender, string receiver) { Content = content; Sender = sender; Receiver = receiver; } public string Sender { get; set; } public string Content { get; set; } public string Receiver { get; set; } public bool IsPrivate { get; set; } } } <file_sep>using System.Reflection; [assembly: AssemblyTitle("Jabbot")] [assembly: AssemblyCompany("<NAME>")] [assembly: AssemblyDescription("Bot API for JabbR")] [assembly: AssemblyProduct("Jabbot")] [assembly: AssemblyCopyright("Copyright © <NAME>")] [assembly: AssemblyVersion("0.1")] <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Text; namespace Jabbot.Sprockets { [InheritedExport] public interface ISprocketInitializer { void Initialize(Bot bot); } } <file_sep>using System.ComponentModel.Composition; namespace Jabbot.Sprockets.Core { /// <summary> /// Sprockets are extension points for bots. When an incoming message comes in, a sprocket /// will get a change to do something with it. /// </summary> [InheritedExport] public interface ISprocket : IMessageHandler { } }
0d031e10ea41c2ba82a14614926f6b3885238be2
[ "Markdown", "C#" ]
15
C#
shiftkey/JabbotTestClient
6c3cf8a877f6556baf6d9b134b629e9508ef6565
319be335a5fe97223100b30e82b8feda001dc1f2
refs/heads/master
<file_sep># Customer-Management with C# Belajar membuat CRUD dengan List View Let's do it! <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Customer_Management { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //PROSES REFRESH private void refreshData() { //DO REFRESH txtName.Text = ""; txtLName.Text = ""; txtPhone.Text = ""; txtEmail.Text = ""; txtAddress.Text = ""; } //PROSES TAMBAH private void addData(String name, String lname, String phone, String email, String address) { //int countRow = 0; //count = countRow+1.ToString(); String[] row = { name, lname, phone, email, address }; ListViewItem data = new ListViewItem(row); listView1.Items.Add(data); } //PROSES DELETE private void deleteData() { //Buat Message Box untuk Warning if(txtName.Text == "") { MessageBox.Show("Tidak ada data yang dipilih.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { if (DialogResult.OK == (MessageBox.Show("Anda yakin ingin menghapus data ini? Data yang sudah dihapus tidak dapat dikembalikan", "Alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))) { listView1.Items.RemoveAt(listView1.SelectedIndices[0]); refreshData(); btnSubmit.Enabled = true; } } } //PROSES UPDATE private void updateData() { if (txtName.Text == "") { MessageBox.Show("Belum ada data yang Anda pilih. Silahkan pilih data yang ingin di update terlebih dahulu dan Pastikan field First Name tidak kosong.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { listView1.SelectedItems[0].SubItems[0].Text = txtName.Text; listView1.SelectedItems[0].SubItems[1].Text = txtLName.Text; listView1.SelectedItems[0].SubItems[2].Text = txtPhone.Text; listView1.SelectedItems[0].SubItems[3].Text = txtEmail.Text; listView1.SelectedItems[0].SubItems[4].Text = txtAddress.Text; refreshData(); btnSubmit.Enabled = true; } } //START private void listView1_SelectedIndexChanged(object sender, EventArgs e) { } private void btnReset_Click(object sender, EventArgs e) { if (DialogResult.OK == (MessageBox.Show("Anda yakin ingin menghapus semua data Customer? Data yang sudah dihapus tidak dapat dikembalikan", "DELETE ALL DATA", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))) { listView1.Items.Clear(); refreshData(); } } private void btnSubmit_Click(object sender, EventArgs e) { //Jika Nama Customer Kosong if (txtName.Text == "") { var notification = MessageBox.Show("Maaf, Nama Customer tidak boleh kosong! Harap masukkan nama customer", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { btnSubmit.Enabled = true; addData( txtName.Text, txtLName.Text, txtPhone.Text, txtEmail.Text, txtAddress.Text ); refreshData(); } } private void btnUpdate_Click(object sender, EventArgs e) { updateData(); } private void btnDelete_Click(object sender, EventArgs e) { deleteData(); } private void listView1_MouseClick(object sender, MouseEventArgs e) { txtName.Text = listView1.SelectedItems[0].SubItems[0].Text; txtLName.Text = listView1.SelectedItems[0].SubItems[1].Text; txtPhone.Text = listView1.SelectedItems[0].SubItems[2].Text; txtEmail.Text = listView1.SelectedItems[0].SubItems[3].Text; txtAddress.Text = listView1.SelectedItems[0].SubItems[4].Text; btnSubmit.Enabled = false; } private void Form1_Load(object sender, EventArgs e) { } } }
5ded89174c4d24329cdc50130d2f89dccd85eca7
[ "Markdown", "C#" ]
2
Markdown
mettasaputra/Customer-Management
9a6b240ea189a470f4218a16612cfdd051490fd8
c8cba57cace7c65422fccd9eaaa89018907b9da8
refs/heads/master
<repo_name>prasannalama/OIPA_Automation_Run<file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>OIPAAutomation_Jenkins</groupId> <artifactId>OIPAAutomation_Jenkins</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <main.basedir>${project.basedir}</main.basedir> </properties> <build> <sourceDirectory>src</sourceDirectory> <resources> <resource> <directory>src</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <suiteXmlFiles> <!-- TestNG suite XML files --> <suiteXmlFile>testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.59</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.6</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.testng/testng --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.3.0</version> <scope>compile</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-surefire-plugin --> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M5</version> </dependency> <!-- https://mvnrepository.com/artifact/net.sf.jxls/jxls-reader --> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-reader</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>org.osgl</groupId> <artifactId>excel-reader</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>ShineXLS</groupId> <artifactId>ShineXLS</artifactId> <scope>system</scope> <version>1.0</version> <systemPath>${project.basedir}/lib/ShineXLS.jar</systemPath> </dependency> </dependencies> </project><file_sep>/src/com/Library/OIPA_Library.java package com.Library; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.nio.file.Paths; import java.nio.file.Files; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Actions; import com.pageFactory.OIPA_PF; import xls.ShineXlsReader; public class OIPA_Library extends OIPA_PF { public static WebDriver driver1; public static String Browser; public XSSFWorkbook wb; public XSSFSheet sheet1; Properties p; public Connection con; String connectionString; public static ShineXlsReader xls = new ShineXlsReader(".\\src\\com\\Utilities\\TestData.xlsx"); String dbType = xls.getCellData("Config", "DbType", 2); String Host = xls.getCellData("Config", "Host", 2); String Port = xls.getCellData("Config", "Port", 2); String Schema = xls.getCellData("Config", "Schema", 2); String DbUserName = xls.getCellData("Config", "Db_UserName", 2); String DbPassword = xls.getCellData("Config", "Db_Password", 2); public void openBrowser() throws Throwable { System.out.println("Launching browser.."); Browser = "chrome"; System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); options.addArguments("--silent"); driver1 = new ChromeDriver(options); driver1.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); driver1.manage().deleteAllCookies(); driver1.manage().window().maximize(); } public WebDriver login(WebDriver driver) throws IOException { driver1.get(xls.getCellData("Config", "URL", 2)); wait(5); driver1.findElement(oipa_username).sendKeys(xls.getCellData("Config", "UserName", 2)); wait(5); driver1.findElement(oipa_password).sendKeys(xls.getCellData("Config", "Password", 2)); wait(5); driver1.findElement(oipa_login).click(); wait(5); return driver1; } public void wait(int seconds) { int ms = seconds * 1000; try { Thread.sleep(ms); } catch (Exception e) { System.out.println(e); } } public static void closeBrowser(WebDriver driver) { driver1.quit(); } public void selectItemInDropdown(WebDriver driver, String item) { String xpath = "//li[contains(.,'" + item + "')]"; driver1.findElement(By.xpath(xpath)).click(); } public Properties LoadPropertiesFile() throws IOException { FileReader reader = new FileReader(".\\src\\com\\Utilities\\config.properties"); Properties p = new Properties(); p.load(reader); return p; } public void takeScreenShot(WebDriver driver, String screenshotName) throws IOException { TakesScreenshot srcshot = ((TakesScreenshot) driver1); File srcFile = srcshot.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(srcFile, new File(".\\src\\com\\Utilities\\Screenshots\\" + screenshotName + ".png")); } // Checks if element passed in function is exists in screen public boolean exists(By by) { try { driver1.findElement(by); return true; } catch (Exception e) { return false; } } // Highlights the element passed in function public static WebDriver HighlightElement(WebDriver driver, By by) { WebElement Celement = driver.findElement(by); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor) driver).executeScript("arguments[0].style.border='3pxsolid red'", Celement); } return driver; } // Unhighlights the element passed in function public static WebDriver UnhighlightElement(WebDriver driver, By by) { WebElement Celement = driver.findElement(by); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor) driver).executeScript("arguments[0].style.border=''", Celement); } return driver; } // Navigates to the element passed in function in screen public void NavigateToElement(WebDriver driver, By by) { WebElement Celement = driver.findElement(by); JavascriptExecutor js = (JavascriptExecutor) driver; if (driver instanceof JavascriptExecutor) { js.executeScript("arguments[0].scrollIntoView();", Celement); } Actions actions = new Actions(driver); actions.moveToElement(Celement); actions.perform(); } // This will return the row data public ArrayList<String> RunQuery(String query) throws SQLException { ArrayList<String> Value = new ArrayList<String>(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(query); ResultSetMetaData md = rs.getMetaData(); int colNumber = md.getColumnCount(); while (rs.next()) { for (int i = 0; i < colNumber; i++) { Value.add(i, rs.getString(i + 1)); } } return Value; } // This method will establish a connection to DB public void connectToDb() { try { if (dbType.equalsIgnoreCase("Oracle")) { connectionString = "jdbc:oracle:thin:@" + Host + ":" + Port + ":" + Schema; // When // SID // is // used // String // connectionString="jdbc:oracle:thin:@//"+dbServer+":"+port+"/"+serviceName; // //When service name is used Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(connectionString, DbUserName, DbPassword); System.out.println("Oracle DB Connection Established"); } else if (dbType.equalsIgnoreCase("SQL")) { connectionString = "jdbc:sqlserver://" + Host + ":" + Port + ";databaseName=" + Schema + ";user=" + DbUserName + ";password=" + DbPassword; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection(connectionString); System.out.println("SQL DB Connection Established"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // This will update clob data for your specific businessrule public void db_updateClob(String fileName, String query) { try { String contents = new String(Files.readAllBytes(Paths.get(fileName))); StringReader reader = new StringReader(contents); PreparedStatement pStmt = con.prepareStatement(query); pStmt.setCharacterStream(1, reader, contents.length()); pStmt.executeUpdate(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // This will update the DB whenever you perform any change to DB rules public void db_refresh() { try { if (dbType.equalsIgnoreCase("Oracle")) { Statement statement = con.createStatement(); statement.executeQuery( "update assequence set sequencedate = sequencedate + 1 Where Sequencename = 'ConfigurationUpdatedGMT'"); wait(3); statement.executeQuery("commit"); wait(3); } else { db_runUpdate( "update assequence set sequencedate = sequencedate + 1 Where Sequencename = 'ConfigurationUpdatedGMT'"); } } catch (Exception e) { e.printStackTrace(); } } // This will help just to update any query public String db_runUpdate(String query) { String result = ""; try { Statement statement = con.createStatement(); statement.executeUpdate(query); } catch (Exception e) { System.out.println(e); return null; } return result; } // This will help in closing the DB Connection public void closeDbConnection() throws SQLException { con.close(); } } <file_sep>/test-output/old/Suite/JenkinsSmokeTest.properties [SuiteResult context=JenkinsSmokeTest]<file_sep>/src/test/java/CreatePolicy.java package test.java; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import java.io.IOException; import java.util.Random; import org.openqa.selenium.interactions.Actions; import com.Library.OIPA_Library; public class CreatePolicy extends OIPA_Library { // Functionality : Create Policy Random rand = new Random(); public String[] PolicyText, ClientText; public String policyHeading, clientHeading, existed_policyNumber; Actions a; @BeforeClass public void login() throws Throwable { System.out.println("***************Smoke Test******************************"); openBrowser(); login(driver1); } @Test public void policycreation() throws IOException { // creating WIS policy driver1.findElement(oipa_createDD).click(); wait(3); selectItemInDropdown(driver1, "Policy"); wait(3); driver1.findElement(oipa_CreateButton).click(); wait(3); driver1.findElement(oipa_policy_companyDD).click(); wait(3); selectItemInDropdown(driver1, "Westpac"); wait(3); driver1.findElement(oipa_policy_productDD).click(); wait(3); selectItemInDropdown(driver1, "BTBS-Standard"); wait(5); driver1.findElement(oipa_policy_planDD).click(); wait(5); selectItemInDropdown(driver1, "AGL-BTBS-ST-Plan1"); wait(5); driver1.findElement(oipa_policy_policyname).sendKeys(xls.getCellData("Policy", 0, 2) + rand.nextInt(1000)); wait(3); driver1.findElement(oipa_policy_BTBS_policynumber).sendKeys(xls.getCellData("Policy", 1, 2) + rand.nextInt(1000)); wait(3); driver1.findElement(oipa_policy_RiskCommencementDate).sendKeys(xls.getCellData("Policy", "RiskCommencementDate", 2)); wait(3); driver1.findElement(oipa_policy_RiskCessationDate).sendKeys(xls.getCellData("Policy", "RiskCessationDate", 2)); wait(3); driver1.findElement(oipa_policy_MemberAccountNumber).sendKeys(xls.getCellData("Policy", "MemberAccountNumber", 2)); wait(3); driver1.findElement(oipa_policy_EmployerBenefitCategoryCode).sendKeys(xls.getCellData("Policy", "EmployerBenefitCategoryCode", 2)); wait(3); driver1.findElement(oipa_policy_SmokerStatus).click(); wait(4); selectItemInDropdown(driver1, "Smoker"); wait(3); driver1.findElement(oipa_policy_CollarRating).sendKeys(xls.getCellData("Policy", "CollarRating", 2)); wait(3); driver1.findElement(oipa_policy_OccupationCode).sendKeys(xls.getCellData("Policy", "OccupationCode", 2)); wait(3); driver1.findElement(oipa_policy_OccupationDescription).sendKeys(xls.getCellData("Policy", "OccupationDescription", 2)); wait(3); driver1.findElement(oipa_policy_LastAnnualReviewDate).sendKeys(xls.getCellData("Policy", "LastAnnualReviewDate", 2)); wait(3); driver1.findElement(oipa_policy_PremiumEffectiveDate).sendKeys(xls.getCellData("Policy", "PremiumEffectiveDate", 2)); wait(3); driver1.findElement(oipa_policy_TotalPremiumDue).clear(); wait(3); driver1.findElement(oipa_policy_TotalPremiumDue).sendKeys(xls.getCellData("Policy", "TotalPremiumDue", 2)); wait(3); driver1.findElement(oipa_policy_PremiumFrequency).click(); wait(3); selectItemInDropdown(driver1, "Annual"); wait(3); driver1.findElement(oipa_policy_PremiumWaiverapplicableCheckbox).click(); wait(3); driver1.findElement(oipa_policy_PremiumWaiverEffectiveDate).sendKeys(xls.getCellData("Policy", "PremiumWaiverEffectiveDate", 2)); wait(3); driver1.findElement(oipa_policy_FrequencyLoading).sendKeys(xls.getCellData("Policy","FrequencyLoading", 2)); wait(3); driver1.findElement(oipa_policy_ModalPremium).clear(); wait(3); driver1.findElement(oipa_policy_ModalPremium).sendKeys(xls.getCellData("Policy","ModalPremium", 2)); wait(3); driver1.findElement(oipa_policy_ExplicitStampDutyFlagCheckbox).click(); wait(3); driver1.findElement(oipa_policy_RateGuaranteeFlagCheckbox).click(); wait(3); driver1.findElement(oipa_policy_RateGuaranteEndDate).sendKeys(xls.getCellData("Policy", "RateGuaranteEndDate", 2)); wait(3); driver1.findElement(oipa_policy_EmployerPaysPremium).click(); wait(3); selectItemInDropdown(driver1, "Y"); wait(3); driver1.findElement(oipa_policy_PlanRatingFactor).sendKeys(xls.getCellData("Policy", "PlanRatingFactor", 2)); wait(3); driver1.findElement(oipa_policy_RegistrySystemCode).click(); wait(3); selectItemInDropdown(driver1, "OIPA"); wait(3); driver1.findElement(oipa_policy_PremiumPaymentType).click(); wait(3); selectItemInDropdown(driver1, "Advance"); wait(3); driver1.findElement(oipa_policy_UnderwrittenOccupationClass).sendKeys(xls.getCellData("Policy", "UnderwrittenOccupationClass", 2)); wait(3); driver1.findElement(oipa_policy_AnnualisedStampDutyAmountFlagCheckbox).click(); wait(3); driver1.findElement(oipa_policy_ClaimIndexationBenefitApplicableCheckbox).click(); wait(3); driver1.findElement(oipa_policy_ExcludeFromSCITaxCheckbox).click(); wait(3); /*driver1.findElement(oipa_policy_BeneficiaryDetails).click(); wait(3); selectItemInDropdown(driver1, "1"); wait(3); driver1.findElement(oipa_policy_BeneficiaryName).sendKeys(xls.getCellData("Policy", "BeneficiaryName", 2)); wait(3); driver1.findElement(oipa_policy_BeneficiaryRelationship).click(); wait(3); selectItemInDropdown(driver1, "Husband"); wait(3); driver1.findElement(oipa_policy_BeneficiarySplitPercentage).clear(); wait(3); driver1.findElement(oipa_policy_BeneficiarySplitPercentage).sendKeys(xls.getCellData("Policy", "BeneficiarySplitPercentage", 2)); wait(3);*/ driver1.findElement(oipa_policy_savebutton).click(); wait(3); // taking screenshot of policy creation takeScreenShot(driver1, "WSI_policy_creation"); wait(3); policyHeading = driver1.findElement(oipa_policyText).getText(); wait(3); PolicyText = policyHeading.split("#"); System.out.println("Policy Number is: " + PolicyText[1]); } @AfterClass public void postTestCase() { closeBrowser(driver1); } } <file_sep>/target/classes/com/Utilities/config.properties url = http://slc10vjk.us.oracle.com:7110/PASJava/index.html Host = slc10vps.us.oracle.com Port = 1522 Schema = SIT <file_sep>/src/test/java/NewTest.java package test.java; import java.sql.Connection; import java.util.Properties; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.testng.annotations.Test; public class NewTest { public static WebDriver driver1; public static String Browser; public XSSFWorkbook wb; public XSSFSheet sheet1; Properties p; public Connection con; String connectionString; @Test public static void testgooglesearch() { System.out.println("Launching browser.."); Browser = "chrome"; System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); options.addArguments("--silent"); driver1 = new ChromeDriver(options); driver1.get("http://google.in"); // we expect the title “Google “ should be present String Expectedtitle = "Google"; // it will fetch the actual title String Actualtitle = driver1.getTitle(); System.out.println("Before Assetion " + Expectedtitle + Actualtitle); // it will compare actual title and expected title // print out the result System.out.println("After Assertion " + Expectedtitle + Actualtitle + " Title matched "); System.out.println("Hello World"); } }
7a9c08588d0f299b3ef286a712809885f0cafc26
[ "Java", "Maven POM", "INI" ]
6
Maven POM
prasannalama/OIPA_Automation_Run
42dbd744a192e8b98ee866c486e654a529126382
08bcc26bdc290026d033559a5bcc3b9601edf48c
refs/heads/main
<file_sep># Simple Discord Exploits <file_sep>from dhooks import Webhook import os from colorama import Fore, init import requests, json def start(): os.system("cls") print(Fore.BLUE) print(" __ __ __ __ ") print(" _ _____ / /_ / /_ ____ ____ / /__ ____ __ __/ /_____ _____") print(" | | /| / / _ \/ __ \/ __ \/ __ \/ __ \/ //_/ / __ \/ / / / //_/ _ \/ ___/") print(" | |/ |/ / __/ /_/ / / / / /_/ / /_/ / ,< / / / / /_/ / ,< / __/ / ") print(" |__/|__/\___/_.___/_/ /_/\____/\____/_/|_| /_/ /_/\__,_/_/|_|\___/_/ ") print("") print(" G X T H B A E") print("") global webhook_link webhook_link = input(" Enter the link of the webhook : ") def main(): start() hook = Webhook(webhook_link) print("") print("Getting webhook infos...") input("") r = requests.get(webhook_link).json() print("id : " + r['id']) print("name : " + r['name']) print("channel id : " + r['channel_id']) print("guild id : " + r['guild_id']) print("token : " + r['token']) print("") nuke = input("the webhook will be deleted are you sure you want to do it [ Y / N ] : ") if nuke == str('Y'): hook.delete() print("Succsesfuly deleted") input("") start() elif nuke == str('N'): start() if __name__ == "__main__": main()<file_sep>import requests from discord import Webhook, RequestsWebhookAdapter import colorama from colorama import Fore import threading # import brain # import haram # import halal colorama.init() def WebHook(): url = input("Webhook Url>>") message = input("Message>>") threading.Thread(target=WebHook).start() while True: webhook = Webhook.from_url(f"{url}", adapter=RequestsWebhookAdapter()) webhook.send(f"{message}") print(f"{Fore.GREEN}[+] Sent {message}") print(f""" {Fore.RED}██╗ ██╗███████╗██████╗ ██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗ {Fore.RED}██║ ██║██╔════╝██╔══██╗██║ ██║██╔═══██╗██╔═══██╗██║ ██╔╝ {Fore.RED}██║ █╗ ██║█████╗ ██████╔╝███████║██║ ██║██║ ██║█████╔╝ {Fore.RED}██║███╗██║██╔══╝ ██╔══██╗██╔══██║██║ ██║██║ ██║██╔═██╗ {Fore.RED}╚███╔███╔╝███████╗██████╔╝██║ ██║╚██████╔╝╚██████╔╝██║ ██╗ {Fore.RED} ╚══╝╚══╝ ╚══════╝╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ {Fore.RED}███████╗██████╗ █████╗ ███╗ ███╗███╗ ███╗███████╗██████╗ {Fore.RED}██╔════╝██╔══██╗██╔══██╗████╗ ████║████╗ ████║██╔════╝██╔══██╗ {Fore.RED}███████╗██████╔╝███████║██╔████╔██║██╔████╔██║█████╗ ██████╔╝ {Fore.RED}╚════██║██╔═══╝ ██╔══██║██║╚██╔╝██║██║╚██╔╝██║██╔══╝ ██╔══██╗ {Fore.RED}███████║██║ ██║ ██║██║ ╚═╝ ██║██║ ╚═╝ ██║███████╗██║ ██║ {Fore.RED}╚══════╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ By GxthBae / Simon [1] WebHook Spammer """) allah = input("Select>>") if allah == '1': WebHook()
db2d2b7e978d896e27e882278c071a9f6d409bff
[ "Markdown", "Python" ]
3
Markdown
lnfernal/Discord-Exploits
6ea8ac522e8d0a9301af87e4224dc74461dd081f
8c72221c64703eda8c5dfe0b3ec9019094cca287
refs/heads/master
<file_sep> //delete부분이 미완성. #include <stdio.h> #include <stdlib.h> typedef struct _node { int data; struct _node *left; struct _node *right; }TreeNode; void init(TreeNode **root) { *root = NULL; } TreeNode *MakeNewNode(int data, TreeNode *left, TreeNode *right) { TreeNode *newNode = (TreeNode *)malloc(sizeof(TreeNode)); newNode->data = data; newNode->left = left; newNode->right = right; return newNode; } void insert_node(TreeNode **root, int key) { TreeNode *parent = NULL; TreeNode *current = *root; TreeNode *newNode = NULL; while (current != NULL) { if (key == current->data) return; parent = current; if (key < current->data) current = current->left; else current = current->right; } newNode = (TreeNode *)malloc(sizeof(TreeNode)); newNode->data = key; newNode->left = newNode->right = NULL; if (parent != NULL) { if (key < parent->data) parent->left = newNode; else parent->right = newNode; } else *root = newNode; } void Delete_node(TreeNode **root, int key) { TreeNode *parent, *child, *succ, *succ_p, *current; parent = NULL; current = *root; while (current != NULL && current->data != key) { parent = current; if (key < current->data) current = current->left; else current = current->right; } if (current == NULL) { printf("key is not in the free"); return; } if (current->left == NULL && current->right == NULL) { if (parent != NULL) { if (parent->left == current) parent->left = NULL; else parent->right = NULL; } else { *root = NULL; } } else if (current->left != NULL || current->right != NULL) { child = (current->left != NULL) ? current->left : current->right; if (parent != NULL) { if (parent == current) parent->left = child; else parent->right = child; } else *root = child; } else { succ = current->right; succ_p = current; while (succ->left != NULL) { succ_p = succ; succ = succ->left; } if (succ_p->left == succ) succ_p->left = succ->right; else succ_p->right = succ->right; } } int main(void) { int arr[] = { 5,3,7,2,4,6,9,1,8,10 }; TreeNode *root; int i; init(&root); for (i = 0; i < 11; i++) insert_node(&root, arr[i]); in(root); printf("\n"); Delete_node(&root, 10); in(root); return 0; }<file_sep>#include <stdio.h> #include <limits.h> #define TRUE 1 #define FALSE 0 #define MAX_VERTICES 7 #define INF 1000 int weight[MAX_VERTICES][MAX_VERTICES] = { { 0,7,INF,INF,3,10,INF }, { 7,0,4,10,2,6,INF }, { INF,4,0,2,INF ,INF ,INF }, { INF,10,2,0,11,9,4 }, { 3,2,INF ,11,0,INF ,5 }, { 10,6,INF ,9,INF ,0,INF }, { INF ,INF ,INF ,4,5,INF ,0 } }; int distance[MAX_VERTICES]; int found[MAX_VERTICES]; int choose(int distance[], int n, int found[]) { int i, minpos; int min = INT_MAX; minpos = -1; for (i = 0; i < n; i++) { if (distance[i] < min && !found[i]) { min = distance[i]; minpos = i; } } return minpos; } void Shortest_path(int start, int n) { int i, u, w,j,k; for (i = 0; i < n; i++) { distance[i] = weight[start][i]; found[i] = FALSE; } found[start] = TRUE; distance[start] = 0; printf("distance[]: "); for (i = 0; i < MAX_VERTICES; i++) printf("%d ", distance[i]); printf("\n"); for (i = 0; i < n - 2; i++) { u = choose(distance, n, found); found[u] = TRUE; printf("\nfound[]: "); for (j = 0; j < MAX_VERTICES; j++) printf("%d ",found[j]); printf("\n"); printf("가장 가까운 정점: %d\n", u); printf("가장 가까운 정점의 거리: %d\n", distance[u]); for (w = 0; w < n; w++) if (!found[w]) if (distance[u] + weight[u][w] < distance[w]) { distance[w] = distance[u] + weight[u][w]; } printf("distance[]: "); for (k = 0; k < MAX_VERTICES; k++) printf("%d ", distance[k]); printf("\n\n"); } } int main(void) { int i,j; printf("인접행렬 초기값\n"); for (i = 0; i < MAX_VERTICES; i++) { for (j = 0; j < MAX_VERTICES; j++) printf("%d ", weight[i][j]); printf("\n"); } printf("\n\n"); Shortest_path(0, MAX_VERTICES); system("pause"); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct _node { char strarr[10]; }Node; Node arr[10][2]; int Hashinit() { for (int i = 0; i < 2; i++) for(int j =0; j < 10 ;j++) arr[i][j].strarr[0] = 0; } int HashisEmpty(int i) { if (arr[i][0].strarr[0] == 0) return 1; else return 0; } int transform(char *key) { int number = 0; while (*key) number += *key++; return number; } int HashGetValue(char *key) { printf("idx: %d\n", transform(key) % 10); return transform(key) % 10; } void DisPlay() { printf("---------------------------------------\n"); for (int i = 0; i < 10; i++) { printf("[%d] %s %s", i, arr[i][0].strarr,arr[i][1].strarr); printf("\n"); } printf("\n---------------------------------------\n"); } void HashInsert(Node key) { int i; int hash_idx = i = HashGetValue(key.strarr); while (!HashisEmpty(i)) { if (!strcmp(arr[i][0].strarr, key.strarr) || !strcmp(arr[i][1].strarr,key.strarr)) { printf("\n\n중복입니다\n\n"); break; } if (arr[i][1].strarr[0] == 0) { arr[i][1] = key; break; } i = (i + 1) % 10; if (i == hash_idx) { printf("테이블이 가득 찼습니다."); break; } } if(arr[i][1].strarr[0] == 0) arr[i][0] = key; } void HashSeach(Node key) { int i; int hash_idx = i = HashGetValue(key.strarr); while (!HashisEmpty(i)) { if (!strcmp(arr[i][0].strarr, key.strarr) || !strcmp(arr[i][1].strarr,key.strarr)) { printf("\n\n찾았습니다! : %s\n", key.strarr); break; } i = (i + 1) % 10; if (i == hash_idx) { printf("\n\n테이블에 찾고자 하는 값이 없습니다.\n\n"); break; } } if(arr[hash_idx][0].strarr[0] ==0) printf("\n\n해당 인덱스에 값이 없습니다.\n"); } int main(void) { int n; Node str; int hash_idx = 0; while (1) { printf("1번 삽입 || 2번 조회 || 3번 종료: "); scanf("%d", &n); if (n == 3)break; printf("단어입력:"); scanf("%s", &str.strarr); if (n == 1) HashInsert(str); else if (n == 2) HashSeach(str); DisPlay(); } system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> int numofdata; int BFSvisit[100]; int BFSarr[100]; typedef struct _node { int data; int w; struct _node *next; }Node; typedef struct _adj { Node *arr[100]; }Graph; typedef struct _heap { Node *heaparr[100]; }Heap; void Graphinit(Graph *g, Heap *heap) { int i; for (i = 0; i < 100; i++) { g->arr[i] = NULL; heap->heaparr[i] = NULL; } } int GisEmpty(Node *g) { if (g == NULL) return 1; else return 0; } void Hinsert(Heap *heap, Node *u) { int idx = numofdata + 1; while (idx != 1) { if (heap->heaparr[idx / 2]->w > u->w) { heap->heaparr[idx] = heap->heaparr[idx / 2]; idx = idx / 2; } else break; } heap->heaparr[idx] = u; numofdata += 1; } void Heapfy(Heap *heap, int i, int size) { int left = i * 2; int right = left + 1; int min; Node *temp; if (left <= size && heap->heaparr[left]->w < heap->heaparr[i]->w) min = left; else min = i; if (right <= size && heap->heaparr[right]->w < heap->heaparr[min]->w) min = right; if (min != i) { temp = heap->heaparr[i]; heap->heaparr[i] = heap->heaparr[min]; heap->heaparr[min] = temp; Heapfy(heap, min, size); } } Node *Dequeue(Heap *heap) { Node *root = heap->heaparr[1]; heap->heaparr[1] = heap->heaparr[numofdata]; numofdata -= 1; Heapfy(heap, 1, numofdata); return root; } void ADJinsert(Graph *g, int u, int v, int w) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = v; newNode->w = w; newNode->next = NULL; if (g->arr[u] == NULL) g->arr[u] = newNode; else { newNode->next = g->arr[u]; g->arr[u] = newNode; } Node *VnewNode = (Node *)malloc(sizeof(Node)); VnewNode->data = u; VnewNode->next = NULL; VnewNode->w = w; if (g->arr[v] == NULL) g->arr[v] = VnewNode; else { VnewNode->next = g->arr[v]; g->arr[v] = VnewNode; } } void Display(Graph *g, int v) { Node *temp; int i; for (i = 1; i < v; i++) { temp = g->arr[i]; while (!GisEmpty(temp)) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } } void BFS(Graph *g, int start, int v) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = start; newNode->w = g->arr[start]->w; newNode->next = NULL; Heap heap; Node *u; int i, idx = 0; Node *temp; Hinsert(&heap, newNode); while (numofdata != 0) { u = Dequeue(&heap); temp = g->arr[u->data]; BFSarr[u->data] = u->data; while (!GisEmpty(temp)) { if (BFSvisit[temp->data] == 0) { Hinsert(&heap, temp); BFSvisit[temp->data] = 1; temp = temp->next; } else temp = temp->next; } } for (i = 1; i < v; i++) printf("%d ", BFSarr[i]); } int main(void) { Graph adjlist; Heap heap; int i, u, v, w; int n1, n2, start; Graphinit(&adjlist, &heap); scanf("%d %d %d", &u, &v, &start); for (i = 0; i < v; i++) { scanf("%d %d %d", &n1, &n2, &w); ADJinsert(&adjlist, n1, n2, w); } Display(&adjlist, v); printf("\n\n"); BFS(&adjlist, start, v); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 typedef struct _node { int data; struct _node *left; struct _node *right; }Node; typedef struct _que { Node *head; Node *tail; }Queue; void init(Queue *pq) { pq->head = NULL; pq->tail = NULL; } int QisEmpty(Queue *pq) { if (pq->head == NULL) return TRUE; else return FALSE; } void Front_Enqueue(Queue *pq, int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; if (pq->tail == NULL) pq->tail = newNode; else { pq->head->left = newNode; newNode->right = pq->head; } pq->head = newNode; } void Back_Enqueue(Queue *pq, int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; if (pq->head == NULL) pq->head = newNode; else { newNode->left = pq->tail; pq->tail->right = newNode; } pq->tail = newNode; } int Front_Dequeue(Queue *pq) { int rdata; Node *rnode; if (QisEmpty(pq)) { printf("memory error"); exit(-1); } rnode = pq->head; rdata = rnode->data; pq->head = pq->head->right; free(rnode); return rdata; } int Back_Dequeue(Queue *pq) { int rdata; Node *rnode; if (QisEmpty(pq)) { printf("memory error"); exit(-1); } rnode = pq->tail; rdata = rnode->data; pq->tail = pq->tail->left; free(rnode); return rdata; } int main(void) { Queue pq; init(&pq); Front_Enqueue(&pq, 3); Front_Enqueue(&pq, 2); Front_Enqueue(&pq, 1); Back_Enqueue(&pq, 4); Back_Enqueue(&pq, 5); Back_Enqueue(&pq, 6); while (!QisEmpty(&pq)) { printf("%d ", Front_Dequeue(&pq)); } system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct _node { int check; int node; int data; struct _node *next; }Node; typedef struct _adj { Node *arr[100]; }AdjacencyList; typedef struct _stack { Node *head; Node *tail; }Stack; void init(AdjacencyList *list, Stack *stack) { stack->head = NULL; stack->tail = NULL; for (int i = 0; i < 100; i++) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->check = 0; newNode->data = 0; newNode->next = NULL; newNode->node = i; list->arr[i] = newNode; } } int SisEmpty(Stack *stack) { if (stack->head == NULL) return 1; else return 0; } void AdjInsert(AdjacencyList *list, int node, int to, int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->check = 0; newNode->node = to; newNode->data = data; newNode->next = NULL; Node *cur = list->arr[node]->next; Node *before = cur; if (list->arr[node]->next == NULL) list->arr[node]->next = newNode; else { while (cur != NULL && cur->node != to) { before = cur; cur = cur->next; } before->next = newNode; } } void Push(Stack *stack,int idx) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->check = 0; newNode->node = idx; newNode->data = 0; newNode->next = NULL; if (stack->head == NULL) stack->head = newNode; else { newNode->next = stack->head; stack->head = newNode; } } int Pop(Stack *stack) { if (SisEmpty(stack)) { printf("stack이 비었습니다\n"); exit(-1); } int idx = stack->head->node; stack->head = stack->head->next; return idx; } void DFS(AdjacencyList *list, Stack *stack,int visit[],int start) { Push(stack, list->arr[start]->node); int idx = 0; int element =0; Node *temp; while (stack->head != NULL) { idx = Pop(stack); temp = list->arr[idx]; if (temp->check == 0) { list->arr[idx]->check = 1; visit[element++] = idx; } while (temp != NULL) { if (list->arr[temp->node]->check == 0) { Push(stack, temp->node); temp = temp->next; } else temp = temp->next; } } } int main(void) { AdjacencyList list; Stack stack; int visit[100] = { 0 }; int sum; int node; int to; int edge; int len = 0; int idx; int num; init(&list, &stack); printf("총개수: "); scanf("%d", &sum); for (int i = 0; i < sum; i++) { printf("node / edge: "); scanf(" %d %d", &node, &edge); for (int j = 0; j < edge; j++) { printf("to / num: "); scanf(" %d ,%d", &to, &num); fgetc(stdin); AdjInsert(&list, node, to, num); } } DFS(&list, &stack, visit, 1); while (visit[len] != 0) len++; for (int i = 0; i < len; i++) printf("%d ", visit[i]); printf("\n"); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <string.h> #define KEY_SIZE 10 #define TABLE_SIZE 13 #define TRUE 1 #define FALSE 0 typedef struct { char key[KEY_SIZE]; }element; element hash_table[TABLE_SIZE][2]; void init_table(element ht[][2]) { int i, j; for (i = 0; i < TABLE_SIZE; i++) { for (j = 0; j < 2; j++) { ht[i][j].key[0] = NULL; } } } int empty(element ht[][2],int i) { if (strlen(ht[i][0].key) != 0 || strlen(ht[i][1].key) != 0) return TRUE; else return FALSE; } int transform(char *key) { int number = 0; while (*key) number += *key++; return number; } int hash_function(char *key) { return transform(key) % TABLE_SIZE; } void hash_lp_search(element item, element ht[][2]) { int i, hash_value, j= 0; hash_value = i = hash_function(item.key); int idx = 0; if (empty(hash_table, i)){ while (j != 2) { if (!strcmp(ht[i][j].key, item.key)) { printf("탐색 성공: 위치 = %d\n", i); return; } j++; } idx = idx + 1; i = (i + idx*idx) % TABLE_SIZE; j = 0; while (j != 2) { if (!strcmp(ht[i][j].key, item.key)) { printf("\n탐색 성공: 위치 = %d\n", i); return; } j++; } if (i == hash_value) { printf("\n찾는 값이 테이블에 존재하지 않습니다\n"); return; } } printf("\n찾는 값이 테이블에 존재하지 않습니다\n"); return; } void hash_lp_add(element item, element ht[][2]) { int i, hash_value, j = 0; hash_value = i = hash_function(item.key); int idx = 0; printf("입력값: %s\n", item.key); if (empty(hash_table, i)) { while (j != 2) { if (!strcmp(ht[i][j].key, item.key)) { printf("키가 중복되었습니다\n"); return; } j++; } idx = idx + 1; i = (i + idx*idx) % TABLE_SIZE; if (i == hash_value) { printf("테이블이 가득찼습니다\n"); return; } } if (ht[i][0].key[0] == NULL) ht[i][0] = item; else { if (ht[i][1].key[0] == NULL) ht[i][1] = item; else { j = 0; while (j != 2) { if (!strcmp(ht[i][j].key, item.key)) { printf("\n키가 중복되었습니다\n"); return; } j++; } while (empty(ht, i)) i++; ht[i][1] = item; } } } void hash_lp_print(element ht[][2],element item) { int j=0; int i ; int idx = 0; while (idx != TABLE_SIZE) { printf("[%d]", idx); i = idx; if (empty(ht, i)) { while (j != 2) { printf(" %s ", ht[i][j].key); j++; } j = 0; } printf("\n"); idx++; } } int main(void) { element tmp; int op; while (1) { printf("원하는 연산을 입력하시오(0=입력,1=탐색,2=종료)="); scanf("%d", &op); if (op == 2)break; printf("키를 입력하시오="); scanf("%s", tmp.key); if (op == 0) hash_lp_add(tmp, hash_table); else if (op == 1) hash_lp_search(tmp, hash_table); hash_lp_print(hash_table,tmp); } return 0; } <file_sep>#include <stdio.h> #include <string.h> #define KEY_SIZE 10 #define TABLE_SIZE 13 #define TRUE 1 #define FALSE 0 typedef struct { char key[KEY_SIZE]; }element; element hash_table[TABLE_SIZE]; void init_table(element ht[]) { int i; for (i = 0; i < TABLE_SIZE; i++) { ht[i].key[0] = NULL; } } int empty(element ht[]) { if (ht->key[0] == NULL) return TRUE; else return FALSE; } int transform(char *key) { int number = 0; while (*key) number += *key++; return number; } int hash_function(char *key) { return transform(key) % TABLE_SIZE; } void hash_lp_search(element item, element ht[]) { int i, hash_value, j; hash_value = i = hash_function(item.key); while (!empty(&ht[i])) { if (!strcmp(ht[i].key, item.key)) { printf("탐색 성공: 위치 = %d\n", i); return; } i = (i + 1) % TABLE_SIZE; if (i == hash_value) { printf("찾는 값이 테이블에 존재하지 않습니다\n"); return; } } printf("찾는 값이 테이블에 존재하지 않습니다\n"); return; } void hash_lp_add(element item, element ht[]) { int i, hash_value; hash_value = i = hash_function(item.key); while (!empty(&ht[i])) { if (!strcmp(ht[i].key, item.key)) { printf("이름이 중복되었습니다\n"); return; } i = (i + 1) % TABLE_SIZE; if (i == hash_value) { printf("테이블이 가득찼습니다\n"); return; } } ht[i] = item; } void hash_lp_print(element ht[]) { int i; for (i = 0; i < TABLE_SIZE; i++) printf("[%d] %s\n", i, ht[i].key); } int main(void) { element tmp; int op; while (1) { printf("원하는 연산을 입력하시오(0=입력,1=탐색,2=종료)="); scanf("%d", &op); if (op == 2)break; printf("키를 입력하시오="); scanf("%s", tmp.key); if (op == 0) hash_lp_add(tmp, hash_table); else if (op == 1) hash_lp_search(tmp, hash_table); hash_lp_print(hash_table); } return 0; }<file_sep>#include <stdio.h> typedef struct _node { int arr[100]; int data; int numofdata; }Heap; int Parentidx(int idx) { return idx / 2; } int leftchildidx(int idx) { return idx * 2; } int rightchildidx(int idx) { return leftchildidx(idx) + 1; } void Hinit(Heap *hp) { hp->data = 0; hp->numofdata = 0; } void HeapInsert(Heap *hp,int data) { int idx = hp->numofdata + 1; while (idx != 1) { if (hp->arr[Parentidx(idx)] > data) { hp->arr[idx] = hp->arr[Parentidx(idx)]; idx = Parentidx(idx); } else break; } hp->arr[idx] = data; hp->numofdata += 1; } void heapfy(Heap *heap, int idx, int size) { int left = leftchildidx(idx); int right = rightchildidx(idx); int temp; int minimum; if (left <= size && heap->arr[left] < heap->arr[idx]) minimum = left; else minimum = idx; if (right <= size && heap->arr[right] < heap->arr[minimum]) minimum = right; if (minimum != idx) { temp = heap->arr[idx]; heap->arr[idx] = heap->arr[minimum]; heap->arr[minimum] = temp; heapfy(heap, minimum, heap->numofdata); } } int Hdelete(Heap *hp) { int head = hp->arr[1]; hp->arr[1] = hp->arr[hp->numofdata]; heapfy(hp, 1, hp->numofdata); hp->numofdata -= 1; return head; } int main(void) { Heap heap; Hinit(&heap); HeapInsert(&heap, 3); HeapInsert(&heap, 2); HeapInsert(&heap, 1); HeapInsert(&heap, 4); HeapInsert(&heap, 5); while (heap.numofdata != 0) printf("%d ", Hdelete(&heap)); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> void merge(int arr[], int newarr[], int left, int mid, int right) { int Lidx = left; int Ridx = mid + 1; int idx = left; int i; printf("[%d %d %d]\n", left, mid, right); while ((Lidx <= mid) && (Ridx <= right)) { if (arr[Lidx] <= arr[Ridx]) newarr[idx++] = arr[Lidx++]; else newarr[idx++] = arr[Ridx++]; } if (Lidx > mid) for (i = Ridx; i <= right; i++) newarr[idx++] = arr[i]; else for (i = Lidx; i <= mid; i++) newarr[idx++] = arr[i]; for (i = left; i <= right; i++) arr[i] = newarr[i]; for (i = left; i <= right; i++) printf("%d ", newarr[i]); printf("\n"); } void MergeSort(int arr[], int newarr[], int left, int right) { int mid; if (left < right) { mid = (left + right) / 2; MergeSort(arr, newarr, left, mid); MergeSort(arr, newarr, mid + 1, right); merge(arr, newarr, left, mid, right); } } int main() { int arr[] = { 1,4,2,5,3,6,9,7 }; int len = sizeof(arr) / sizeof(int); int *newarr = (int *)malloc(sizeof(int)*len ); int i; MergeSort(arr, newarr, 0, len - 1); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct _node { int node; int data; struct _node *next; }Node; typedef struct _adj { Node *arr[100]; }AdjacencyList; void init(AdjacencyList *list) { for (int i = 0; i < 100; i++) list->arr[i] = NULL; } void AdjInsert(AdjacencyList *list,int node,int to,int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->node = to; newNode->data = data; newNode->next = NULL; Node *cur = list->arr[node]; Node *before = cur; if (list->arr[node] == NULL) list->arr[node]= newNode; else { while (cur != NULL && cur->node != to) { before = cur; cur = cur->next; } before->next = newNode; } } void peek(AdjacencyList * list) { Node *temp; for (int i = 0; i < 100; i++) { if (list->arr[i] != NULL) { printf("%d¹øÂ°: ", i); temp = list->arr[i]; while (temp != NULL) { printf("%d ", temp->node); temp = temp->next; } printf("\n"); } } } int main(void) { AdjacencyList list; init(&list); int sum; int node; int to; int edge; int idx; int num; printf("ÃѰ³¼ö: "); scanf("%d", &sum); for (int i = 0; i < sum; i++) { printf("node / edge: "); scanf(" %d %d",&node, &edge); for (int j = 0; j < edge; j++) { printf("to / num: "); scanf(" %d ,%d", &to, &num); fgetc(stdin); AdjInsert(&list,node,to, num); } } peek(&list); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct _node { int data; struct _node *next; }Node; typedef struct _stack { Node *head; }Stack; void init(Stack *pstack) { pstack->head = NULL; } int SisEmpty(Stack *pstack) { if (pstack->head == NULL) return 1; else return 0; } void push(Stack *pstack,int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; if (pstack->head == NULL) pstack->head = newNode; else { newNode->next = pstack->head; pstack->head = newNode; } } int pop(Stack *pstack) { int rdata; Node *rnode; if (SisEmpty(pstack)) { printf("memory error"); exit(-1); } rnode = pstack->head; rdata = rnode->data; pstack->head = pstack->head->next; free(rnode); return rdata; } int main(void) { Stack stack; init(&stack); push(&stack, 1); push(&stack, 2); push(&stack, 3); push(&stack, 4); push(&stack, 5); while (!SisEmpty(&stack)) printf("%d ", pop(&stack)); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #define INF 9999 int distance[10]; typedef struct _graphtype { int data; int w; struct _graphtype *next; }Node; typedef struct adjlist { Node *adjarr[10]; int numofdata; }Graph; typedef struct heap { Node *datadarr[10]; int num; }Heap; void Heapinit(Heap *ph) { ph->num = 0; int i; for (i = 1; i <= 10; i++) ph->datadarr[i] = NULL; } void Enqueue(Heap *pq, Node *data) { int idx = pq->num + 1; while (idx != 1) { if (pq->datadarr[idx / 2] -> w > data -> w) { pq->datadarr[idx] = pq->datadarr[idx / 2]; idx = idx / 2; } else break; } pq->datadarr[idx] = data; pq->num += 1; } void heapfy(Heap *pq, int i, int size) { int left = i * 2; int right = left + 1; int largest; Node *temp; if (left <= size && pq->datadarr[left]->w < pq->datadarr[i]->w) largest = left; else largest = i; if (right <= size && pq->datadarr[right]->w < pq->datadarr[largest]->w) largest = right; if (largest != i) { temp = pq->datadarr[largest]; pq->datadarr[largest] = pq->datadarr[i]; pq->datadarr[i] = temp; heapfy(pq, largest, size); } } Node *Dequeue(Heap *heap) { Node *temp = heap->datadarr[1]; heap->datadarr[1] = heap->datadarr[heap->num]; heap->num -= 1; heapfy(heap, 1, heap->num); return temp; } void init(Graph *g) { int i; g->numofdata = 0; for (i = 0; i <= 10; i++) { g->adjarr[i] = NULL; } } void AdjInsert(Graph *adj, int u, int v, int w) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = v; newNode->w = w; newNode->next = NULL; if (adj->adjarr[u] == NULL) adj->adjarr[u] = newNode; else { newNode->next = adj->adjarr[u]; adj->adjarr[u] = newNode; } Node *VnewNode = (Node *)malloc(sizeof(Node)); VnewNode->data = u; VnewNode->w = w; VnewNode->next = NULL; if (adj->adjarr[v] == NULL) adj->adjarr[v] = VnewNode; else { VnewNode->next = adj->adjarr[v]; adj->adjarr[v] = VnewNode; } adj->numofdata++; } void Display(Graph *g) { int i; Node *temp; for (i = 1; i <= g->numofdata; i++) { temp = g->adjarr[i]; printf("%d-> ", i); while (temp != NULL) { printf("%d/%d", temp->data,temp->w); temp = temp->next; printf("-> "); } printf("\n"); } } void Dijstra(Graph *g, int start) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = start; newNode->w = 0; newNode->next = NULL; Node *u, *cur; int i,w=0; Heap heap; Heapinit(&heap); Enqueue(&heap, newNode); distance[start] = 0; while (heap.num != 0) { u = Dequeue(&heap); cur = g->adjarr[u->data]; while (cur != NULL) { if (distance[cur->data] == INF && start == u->data) { distance[cur->data] = cur->w; Enqueue(&heap, cur); } else if (distance[cur->data] > distance[u->data] + g->adjarr[u->data]->w) distance[cur->data] = distance[u->data] + g->adjarr[u->data]->w; cur = cur->next; } printf("\n"); for (i = 1; i <= 4; i++) printf("%d ", distance[i]); } } int main(void) { Graph graph; int i; init(&graph); for (i = 1; i <= 10; i++) distance[i] = INF; AdjInsert(&graph, 1, 2, 5); AdjInsert(&graph, 1, 4, 8); AdjInsert(&graph, 2, 3, 11); AdjInsert(&graph, 3, 4, 7); Display(&graph); printf("\n"); Dijstra(&graph, 1); system("pause"); return 0; }<file_sep>#include <stdio.h> typedef struct _heap { int datarr[10]; int numofdata; }Heap; void init(Heap *ph) { ph->numofdata = 0; } int HisEmpty(Heap *ph) { if (ph->numofdata == 0) return 0; else return 1; } void Hinsert(Heap *ph, int data) { int idx = ph->numofdata + 1; while (idx != 1) { if (ph->datarr[idx / 2] > data) { ph->datarr[idx] = ph->datarr[idx / 2]; idx = idx / 2; } else break; } ph->datarr[idx] = data; ph->numofdata += 1; for (int i = 1; i <= 5; i++) printf("%d ", ph->datarr[i]); printf("\n"); } void Heapfy(Heap *ph, int i, int size) { int left = i * 2; int right = left + 1; int largest; int temp; if (left <= size && ph->datarr[left] < ph->datarr[i]) largest = left; else largest = i; if (right <= size && ph->datarr[right] < ph->datarr[largest]) largest = right; if (largest != i) { temp = ph->datarr[largest]; ph->datarr[largest] = ph->datarr[i]; ph->datarr[i] = temp; Heapfy(ph, largest, size); } } int Dequeue(Heap *ph) { int rdata = ph->datarr[1]; ph->datarr[1] = ph->datarr[ph->numofdata]; ph->numofdata -= 1; Heapfy(ph, 1, ph->numofdata); return rdata; } int main() { Heap heap; init(&heap); Hinsert(&heap, 2); Hinsert(&heap, 1); Hinsert(&heap, 3); Hinsert(&heap, 5); Hinsert(&heap, 4); for (int i = 1; i <= 5; i++) printf("%d ", Dequeue(&heap)); system("pause"); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct _node { int check; int node; int data; struct _node *next; }Node; typedef struct _adj { Node *arr[100]; }AdjacencyList; typedef struct _queue { Node *head; Node *tail; }Queue; void init(AdjacencyList *list, Queue *pq) { pq->head = NULL; pq->tail = NULL; for (int i = 0; i < 100; i++) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->check = 0; newNode->data = 0; newNode->next = NULL; newNode->node = i; list->arr[i] = newNode; } } int SisEmpty(Queue *pq) { if (pq->head == NULL) return 1; else return 0; } void AdjInsert(AdjacencyList *list, int node, int to, int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->check = 0; newNode->node = to; newNode->data = data; newNode->next = NULL; Node *cur = list->arr[node]->next; Node *before = cur; if (list->arr[node]->next == NULL) list->arr[node]->next = newNode; else { while (cur != NULL && cur->node != to) { before = cur; cur = cur->next; } before->next = newNode; } } void Enqueue(Queue *pq, int idx) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->check = 0; newNode->data = 0; newNode->node = idx; newNode->next = NULL; if (pq->head == NULL) pq->head = newNode; else pq->tail->next = newNode; pq->tail = newNode; } int Dequeue(Queue *pq) { if (SisEmpty(pq)) { exit(-1); } int data = pq->head->node; pq->head = pq->head->next; return data; } void BFS(AdjacencyList *list, Queue *pq,int visit[] ,int start) { Enqueue(pq, start); Node *temp; int idx; int element = 0; while (pq->head != NULL) { idx = Dequeue(pq); temp = list->arr[idx]; if (temp->check == 0) { list->arr[idx]->check = 1; visit[element++] = idx; } while (temp != NULL) { if (list->arr[temp->node]->check == 0) { Enqueue(pq, temp->node); temp = temp->next; } else temp = temp->next; } } } int main(void) { AdjacencyList list; Queue queue; int visit[100] = { 0 }; int sum; int node; int to; int edge; int len = 0; int idx; int num; init(&list, &queue); printf("ΓΡ°³Όφ: "); scanf("%d", &sum); for (int i = 0; i < sum; i++) { printf("node / edge: "); scanf(" %d %d", &node, &edge); for (int j = 0; j < edge; j++) { printf("to / num: "); scanf(" %d ,%d", &to, &num); fgetc(stdin); AdjInsert(&list, node, to, num); } } BFS(&list, &queue, visit, 1); while (visit[len] != 0) len++; for (int i = 0; i < len; i++) printf("%d ", visit[i]); printf("\n"); system("pause"); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define Hash_size 10; typedef struct _node { char str[10]; struct _node *next; }Node; Node *arr[10]; void Hashinit() { for (int i = 0; i < 10; i++) arr[i] = NULL; } int HashisEmpty(Node *temp) { if (temp == NULL) return 1; else return 0; } int Transform(char *str) { int number = 0;; while (*str) { number += *str++; } return number; } int HashGetValue(char *str) { printf("idx: %d\n", Transform(str) %10); return Transform(str) % 10; } void Enqueue(Node *data,int idx) { if (arr[idx] == NULL) arr[idx] = data; else { data->next = arr[idx]; arr[idx] = data; } } void HashTable_add(Node *key) { int idx = HashGetValue(key->str); Node *temp = arr[idx]; while (!HashisEmpty(temp)) { if (!strcmp(arr[idx]->str, key->str)) { printf("중복된 값이 존재합니다"); break; } else { Enqueue(key, idx); } temp = temp->next; } if (arr[idx] == NULL) Enqueue(key, idx); } void Display() { Node *temp; for (int i = 0; i < 10; i++) { temp = arr[i]; printf("[%d] ",i); while (!HashisEmpty(temp)) { printf("%s ", temp->str); temp = temp->next; } printf("\n"); } } int main(void) { Node *key; int n; Hashinit(); while (1) { key = (Node *)malloc(sizeof(Node)); key->next = NULL; printf("1.입력 || 2.조회 || 3.종료: "); scanf("%d", &n); if (n == 1) { printf("단어를 입력하세요: "); scanf("%s", key->str); HashTable_add(key); } else break; Display(); } system("pause"); return 0; } <file_sep>#include <stdio.h> void Swap(int arr[], int d1, int d2) { int temp = arr[d1]; arr[d1] = arr[d2]; arr[d2] = temp; } int Pivot(int arr[], int left, int right) { int Lidx = left+1; int mid = (left + right) / 2; int Ridx = right; int pivot = arr[left]; int i; while (Lidx < Ridx) { while (pivot > arr[Lidx]) Lidx++; while (pivot < arr[Ridx]) Ridx--; if (Lidx < Ridx) Swap(arr, Lidx, Ridx); } Swap(arr, left, Ridx); return Ridx; } void QuickSort(int arr[], int left, int right) { int pivot; if (left < right) { pivot = Pivot(arr,left,right); QuickSort(arr, left, pivot - 1); QuickSort(arr, pivot + 1, right); } } int main(void) { int arr[] = { 1,4,2,5,3,6,9,7 }; int i; int len = sizeof(arr) / sizeof(int); QuickSort(arr, 0, len - 1); for (i = 0; i < 8; i++) printf("%d ", arr[i]); system("pause"); }<file_sep>#include <stdio.h> #include <stdlib.h> #define MAX_LEN 100 #define TRUE 1 #define FALSE 0 typedef struct _node { int data; struct _node *left; struct _node *right; }Node; typedef struct { Node *heaparr[MAX_LEN]; int len; }Heap; int Parentidx(int idx) { return idx / 2; } int Lchildidx(int idx) { return idx * 2; } int Rchildidx(int idx) { return Lchildidx(idx) + 1; } void init(Heap *h) { h->len = 0; } Node *MakenewNode(int data, Node *left, Node *right) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->left = left; newNode->right = right; return newNode; } void insert_min_heap(Heap *arr, Node *data) { int i = ++(arr->len); while (i != 1) { if (arr->heaparr[Parentidx(i)]->data > data->data) { arr->heaparr[i] = arr->heaparr[Parentidx(i)]; i = Parentidx(i); } else break; } arr->heaparr[i] = data; } //부모와 자식간의 우선순위를 비교하는 코드 void heapfy(Heap *arr, int i, int size) { int left = Lchildidx(i); int right = Rchildidx(i); int small; Node *temp; //왼쪽 자식노드와 부모 노드의 우선순위 비교 if (left <= size && arr->heaparr[left]->data < arr->heaparr[i]->data) small = left; else small = i; //왼쪽자식노드와 부모노드의 우선순위 계산이 된 small과 오른쪽 자식의 우선순위 비교 if (right <= size && arr->heaparr[right]->data < arr->heaparr[small]->data) small = right; //부모 노드보다 자식 값이 작다면 swap 후, upheap으로 구성 if (small != i) { temp = arr->heaparr[i]; arr->heaparr[i] = arr->heaparr[small]; arr->heaparr[small] = temp; heapfy(arr, small, size); } } //heapfy를 이용하여 삭제 후, 정렬 Node *delete(Heap *heap) { Node *root = heap->heaparr[1]; //반환할 root 노드를 저장. heap->heaparr[1] = heap->heaparr[heap->len]; // root자리에 마지막 값 삽입 heap->len -= 1;// 삭제로 인한 size 감소 heapfy(heap, 1, heap->len); // root가 된 마지막 값이 down heap을 통해 정렬 return root; } void huffman(int feq[], int len) { Heap heap; Node *e; int i; init(&heap); for (i = 0; i < len; i++) { Node *newNode = MakenewNode(0, NULL, NULL); newNode->data = feq[i]; insert_min_heap(&heap, newNode); } for (i = 1; i <= len - 1; i++) { e = MakenewNode(0, NULL, NULL); e->left = delete(&heap); e->right = delete(&heap); e->data = e->left->data + e->right->data; insert_min_heap(&heap, e); } e = delete(&heap); printf("%d ", e->data); free(e); } int main(void) { int feq[] = { 15,12,8,6,4 }; huffman(feq, 5); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <memory.h> typedef struct _node { int data; struct _node *left_child; struct _node *right_child; }AVLtree; AVLtree *root; AVLtree *rotate_right(AVLtree *parent) { AVLtree *child = parent->left_child; parent->left_child = child->right_child; child->right_child = parent; return child; } AVLtree *rotate_left(AVLtree *parent) { AVLtree *child = parent->right_child; parent->right_child = child->left_child; child->left_child = parent; return child; } AVLtree *rotate_right_left(AVLtree *parent) { AVLtree *child = parent->right_child; parent->right_child = child->left_child; return rotate_left(parent); } AVLtree *rotate_left_right(AVLtree *parent) { AVLtree *child = parent->left_child; parent->left_child = child->right_child; return rotate_right(parent); } int get_heights(AVLtree *node) { int height = 0; if (node != NULL) height = 1 + max(get_heights(node->left_child), get_heights(node->right_child)); return height; } int get_hight_diff(AVLtree *node) { if (node == NULL) return 0; return get_heights(node->left_child) - get_heights(node->right_child); } AVLtree *revalance(AVLtree **node) { int height_diff = get_hight_diff(*node); if (height_diff > 1) { if (get_hight_diff((*node)->left_child) > 0) *node = rotate_right(*node); else *node = rotate_left_right(*node); } else if (height_diff < -1) { if (get_hight_diff((*node)->right_child) < 0) *node = rotate_left(*node); else *node = rotate_right_left(*node); } return *node; } AVLtree *avl_add(AVLtree **root, int new_key) { if (*root == NULL) { *root = (AVLtree *)malloc(sizeof(AVLtree)); if (*root == NULL) { printf("메모리 할당 에러\n"); exit(1); } (*root)->data = new_key; (*root)->left_child = (*root)->right_child = NULL; } else if (new_key < (*root)->data) { (*root)->left_child = avl_add(&((*root)->left_child), new_key); (*root) = revalance(root); } else if (new_key > (*root)->data) { (*root)->right_child = avl_add(&((*root)->right_child), new_key); (*root) = revalance(root); } else { printf("중복된 키 에러\n"); exit(1); } return *root; } AVLtree *avl_search(AVLtree *node, int key) { if (node == NULL) return NULL; printf("%d ", node->data); if (key == node->data) return node; else if (key < node->data) return avl_search(node->left_child, key); else return avl_search(node->right_child, key); } void Inorder(AVLtree **root) { if (*root == NULL) return; Inorder(&(*root)->left_child); printf("%d ", (*root)->data); Inorder(&(*root)->right_child); } int main(void) { avl_add(&root,8); avl_add(&root, 9); avl_add(&root, 10); avl_add(&root, 2); avl_add(&root, 1); avl_add(&root, 5); avl_add(&root, 3); avl_add(&root, 6); avl_add(&root, 4); avl_add(&root, 7); avl_add(&root, 11); avl_add(&root, 12); printf("AVL 탐색: "); avl_search(root, 12); printf("\n\n중위 순회: "); Inorder(&root); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct _node { int data; struct _node *left; struct _node *right; }Node; Node *makeNode(int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } void insertTree(Node *main,int data) { Node *ed = NULL; Node *ing = main; Node *newNode; while (ing != NULL) { if (data < ing->data) { ed = ing; ing = ing->left; } else { ed = ing; ing = ing->right; } } newNode = makeNode(data); if (newNode->data < ed->data) ed->left = newNode; else ed->right = newNode; } int deleteTree(Node **head, int data) { Node *ed = *head; Node *ing = *head; Node *temp; int rdata; while (ing->data != data) { if (data < ing->data) { ed = ing; ing = ing->left; } else { ed = ing; ing = ing->right; } } if (ing->data < ed->data) { if (ing->left == NULL && ing->right == NULL) { rdata = ing->data; ed->left = NULL; free(ed->left); return rdata; } else if (ing->left != NULL && ing->right == NULL) { rdata = ing->data; ed->left = ing->left; return rdata; } else if (ing->left == NULL && ing->right != NULL) { rdata = ing->data; ed->left = ing->right; return rdata; } else { temp = ing ->left; ed->left = ing->right; ing = ing->right->left; if (ing == NULL) ed->left->left = temp; else { while (ing != NULL) { ed = ing; ing = ing->left; } ed->left = temp; } return data; } } else if (ing->data > ed->data) { if (ing->left == NULL && ing->right == NULL) { rdata = ing->data; ed->right = NULL; free(ed->right); return rdata; } else if (ing->left != NULL && ing->right == NULL) { rdata = ing->data; ed->right = ing->left; return rdata; } else if (ing->left == NULL && ing->right != NULL) { rdata = ing->data; ed->right = ing->right; return rdata; } else { temp = ing->left; ed->right = ing->right; ing = ing->right->left; if(ing == NULL) ed->right->left = temp; else { while (ing != NULL) { ed = ing; ing = ing->left; } ed->left =temp; } return data; } } else { temp = ing->left; *head = ing->right; if (ed->right->left != NULL) { ing = ing->right->left; while (ing != NULL) { ed = ing; ing = ing->left; } ed->left = temp; } else { ing->right->left = temp; } return data; } } void inOrder(Node *head) { if (head == NULL) return; else { printf("%d ", head->data); inOrder(head->left); inOrder(head->right); } } int main(void) { Node *head = makeNode(15); insertTree(head, 10); insertTree(head, 5); insertTree(head, 13); insertTree(head, 4); insertTree(head, 7); insertTree(head, 12); insertTree(head, 14); insertTree(head, 20); insertTree(head, 19); insertTree(head, 25); insertTree(head, 22); insertTree(head, 27); inOrder(head); printf("\n"); printf("%d\n",deleteTree(&head, 27)); inOrder(head); printf("\n"); system("pause"); return 0; }
269872e1e61e144d43a14d3aca23994963a935c9
[ "C" ]
20
C
tjrkdgnl/dataStructure2
7bbc835fd3eca9b9fbde05d80a41af9ef4163527
3d274d6417ca5f16a9e73ac06144156d1959099a
refs/heads/master
<file_sep>//CODE GOES HERE import {combineReducers} from "redux"; import WeatherReducer from "./reducer_weather"; export default combineReducers({ weather: WeatherReducer }); //CODE GOES HERE //CODE GOES HERE //CODE GOES HERE <file_sep>import React, { Component } from 'react'; // import SearchBar from "./search_bar.jsx"; // import WeatherData from "./weather_data.jsx"; // import WeatherList from "./weather_list.jsx"; //CODE GOES HERE export default class App extends Component { render(){ return ( <div> Test </div> ); } } //CODE GOES HERE //CODE GOES HERE //CODE GOES HERE
40456b31bd26caea124c37f5de1af8a83803e693
[ "JavaScript" ]
2
JavaScript
rukaroa/redux
69da1f8c1314fa1361466adb6757578f6f1b2361
3816457795e08563d53ac5f382735846146176eb
refs/heads/master
<repo_name>mustafamg/nestjs-mqtt-example<file_sep>/src/app.controller.ts import { Controller, Get } from '@nestjs/common'; import { Ctx, MessagePattern, MqttContext, Payload, } from '@nestjs/microservices'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} //testtopic/1 @MessagePattern('testtopic/1') getNotifications(@Payload() data: number[], @Ctx() context: MqttContext) { console.log(`Topic: ${context.getTopic()}`); } } <file_sep>/src/main.ts import { Logger } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { MicroserviceOptions } from '@nestjs/microservices'; import { Transport } from '@nestjs/microservices/enums/transport.enum'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.createMicroservice<MicroserviceOptions>( AppModule, { transport: Transport.MQTT, options: { hostname: 'broker.hivemq.com', port: 1883, clientId: 'clientId-nWJplWkEtYsd', protocol: 'tcp', } }, ); await app.listen(() => { Logger.log('Microservice is listining...'); }); } bootstrap();
b72e492587720b1af31db025b2f78b98b66516eb
[ "TypeScript" ]
2
TypeScript
mustafamg/nestjs-mqtt-example
973350d7f011ee44edf6a93458451fbfd303c6ca
e8592defcdf50abf5d8319447a8b707934cb9140
refs/heads/master
<repo_name>MaxJeong/Hospital-Android-App<file_sep>/src/backend/Patient.java package backend; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import frontend.PatientInfo; import android.annotation.SuppressLint; /** * A representation of a Patient. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * */ public class Patient implements Doctor, Serializable{ private static final long serialVersionUID = 6743028506959888117L; private Map<Date, VitalSigns> vitalSignsMap; private Map<Date, Symptoms> symptomsMap; private Map<Date, Prescription> prescriptionMap; private Urgency urgency; @SuppressLint("SimpleDateFormat") SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); //date when the patient has been seen by a doctor. private Date seenDate; //date when the patient was registered to a hospital. private Date admissionDate; private String name; private String dob; //dob is date of birth, in the format year/month/day private int hcn; //hcn is health card number private int age; /** * Creates a patient object with nothing but their basic information * stored. * @param date Date the patient was admitted * @param name Name of the patient * @param dob Date of birth of the patient * @param hcn Health Card Number of the patient * @param age Age of the patient */ public Patient(Date date, String name, String dob, int hcn, int age) { this.vitalSignsMap = new HashMap<Date, VitalSigns>(); this.symptomsMap = new HashMap<Date, Symptoms>(); this.prescriptionMap = new HashMap<Date, Prescription>(); this.urgency = new Urgency(); this.name = name; this.dob = dob; this.hcn = hcn; this.age = age; this.seenDate = null; admissionDate = date; } /** * Creates a patient object that's been seen by a doctor. * @param date Date the patient was admitted * @param name Name of the patient * @param dob Date of birth of the patient * @param hcn Health Card Number of the patient * @param age Age of the patient * @param seenbydoctor Date that the patient has been seen by a doctor. */ public Patient(Date date, String name, String dob, int hcn, int age, Date seenbydoctor) { this.vitalSignsMap = new HashMap<Date, VitalSigns>(); this.symptomsMap = new HashMap<Date, Symptoms>(); this.urgency = new Urgency(); this.name = name; this.dob = dob; this.hcn = hcn; this.age = age; this.seenDate = seenbydoctor; admissionDate = date; } /** * Sets this Patient's name * @param name the name of the patient */ public void setName(String name){ this.name = name; } /** * Sets this Patient's date of birth * @param year year of birthday * @param month month of birthday * @param day day of birthday */ public void setDOB(String year, String month, String day){ this.dob = year+"/"+month+"/"+day; } /** * Sets this Patient's Health Card Number * @param hcn the Patient's health card number */ public void setHCN(int hcn){ this.hcn = hcn; } /** * Sets this Patient's age * @param age the patient's age */ public void setAge(int age){ this.age = age; } /** * Returns a Map of Date to VitalSigns for this Patient. * @return Map of Date to VitalSigns for this Patient. */ public Map<Date, VitalSigns> getVitalSignsMap() { return vitalSignsMap; } /** * Returns a Map of Date to Symptoms for this Patient. * @return Map of Date to Symptoms */ public Map<Date, Symptoms> getSymptomsMap() { return symptomsMap; } /** * Returns the map of date to prescriptions for this patient * @return Map of date to prescription */ public Map<Date, Prescription> getPrescriptionMap(){ return prescriptionMap; } /** * Returns the urgency category and point for this Patient. * @return the urgency category and point for this Patient. */ public Urgency getUrgency() { return urgency; } public Date getAdmissionDate() { return admissionDate; } /** * Returns the name of this Patient. * @return the name of this Patient. */ public String getName() { return name; } /** * Returns the date of birth for this Patient. * @return the date of birth for this Patient. */ public String getDob() { return dob; } /** * Returns the health card number for this Patient. * @return the health card number for this Patient. */ public int getHcn() { return hcn; } /** * Returns the age for this Patient. * @return the age for this Patient. */ public int getAge() { return age; } /** * Adds the recorded time of symptoms and the actual symptoms for this * Patient. * @param symptoms the symptoms that needs to be added. */ public void addSymptoms(Symptoms symptoms) { Date symptomsRecordTime = symptoms.getTimeOfRecording(); symptomsMap.put(symptomsRecordTime, symptoms); // Write to patient.symptoms file } /** * Adds the recorded time of vital signs and the actual vital signs for * this Patient. * @param vitalSigns the vital signs that needs to be added. */ public void addVitalSigns(VitalSigns vitalSigns) { Date vitalRecordTime = vitalSigns.getTimeOfRecording(); vitalSignsMap.put(vitalRecordTime, vitalSigns); this.urgency = new Urgency(this, vitalSigns); // Write to patient.vitalsigns file } /** * Adds an additional prescription for this patient, mapped with it's recording time as a key * @param prescription the prescription to be added */ public void addPrescription(Prescription prescription) { Date prescriptionRecordTime= prescription.getTimeOfRecording(); prescriptionMap.put(prescriptionRecordTime, prescription); } /** * Returns a string representation of Patient. * Contains their basic information. */ public String toString() { String s; if (this.seenDate==null){ s = this.getName() + " " + this.getDob() + " " + this.getHcn() + " " + this.getAge() + " " + dateformat.format(this.getAdmissionDate()); } else { s = this.getName() + " " + this.getDob() + " " + this.getHcn() + " " + this.getAge() + " " + dateformat.format(this.getAdmissionDate()) + " " + PatientInfo.dateandtimeformat.format(this.seenDate); } return s; } @Override public void setDateSeenByDoctor(Date d) { // TODO Auto-generated method stub seenDate = d; } /** * Returns the date seen by a doctor for this Patient. * @return the date seen by a doctor for this Patient. */ public Date getDateSeenByDoctor() { return seenDate; } } <file_sep>/README.md # Hospital-Android-App<file_sep>/src/frontend/PatientVS.java package frontend; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import backend.HospitalRecord; import backend.Nurse; import backend.Patient; import backend.VitalSigns; import com.example.hospitalapplication.R; public class PatientVS extends Fragment{ Patient patient; Nurse nurse = new Nurse(); String FILENAME = "patientfile.txt"; @SuppressLint("SimpleDateFormat") public static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); public static SimpleDateFormat dateandtimeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ArrayList<String> displayVS = new ArrayList<String>(); ArrayAdapter<String> VSListAdapter; private ListView VSlv; TextView DateSeen,Urgency; View rootView; //This is a helper method that checks if the input string //contains only numeric characters public static boolean isNumeric(String str) { try { @SuppressWarnings("unused") double d = Double.parseDouble(str); } catch(NumberFormatException nfe) { return false; } return true; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.patient_vital_signs, container, false); // Get Patient from previous activity int key = getActivity().getIntent().getExtras().getInt("PatientHCNKey"); patient = HospitalRecord.getListOfPatients().get(Integer.toString(key)); boolean isNurse = getActivity().getIntent().getExtras().getBoolean("isNurse"); // Setup OnClickListener Button updateVS = (Button) rootView.findViewById(R.id.BTupdate_vital_signs); updateVS.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()){ case R.id.BTupdate_vital_signs: // Retrieve all fields from EditText EditText Temperature = (EditText) rootView.findViewById(R.id.ETtemperature); EditText BPSystolic = (EditText) rootView.findViewById(R.id.ETSystolicBP); EditText BPDiastolic = (EditText) rootView.findViewById(R.id.ETDiastolicBP); EditText HeartRate = (EditText) rootView.findViewById(R.id.ETHeartRate); // Check for correct format if (isNumeric(Temperature.getText().toString())==false){ Context context = getActivity(); CharSequence text = "Temperature can only contain numeric characters"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (isNumeric(BPSystolic.getText().toString())==false){ Context context = getActivity(); CharSequence text = "Systolic BP can only contain numeric characters"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (isNumeric(BPDiastolic.getText().toString())==false){ Context context = getActivity(); CharSequence text = "Diastolic BP can only contain numeric characters"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (isNumeric(HeartRate.getText().toString())==false){ Context context = getActivity(); CharSequence text = "Heart Rate can only contain numeric characters"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else { // Call backend function VitalSigns vitalsigns = nurse.updateVitalSigns(patient, new Date(), Double.parseDouble(Temperature.getText().toString()), (int)Double.parseDouble(BPSystolic.getText().toString()), (int)Double.parseDouble(BPDiastolic.getText().toString()), (int)Double.parseDouble(HeartRate.getText().toString())); // Clear EditTexts Temperature.setText(""); BPSystolic.setText(""); BPDiastolic.setText(""); HeartRate.setText(""); // Update List of VitalSigns displayVS.add(vitalsigns.displayString()); VSListAdapter.notifyDataSetChanged(); break; } } } }); // Setup List of Vital Signs VSlv = (ListView) rootView.findViewById(R.id.LISTvitalSigns); Iterator<Map.Entry<Date, VitalSigns>> ITvitalsigns = patient.getVitalSignsMap().entrySet().iterator(); while (ITvitalsigns.hasNext()){ Entry<Date, VitalSigns> VSSet = ITvitalsigns.next(); displayVS.add(VSSet.getValue().displayString()); } VSListAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, displayVS); VSlv.setAdapter(VSListAdapter); if (!isNurse) { updateVS.setVisibility(View.INVISIBLE); } return rootView; } } <file_sep>/src/manager/PatientManager.java package manager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Locale; import java.util.Scanner; /** * Manages the reading and writing of Patient objects into or out of text * files. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * @param <T> Patient */ public class PatientManager<T> extends Manager<T>{ /** * Locates or creates the file to be written or read from. * @param dir Directory of where the file is to be located. * @param FILENAME Name of file. * @throws IOException * @throws ParseException */ public PatientManager(File dir, String FILENAME) throws IOException, ParseException { super(dir, FILENAME); // TODO Auto-generated constructor stub } @Override public void readIntoFile(Scanner linescanner) { // TODO Auto-generated method stub String data[]; int j = 0; while (linescanner.hasNext()){ String line = linescanner.nextLine(); System.out.println(j++ +": "+line); data = line.split(" "); try { nurse.recordPatientData(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(data[4]), data[0], data[1], Integer.parseInt(data[2]), Integer.parseInt(data[3])); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void writeIntoFile(Iterator<T> iterator, FileOutputStream writeStream) throws IOException { // TODO Auto-generated method stub while (iterator.hasNext()){ writeStream.write(iterator.next().toString().getBytes()); if (iterator.hasNext()) writeStream.write("\r\n".getBytes()); } } } <file_sep>/src/frontend/PatientPrescription.java package frontend; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import backend.HospitalRecord; import backend.Patient; import backend.Physician; import backend.Prescription; import com.example.hospitalapplication.R; public class PatientPrescription extends Fragment implements OnClickListener{ private ArrayList<String> displayPrescription = new ArrayList<String>(); private ArrayAdapter<String> ListAdapter; private ListView lv; Patient patient; Physician p; View rootView; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.patient_prescription, container, false); Button add = (Button) rootView.findViewById(R.id.BTaddprescription); add.setOnClickListener(this); // Get Patient from previous activity int key = getActivity().getIntent().getExtras().getInt("PatientHCNKey"); patient = HospitalRecord.getListOfPatients().get(Integer.toString(key)); boolean isNurse = getActivity().getIntent().getExtras().getBoolean("isNurse"); if (isNurse){ add.setVisibility(View.INVISIBLE); } else { p = new Physician(); } // Setup List Adapters and List View lv = (ListView) rootView.findViewById(R.id.LVPrescription); displayPrescription.add(" "); ListAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, displayPrescription); lv.setAdapter(ListAdapter); // Initialize diplayPrescription updateList(); return rootView; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.BTaddprescription: EditText ETprescription_data = (EditText) rootView.findViewById(R.id.ETPrescription); String medName = ETprescription_data.getText().toString(); EditText ETmed_instruction = (EditText) rootView.findViewById(R.id.ETMedicationInstructions); String med_instruction =ETmed_instruction.getText().toString(); if (!medName.equals("") && !med_instruction.equals("")){ p.updatePrescription(new Date(), patient, medName, med_instruction); updateList(); ETprescription_data.setText(""); ETmed_instruction.setText(""); } else { Toast.makeText(getActivity(), "Can't be empty string", Toast.LENGTH_LONG).show(); } } } public void updateList(){ displayPrescription.clear(); Iterator<Prescription> it = patient.getPrescriptionMap().values().iterator(); while (it.hasNext()){ displayPrescription.add(it.next().toString()); } ListAdapter.notifyDataSetChanged(); } } <file_sep>/src/backend/Prescription.java package backend; import android.annotation.SuppressLint; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; /** * Prescription object which stores, and has getters for a prescription * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * */ public class Prescription implements Serializable{ /** * */ private static final long serialVersionUID = -4792449139582731182L; @SuppressLint("SimpleDateFormat") SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd"); private Date timeOfRecording; private String medicationName; private String medicationInstructions; /** * Constructor for the Prescription object * @param medName Name of the meds * @param medInstructions Instructions for the meds * @param date date the prescription was created on */ public Prescription(String medName, String medInstructions, Date date){ this.timeOfRecording = date; this.medicationName = medName; this.medicationInstructions = medInstructions; } /** * Returns the time the prescription was created * @return the time the prescription was created */ public Date getTimeOfRecording() { return this.timeOfRecording; } /** * Returns the name of the medication prescribed * @return the name of the medication prescribed */ public String getMedicationName() { return this.medicationName; } /** * Returns the instructions to go with the medication * @return the instructions to go with the medication */ public String getMedicationInstructions() { return this.medicationInstructions; } /** * Returns a string representation of the prescriptionq * @return a string representation fo the prescription */ public String toString() { return "Date: "+ dateformat.format(timeOfRecording) + "\nMedication: " + medicationName + "\nInstructions: " + medicationInstructions; } } <file_sep>/src/manager/AccountManager.java package manager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Scanner; import java.text.ParseException; import backend.Account; /** * Manages reading and writing all of nurse and physician accounts. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * */ public class AccountManager<T> extends Manager<T>{ public Map<String, Account> credentials = new HashMap<String, Account>(); public AccountManager(File dir, String FILENAME) throws IOException, ParseException { super(dir, FILENAME); } @Override public void readIntoFile(Scanner linescanner) { while (linescanner.hasNext()) { String line = linescanner.nextLine(); if (!line.equals("")) { final String[] account = line.split(" "); Account ac = new Account(account[0], account[1], Boolean.parseBoolean(account[2])); credentials.put(account[0], ac); } } } @Override public void writeIntoFile(Iterator<T> iterator, FileOutputStream writeStream) throws Exception { while (iterator.hasNext()) { writeStream.write(iterator.next().toString().getBytes()); writeStream.write("\r\n".getBytes()); } } public Boolean authenticate(String username, String password){ if (credentials.containsKey(username) && credentials.get(username).getPassword().equals(password)){ return credentials.get(username).isNurse(); } else { return null; } } } <file_sep>/src/manager/PrescriptionManager.java package manager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Scanner; import backend.HospitalRecord; import backend.Patient; import backend.Prescription; /** * Manages reading and writing all of a patient's prescriptions to file * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * @param <T> Patient */ public class PrescriptionManager<T> extends Manager<T> { /** * Constructor for the PrescriptionManager class * @param dir the location for the file for the prescriptions * @param FILENAME the name of the file for the prescriptions * @throws IOException * @throws ParseException */ public PrescriptionManager(File dir, String FILENAME) throws IOException, ParseException { super(dir, FILENAME); } @Override protected void readIntoFile(Scanner linescanner){ while (linescanner.hasNext()){ String stringline = linescanner.nextLine(); if (!stringline.equals("")){ final String[] presData = stringline.split(" "); Patient patient = HospitalRecord.getListOfPatients() .get(presData[0]); String presInst = presData[3].replace("_", " "); String[] date = presData[1].split("-"); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, Integer.parseInt(date[0])); cal.set(Calendar.MONTH, Integer.parseInt(date[1])); cal.set(Calendar.DATE, Integer.parseInt(date[2])); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); final Date fixedDate = cal.getTime(); physician.updatePrescription(fixedDate, patient, presData[2], presInst); } } } @Override protected void writeIntoFile(Iterator<T> iter, FileOutputStream writeStream) throws Exception { // TODO Auto-generated method stub while (iter.hasNext()){ Patient patient = (Patient) iter.next(); String hcn = Integer.toString(patient.getHcn()); Iterator<Prescription> itertwo = patient.getPrescriptionMap() .values().iterator(); while (itertwo.hasNext()){ Prescription presToWrite = itertwo.next(); String presString = presToWrite.getTimeOfRecording() + " " + presToWrite.getMedicationName() + " " + presToWrite.getMedicationInstructions().replace(" ", "_"); writeStream.write((hcn+" "+presString).getBytes()); writeStream.write(("\r\n").getBytes()); } } } }<file_sep>/src/backend/Doctor.java package backend; import java.util.Date; /** * An interface for the date the patient has been seen by a doctor. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * */ public interface Doctor { /** * Returns the date. * @return the date */ public Date getDateSeenByDoctor(); /** * Sets the date seen by doctor */ public void setDateSeenByDoctor(Date d); } <file_sep>/src/manager/VitalSignsManager.java package manager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Scanner; import backend.HospitalRecord; import backend.Patient; import backend.VitalSigns; /** * Manages the reading and writing of Symptom objects into or out of text * files. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * @param <T> Patient */ public class VitalSignsManager<T> extends Manager<T>{ /** * Locates or creates the file to be written or read from. * @param dir Directory of where the file is to be located. * @param FILENAME Name of file. * @throws IOException * @throws ParseException */ public VitalSignsManager(File dir, String FILENAME) throws IOException, ParseException { super(dir, FILENAME); // TODO Auto-generated constructor stub } @Override public void readIntoFile(Scanner linescanner) { // TODO Auto-generated method stub while (linescanner.hasNext()){ String curLine = linescanner.nextLine(); if (!curLine.equals("")){ final String[] data = curLine.split(" "); Patient patient = HospitalRecord.getListOfPatients() .get(data[0]); String[] date = data[1].split("-"); Calendar cal = Calendar.getInstance(); System.out.println("FormatDate:"+Integer.parseInt(date[0]) +Integer.parseInt(date[1])+Integer.parseInt(date[2])); cal.set(Calendar.YEAR, Integer.parseInt(date[0])); cal.set(Calendar.MONTH, Integer.parseInt(date[1])); cal.set(Calendar.DATE, Integer.parseInt(date[2])); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); final Date j = cal.getTime(); nurse.updateVitalSigns(patient, j, Double.parseDouble(data[2]), Integer.parseInt(data[3]), Integer.parseInt(data[4]), Integer.parseInt(data[5])); } } } @Override public void writeIntoFile(Iterator<T> iterator, FileOutputStream writeStream) throws IOException { // TODO Auto-generated method stub while (iterator.hasNext()){ Patient patient = (Patient) iterator.next(); String hcn = Integer.toString(patient.getHcn()); Iterator<VitalSigns> it = patient.getVitalSignsMap() .values().iterator(); while (it.hasNext()){ writeStream.write((hcn+" "+it.next().toString()).getBytes()); writeStream.write(("\r\n").getBytes()); } } } } <file_sep>/src/backend/Urgency.java package backend; import java.io.Serializable; /** * Urgency object that stores points of a patient based on the hostpial's * policy and the 'urgent' category that they fall under. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * */ public class Urgency implements Serializable{ /** * */ private static final long serialVersionUID = -8371670428536609050L; private int points; private String patientCategory; /** * Constructor for this Urgency Object. * @param patient Patient object that this Urgency Object will correspond * to. */ public Urgency(Patient patient, VitalSigns vs) { points = 0; pointAllocation(patient, vs); } /** * Empty Constructor that sets point to 0. */ public Urgency(){ points = 0; setPatientCategory(); } /** * Allocates points for patient based on Hospital Policy. * @param patient Patient object */ private void pointAllocation(Patient patient, VitalSigns vs){ if (patient.getAge() < 2){ points++; } if (vs.getTemperature() >= 39.0){ points++; } if (vs.getBloodPressure().getSystolicBP() >= 140 || vs.getBloodPressure().getDiastolicBP() >= 90){ points++; } if (vs.getHeartRate()>=100 || vs.getHeartRate()<=50){ points++; } setPatientCategory(); } /** * Sets patientCategory according to points. */ private void setPatientCategory(){ switch(points){ case 0: patientCategory = "No VitalSigns"; break; case 1: patientCategory = "Non Urgent"; break; case 2: patientCategory = "Less Urgent"; break; case 3: case 4: patientCategory = "Urgent"; break; } } /** * Gets the category of the patient that he/she falls under. * @return String patientCategory */ public String getPatientCategory(){ return patientCategory; } /** * Gets the amount of urgency points. * @return int points */ public int getPoints(){ return points; } /** * Returns this Urgency object as a String, contains the category and * points. */ public String toString(){ return patientCategory + " " + points + " points"; } }<file_sep>/src/frontend/HomeScreen.java package frontend; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.Toast; import backend.HospitalRecord; import backend.Patient; import com.example.hospitalapplication.R; public class HomeScreen extends Activity implements OnItemClickListener, OnClickListener{ ArrayList<String> displayHCN = new ArrayList<String>(); ArrayList<String> HCNList = new ArrayList<String>(); ArrayList<Patient> PatientList = new ArrayList<Patient>(); ArrayAdapter<String> ListAdapter; String[] HCNArray; Patient[] PatientArray; private ListView lv; EditText inputSearch; boolean isNurse; int sortSelected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_screen); // Setup New Patient button Button newpatient = (Button) findViewById(R.id.BTnewpatient); newpatient.setOnClickListener(this); Button save = (Button) findViewById(R.id.BTSave); save.setOnClickListener(this); isNurse = getIntent().getExtras().getBoolean("isNurse"); if (!isNurse) { newpatient.setVisibility(View.INVISIBLE); } // Setup List Adapters and List View lv = (ListView) findViewById(R.id.list); inputSearch = (EditText) findViewById(R.id.inputSearch); displayHCN.add(" "); // Empty placeholder. ListAdapter = new ArrayAdapter<String>(this, android.R.layout .simple_list_item_1, displayHCN); lv.setAdapter(ListAdapter); lv.setOnItemClickListener(this); // Setup Patient Search Function inputSearch.addTextChangedListener(new TextWatcher(){ public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user changed the Text HomeScreen.this.ListAdapter.getFilter().filter(cs); } public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } }); // Initialize ListView with patient data Iterator<Map.Entry<String, Patient>> listofpatients = HospitalRecord .getListOfPatients().entrySet().iterator(); while (listofpatients.hasNext()){ Entry<String, Patient> currentRecord = listofpatients.next(); HCNList.add(currentRecord.getValue().getName()+" "+ currentRecord .getValue().getDob()+" "+currentRecord.getKey()); PatientList.add(currentRecord.getValue()); } HCNArray = HCNList.toArray(new String[HCNList.size()]); PatientArray = PatientList.toArray(new Patient[PatientList.size()]); displayHCN.clear(); displayHCN.addAll(HCNList); ListAdapter.notifyDataSetChanged(); sortSelected = 0; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub Intent patientViewIntent = new Intent(this, PatientMasterSwipe.class); patientViewIntent.putExtra("PatientHCNKey", PatientArray[position] .getHcn()); patientViewIntent.putExtra("isNurse", isNurse); startActivityForResult(patientViewIntent, 1); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.BTnewpatient: Intent intent = new Intent(this, NewPatient.class); intent.putExtra("isNurse", isNurse); startActivityForResult(intent, 1); break; case R.id.BTSave: try { LoginAuthentication.pmanager.writeToFile(HospitalRecord .getListOfPatients().values().iterator()); LoginAuthentication.vsmanager.writeToFile(HospitalRecord .getListOfPatients().values().iterator()); LoginAuthentication.smanager.writeToFile(HospitalRecord .getListOfPatients().values().iterator()); LoginAuthentication.prmanager.writeToFile(HospitalRecord .getListOfPatients().values().iterator()); Toast.makeText(getApplicationContext(), "Saved", Toast .LENGTH_LONG).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * OnClickListener for group of radio buttons * @param view */ public void onRadioButtonClicked(View view){ boolean checked = ((RadioButton) view).isChecked(); switch(view.getId()){ case R.id.RBAll: if (checked){ sortSelected = 0; updateList(HospitalRecord.getListOfPatients().entrySet() .iterator()); } break; case R.id.RBTime: if (checked){ sortSelected = 1; updateList(HospitalRecord.getListOfEarliestArrivingPatients() .entrySet().iterator()); } break; case R.id.RBUrgency: if (checked){ sortSelected = 2; updateList(HospitalRecord.getListOfMostUrgentPatients() .entrySet().iterator()); } break; } } public void updateList(Iterator<Map.Entry<String, Patient>> listofpatients){ // Empty our current Lists HCNList.clear(); PatientList.clear(); while (listofpatients.hasNext()){ Entry<String, Patient> currentRecord = listofpatients.next(); HCNList.add(currentRecord.getValue().getName()+" "+ currentRecord .getValue().getDob()+" "+currentRecord.getKey()); PatientList.add(currentRecord.getValue()); } PatientArray = PatientList.toArray(new Patient[PatientList.size()]); displayHCN.clear(); displayHCN.addAll(HCNList); ListAdapter.notifyDataSetChanged(); } protected void onActivityResult(int requestCode, int resultCode , Intent data) { switch(sortSelected){ case 0: updateList(HospitalRecord.getListOfPatients().entrySet() .iterator()); break; case 1: updateList(HospitalRecord.getListOfEarliestArrivingPatients() .entrySet().iterator()); break; case 2: updateList(HospitalRecord.getListOfMostUrgentPatients() .entrySet().iterator()); break; } } } <file_sep>/src/frontend/RegisterScreen.java package frontend; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import backend.Account; import com.example.hospitalapplication.R; public class RegisterScreen extends Activity { private RadioButton radioTypeButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register_screen); } public void submitRegister(View view) throws Exception{ EditText userText = (EditText) findViewById(R.id.usernameSubmit); String username = userText.getText().toString(); EditText passwordText = (EditText) findViewById(R.id.passwordSubmit); String password = <PASSWORD>(); RadioGroup nurseOrPhysicianGroup = (RadioGroup) findViewById(R.id.radioGroup1); int selectedbuttonID = nurseOrPhysicianGroup.getCheckedRadioButtonId(); radioTypeButton = (RadioButton) findViewById(selectedbuttonID); String nurseOrPhysician = radioTypeButton.getText().toString(); Account ac; if (nurseOrPhysician.equals("Nurse")){ ac = new Account(username, password, true); } else { ac = new Account(username, password, false); } // Add to logical data structure LoginAuthentication.acmanager.credentials.put(username, ac); // Write to file LoginAuthentication.acmanager.writeToFile(LoginAuthentication .acmanager.credentials.values().iterator()); Intent intent = new Intent(this, LoginAuthentication.class); startActivity(intent); } } <file_sep>/src/backend/BloodPressure.java package backend; import java.io.Serializable; /** * A representation of BloodPressure measured in systolic and diastolic. * @author SeongMinJeong, JunaidPatel, EricCyr, JackYiu, YiChenZhu * */ public class BloodPressure implements Serializable{ /** * */ private static final long serialVersionUID = 6919692996219657546L; public Integer systolicBP; public Integer diastolicBP; /** * Creates a new BloodPressure with the given systolicBP and diastolicBP. * @param systolicBP * @param diastolicBP */ public BloodPressure(Integer systolicBP, Integer diastolicBP) { this.systolicBP = systolicBP; this.diastolicBP = diastolicBP; } /** * Returns systolicBP * @return systolicBP */ public Integer getSystolicBP() { return systolicBP; } /** * Returns diastolicBP * @return diastolicBP */ public Integer getDiastolicBP() { return diastolicBP; } /** * Sets systolicBP for this BloodPressure. * @param systolicBP */ public void setSystolicBP(Integer systolicBP) { this.systolicBP = systolicBP; } /** * Sets diastolicBP for this BloodPressure. * @param diastolicBP */ public void setDiastolicBP(Integer diastolicBP) { this.diastolicBP = diastolicBP; } /** * Returns a string representation of this BloodPressure. */ public String toString(){ return "SBP: "+systolicBP+", DBP: "+diastolicBP; } /** * Returns a string representation of this BloodPressure that will be * stored in a text file. * @return a string representation of this BloodPressure. */ public String fileString(){ return systolicBP + " " + diastolicBP; } }
05dd5678b5dbd2e688fba951aad973b197923f9b
[ "Markdown", "Java" ]
14
Java
MaxJeong/Hospital-Android-App
7c201df050471820ee13064b575f592d8409f171
44104662e9e5989b4b777433db2cc895d22cc7aa
HEAD
<file_sep>import FWCore.ParameterSet.Config as cms # # reusable functions def producers_by_type(process, *types): return (module for module in process._Process__producers.values() if module._TypedParameterizable__type in types) def esproducers_by_type(process, *types): return (module for module in process._Process__esproducers.values() if module._TypedParameterizable__type in types) # # one action function per PR - put the PR number into the name of the function # example: # def customiseFor12718(process): # for pset in process._Process__psets.values(): # if hasattr(pset,'ComponentType'): # if (pset.ComponentType == 'CkfBaseTrajectoryFilter'): # if not hasattr(pset,'minGoodStripCharge'): # pset.minGoodStripCharge = cms.PSet(refToPSet_ = cms.string('HLTSiStripClusterChargeCutNone')) # return process def customiseFor13062(process): for module in producers_by_type(process,'PixelTrackProducer'): if not hasattr(module.RegionFactoryPSet.RegionPSet,'useMultipleScattering'): module.RegionFactoryPSet.RegionPSet.useMultipleScattering = cms.bool(False) if not hasattr(module.RegionFactoryPSet.RegionPSet,'useFakeVertices'): module.RegionFactoryPSet.RegionPSet.useFakeVertices = cms.bool(False) for module in producers_by_type(process,'SeedGeneratorFromRegionHitsEDProducer'): if not hasattr(module.RegionFactoryPSet.RegionPSet,'useMultipleScattering'): module.RegionFactoryPSet.RegionPSet.useMultipleScattering = cms.bool(False) if not hasattr(module.RegionFactoryPSet.RegionPSet,'useFakeVertices'): module.RegionFactoryPSet.RegionPSet.useFakeVertices = cms.bool(False) for module in esproducers_by_type(process,'Chi2ChargeMeasurementEstimatorESProducer'): if hasattr(module,'MaxDispacement'): delattr(module,'MaxDispacement') if not hasattr(module,'MaxDisplacement'): module.MaxDisplacement = cms.double(100.) if not hasattr(module,'MaxSagitta'): module.MaxSagitta = cms.double(-1.) if not hasattr(module,'MinimalTolerance'): module.MinimalTolerance = cms.double(10.) for module in esproducers_by_type(process,'Chi2MeasurementEstimatorESProducer'): if hasattr(module,'MaxDispacement'): delattr(module,'MaxDispacement') if not hasattr(module,'MaxDisplacement'): module.MaxDisplacement = cms.double(100.) if not hasattr(module,'MaxSagitta'): module.MaxSagitta = cms.double(-1.) if not hasattr(module,'MinimalTolerance'): module.MinimalTolerance = cms.double(10.) for pset in process._Process__psets.values(): if hasattr(pset,'ComponentType'): if (pset.ComponentType == 'CkfBaseTrajectoryFilter'): if not hasattr(pset,'minGoodStripCharge'): pset.minGoodStripCharge = cms.PSet(refToPSet_ = cms.string('HLTSiStripClusterChargeCutNone')) if not hasattr(pset,'maxCCCLostHits'): pset.maxCCCLostHits = cms.int32(9999) if not hasattr(pset,'seedExtension'): pset.seedExtension = cms.int32(0) if not hasattr(pset,'strictSeedExtension'): pset.strictSeedExtension = cms.bool(False) return process # # CMSSW version specific customizations def customizeHLTforCMSSW(process, menuType="GRun"): import os cmsswVersion = os.environ['CMSSW_VERSION'] if cmsswVersion >= "CMSSW_8_0": # process = customiseFor12718(process) process = customiseFor13062(process) from HLTrigger.Configuration.customizeHLTfor2016trackingTemplate import customiseFor2016trackingTemplate # process = customiseFor2016trackingTemplate(process) pass return process
e88cdbee8ed7ab5d1cca881a951d9e8b9be2db49
[ "Python" ]
1
Python
tstreble/L1_eg_emul_fw_tests
4781fc34c3d210e5bde141027fda576e2f8c0e67
425a15307d19b22b90c71b8bf30f733722c25996
refs/heads/main
<repo_name>jackcarter/advent_of_code_2020<file_sep>/2020/day_20/puzzle_1.py from functools import reduce import operator from pprint import pprint import math def get_edge(tile, edge): edges = {"top": tile[0], "bottom": tile[-1], "left": [t[0] for t in tile], "right": [t[-1] for t in tile] } return edges[edge] def get_edges(tile): return get_edge(tile, "top"), get_edge(tile, "bottom"), get_edge(tile, "left"), get_edge(tile, "right") def rotate_tile(tile): # https://stackoverflow.com/questions/5164642/python-print-a-generator-expression return list(zip(*tile[::-1])) def flip_tile(tile): return [t[::-1] for t in tile] def get_permutations(tile): functions_list = [lambda x: x, lambda x: rotate_tile(x), lambda x: rotate_tile(rotate_tile(x)), lambda x: rotate_tile(rotate_tile(rotate_tile(x))), lambda x: flip_tile(x), lambda x: flip_tile(rotate_tile(x)), lambda x: flip_tile(rotate_tile(rotate_tile(x))), lambda x: flip_tile(rotate_tile(rotate_tile(rotate_tile(x))))] return [f(tile) for f in functions_list] def edge_match(tile1, tile2): e1 = get_edges(tile1) e2 = get_edges(tile2) for edge1 in e1: for edge2 in e2: if edge1 == edge2: return True return False def compare_tiles(tile1, tile2): match_count = 0 for ii, t2p in enumerate(get_permutations(tile2)): if edge_match(tile1, t2p): match_count+=1 return match_count def get_matches(tile1, unused_tiles): matches = [] for tilenum2, tile2 in unused_tiles.items(): match = compare_tiles(tile1['tile'], tile2['tile']) if match>0: matches.append(tilenum2) return matches def unused(tiles, jigsaw): used_tilenums = [j['tileNum'] for j in jigsaw] unused_tiles = {k: v for k, v in tiles.items() if k not in used_tilenums} return unused_tiles def parse_tiles(lines): tiles = {} tile = [] for ii, line in enumerate(lines): if line[:4]=="Tile": x, tilenum = line.split(" ") tilenum = int(tilenum[:-1]) tiles[tilenum] = [] elif line=="": tiles[tilenum] = {'tile': tile, 'orientationFixed':False, 'countMatches': 0, 'tileNum': tilenum} tile = [] else: tile.append([l for l in line]) return tiles with open("data.txt") as data: lines = data.read().splitlines() tiles = parse_tiles(lines) corners = [] for tilenum1, tile1 in tiles.items(): matches = get_matches(tile1, unused(tiles, [tiles[tilenum1]])) tiles[tilenum1]['countMatches']=len(matches) if len(matches) == 2: corners.append(tilenum1) corner_prod = reduce(operator.mul, corners, 1) print("Answer:", corner_prod) # Answer: 20913499394191<file_sep>/2015/day_10/puzzle_2.py with open("data.txt") as data: lines = data.read().splitlines() sequence = lines[0] def next_sequence(sequence): last_seen = sequence[0] current_count = 0 next_sequence = "" for char in sequence: if char == last_seen: current_count += 1 else: next_sequence += str(current_count) + last_seen current_count = 1 last_seen = char next_sequence += str(current_count) + last_seen return next_sequence for ii in range(50): sequence = next_sequence(sequence) print(len(sequence)) # Answer: 329356<file_sep>/2015/day_05/puzzle_1.py import string with open("data.txt") as data: lines = data.readlines() def is_nice(word): vowels = "aeiou" count_vowels = 0 for c in word: if c in vowels: count_vowels += 1 if count_vowels < 3: return False doubled = [ch + ch for ch in string.ascii_lowercase] for d in doubled: if d in word: break else: return False bad_strings = ["ab", "cd", "pq", "xy"] for bs in bad_strings: if bs in word: return False return True count_nice = 0 for ii, line in enumerate(lines): if is_nice(line): count_nice += 1 print(count_nice) # Answer: 236<file_sep>/2020/day_19/puzzle_2.py import itertools from pprint import pprint import numpy as np from copy import deepcopy import operator import re def evaluate_rule(rules, rule): rule_regex = "" if '"' in rule: return rule[1] elif "|" in rule: rule_parts = rule.split(" | ") sub_evals =[evaluate_rule(rules, rp) for rp in rule_parts] return "((" + ")|(".join(sub_evals) + "))" else: sub_rules = rule.split(" ") sub_evals = [evaluate_rule(rules, rules[sr]) for sr in sub_rules] if rule == "42 31": recursion_limit = 10 sub_rule = "(" for ii in range(1,recursion_limit): #I don't want to do recursive groups. Assume that there won't be more than 10 levels of recursion... sub_rule += f"(({sub_evals[0]}){{{ii}}}({sub_evals[1]}){{{ii}}})" if ii < recursion_limit - 1: sub_rule += "|" sub_rule += ")" else: sub_rule = "(" + "".join([item for sublist in sub_evals for item in sublist]) + ")" if rule == "42": sub_rule = "(" + sub_rule + "+)" return sub_rule with open("data.txt") as data: lines = data.read().splitlines() rules = {} messages = [] section = 0 for line in lines: if line == "": section += 1 continue if section == 0: rulenum, rule = line.split(": ") rules[rulenum] = rule elif section == 1: messages.append(line) rule0 = evaluate_rule(rules, rules["0"]) pattern = re.compile('^' + rule0 + '$') print("Answer:",len([1 for message in messages if pattern.match(message)])) # Answer: 296<file_sep>/2020/day_24/puzzle_2.py from copy import deepcopy def parse_line(line): ins, num = line.split(" ") num = int(num) return ins, num def hash_addr(address): return str(address[0]) + "$" + str(address[1]) with open("data.txt") as data: #lines = list(map(int, data.read().splitlines())) lines = data.read().splitlines() dirs = ['ne', 'e', 'se', 'sw', 'w', 'nw'] tiles = {} for data in lines: address = [0,0] instructions = [] pointer = 0 while pointer < len(data): if pointer < len(data)-1 and data[pointer] + data[pointer+1] in dirs: instructions.append(data[pointer] + data[pointer+1]) pointer += 2 else: instructions.append(data[pointer]) pointer += 1 #print(instructions) for ins in instructions: if ins=='ne': address[0]+=0 address[1]+=1 elif ins=='e': address[0]+=1 address[1]+=0 elif ins=='se': address[0]+=1 address[1]+=-1 elif ins=='sw': address[0]+=0 address[1]+=-1 elif ins=='w': address[0]+=-1 address[1]+=0 elif ins=='nw': address[0]+=-1 address[1]+=1 #print(ins, address) #print(address) addr_str = hash_addr(address) if addr_str not in tiles: tiles[addr_str] = 'b' #print("new black", addr_str) else: if tiles[addr_str] == 'b': #print("black to white", addr_str) tiles[addr_str] = 'w' elif tiles[addr_str] == 'w': #print("white to black", addr_str) tiles[addr_str] = 'b' black = len([v for k, v in tiles.items() if v=='b']) def count_black_neighbors(tiles, ii, jj): dirs = [[0,1], [1,0], [1,-1], [0,-1], [-1,0], [-1,1]] count_black = 0 for d in dirs: check_addr_str = hash_addr([ii+d[0], jj+d[1]]) if check_addr_str in tiles: if tiles[check_addr_str] == 'b': count_black += 1 else: tiles[check_addr_str] = 'w' return count_black domain = 30 for ii in range(-domain,domain): for jj in range(-domain,domain): ref_tile = hash_addr([ii,jj]) if ref_tile not in tiles: tiles[ref_tile] = 'w' domain -= 5 for day in range(1, 101): max_ii = 10 max_jj = 10 new_tiles = deepcopy(tiles) for ii in range(-domain,domain): for jj in range(-domain,domain): ref_tile = hash_addr([ii,jj]) bn = count_black_neighbors(tiles, ii, jj) if ref_tile not in tiles: tiles[ref_tile] = 'w' if tiles[ref_tile] == 'w': if bn == 2: if abs(ii) > max_ii: max_ii = abs(ii) if abs(jj) > max_jj: max_jj = abs(jj) new_tiles[ref_tile] = 'b' else: if abs(ii) > max_ii: max_ii = abs(ii) if abs(jj) > max_jj: max_jj = abs(jj) if bn == 0 or bn > 2: new_tiles[ref_tile] = 'w' tiles = deepcopy(new_tiles) domain = max(max_ii, max_jj) + 10 print("Answer:", len([v for k, v in new_tiles.items() if v=='b'])) # Answer: 3711<file_sep>/2020/day_21/puzzle_1.py import itertools from pprint import pprint def parse_line(line): ing_str, aller_str = line.split(" (contains ") ingredients = set(ing_str.split(" ")) allergens = aller_str[:-1].split(", ") return allergens, ingredients with open("data.txt") as data: lines = data.read().splitlines() allergen_dict = {} ingredients_set = set() ingredient_counts = {} for ii, line in enumerate(lines): allergens, ingredients = parse_line(line) for allergen in allergens: if allergen not in allergen_dict: allergen_dict[allergen] = set(ingredients) else: allergen_dict[allergen] = allergen_dict[allergen].intersection(ingredients) ingredients_set = ingredients_set.union(ingredients) for ingredient in ingredients: if ingredient not in ingredient_counts: ingredient_counts[ingredient] = 1 else: ingredient_counts[ingredient] += 1 pprint(allergen_dict) pprint(ingredients_set) print([v for k, v in allergen_dict.items()]) remaining_ingredients = set.union(*[v for k, v in allergen_dict.items()]) safe_ingredients = ingredients_set - remaining_ingredients total_count = 0 for si in safe_ingredients: total_count+=ingredient_counts[si] print(total_count) # Answer: 1707<file_sep>/2020/day_18/puzzle_1.py import itertools from pprint import pprint import numpy as np from copy import deepcopy import operator def get_matching_close_paren(section, start): paren_stack = 0 for ii, char in enumerate(section): if ii < start: continue if char == '(': paren_stack += 1 elif char == ')': paren_stack -= 1 if paren_stack == 0: return ii def evaluate_minimal(expression): lookup = {'+': operator.add, '*': operator.mul} return lookup[expression[1]](int(expression[0]), int(expression[2])) def evaluate_no_parens(expression): expression = expression.split(" ") while len(expression) > 1: intermediate_result = evaluate_minimal(expression[:3]) expression = [intermediate_result] + expression[3:] return intermediate_result def evaluate(section): if '(' in section: for ii, char in enumerate(section): if char == '(': matching_close_paren = get_matching_close_paren(section, ii) inside_parens = evaluate(section[ii+1:matching_close_paren]) return evaluate(section[:ii] + str(inside_parens) + section[matching_close_paren+1:]) else: return evaluate_no_parens(section) with open("data.txt") as data: lines = data.read().splitlines() print("Answer:",sum([evaluate(line) for line in lines])) # Answer: 45283905029161<file_sep>/2020/day_13/scratch.py from functools import reduce # Valid in Python 2.6+, required in Python 3 import operator import itertools line = """ 19,x,x,x,x,x,x,x,x,x,x,x,x,37,x,x,x,x,x,751,x,29,x,x,x,x,x,x,x,x,x,x,13,x,x,x,x,x,x,x,x,x,23,x,x,x,x,x,x,x,431,x,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,17 """ mytime= 1002578 buses = [[ii, int(t)] for ii, t in enumerate(line.split(",")) if t != 'x'] print(buses) bigN = reduce(operator.mul, [bus[0] for bus in buses[1:]], 1) print(bigN) incrementer = buses[0][1] for ii in itertools.count(1): time = ii*incrementer syncs = ['_']*len(buses) for jj, bus in enumerate(buses): if (time+bus[0]) % bus[1] == 0: syncs[jj] = 'X' else: syncs[jj] = ((time+bus[0]) % bus[1]) print(syncs, ii, syncs.count('X')) good=True for bus in buses: if (time+bus[0]) % bus[1] != 0: good = False break if good: print(time, "win") exit(0) if ii>350000: exit(0) # missamount + abs(bus[1]-incrementer) * x = bus[1] buses=buses[:3] incrementer = buses[0][1] count = 1 max_numgood = 1 for ii in itertools.count(1): time=incrementer*ii numgood = 0 for bus in buses: if (time+bus[0]) % bus[1] == 0: numgood+=1 else: break if numgood > max_numgood: incrementer *= bus[1] max_numgood += 1 print(numgood, incrementer) if numgood==len(buses): print(time) #exit(0) if ii>500: exit(0) # 37x = 19y+13 #if (time+buses[bus_in_q][0]) % buses[bus_in_q][1] == 0: # print(time,buses[bus_in_q][0]+time, (time+buses[bus_in_q][0])/buses[bus_in_q][1]) # incrementer *= (time+buses[bus_in_q][0])/buses[bus_in_q][1] # print("inc:",incrementer) # bus_in_q+=1 # if bus_in_q > len(buses): # break # Answer: s<file_sep>/2020/day_04/puzzle_2.py import re def hgt_valid(hgt): if hgt[-2:] == 'cm': return 150 <= int(hgt[:-2]) <= 193 elif hgt[-2:] == 'in': return 59 <= int(hgt[:-2]) <= 76 else: return False def is_valid(passport): required_elements = {'byr': lambda x: 1920 <= int(x) <= 2002, 'iyr': lambda x: 2010 <= int(x) <= 2020, 'eyr': lambda x: 2020 <= int(x) <= 2030, 'hgt': hgt_valid, 'hcl': lambda x: re.match('^\#[a-f|\d]{6}$', x) is not None, 'ecl': lambda x: x in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'], 'pid': lambda x: re.match('^\d{9}$', x) is not None, #'cid', } passport_elements = passport.split(' ') passport_elements = {pe.split(':')[0]: pe.split(':')[1] for pe in passport_elements} for req_el, test in required_elements.items(): if req_el not in passport_elements.keys(): return False elif test(passport_elements[req_el]) == False: return False return True passports = [] with open("data.txt") as data: lines = data.read().splitlines() lines.append('') #ensure we 'flush' the last passport to passports list accumulator = [] for line in lines: if line != '': accumulator.append(line) else: passports.append(' '.join(accumulator)) accumulator = [] num_valid = 0 for passport in passports: if is_valid(passport): num_valid += 1 print(num_valid) # Answer: 184<file_sep>/2015/day_01/puzzle_1.py with open("data.txt") as data: lines = data.readlines() floor = 0 for ii, char in enumerate(lines[0]): if char == '(': floor += 1 elif char == ')': floor -= 1 print(floor) # Answer: 280<file_sep>/2020/day_07/puzzle_1.py def get_containing_bags(bags, start_bag): top_bags = [] for name, contents in bags.items(): if start_bag in contents: top_bags.append(name) top_bags.extend(get_containing_bags(bags, name)) return top_bags def parse_line(line): name, contents_txt = line.split(" bags contain ") contents = {} contents_txt = contents_txt[:-1] #drop the period if contents_txt == "no other bags": contents = [] else: csplit = contents_txt.split(", ") for x in csplit: content_desc = x.split(" ") num = content_desc[0] content_bag_name = content_desc[1]+" "+content_desc[2] contents[content_bag_name] = num return name, contents groups = [] with open("data.txt") as data: lines = data.read().splitlines() bags = {} for line in lines: name, contents = parse_line(line) bags[name] = contents top_level_bags = get_containing_bags(bags, "shiny gold") #print(top_level_bags) print(len(set(top_level_bags))) # Answer: 287<file_sep>/2020/day_16/puzzle_2.py import itertools from pprint import pprint from functools import reduce import operator def parse_rules(line): field, rules = line.split(": ") r1, r2 = rules.split(" or ") r1min, r1max = list(map(int, r1.split("-"))) r2min, r2max = list(map(int, r2.split("-"))) return field, lambda x: r1min <= x <= r1max or r2min <= x <= r2max #return lambda x: r1min <= x <= r1max or r2min <= x <= r2max with open("data.txt") as data: lines = data.read().splitlines() section = 0 rules = {} other_tickets = {} for ii, line in enumerate(lines): if section == 0: if line == "": section += 1 else: field, func = parse_rules(line) rules[field] = func elif section == 1: if line == "": section += 1 elif line == "your ticket:": continue else: my_ticket = list(map(int,line.split(","))) elif section == 2: if line == "nearby tickets:": continue else: other_tickets[ii] = list(map(int,line.split(","))) invalid_tickets = [] for ii, t in other_tickets.items(): for f in t: if not any([rules[r](f) for r in rules]): invalid_tickets.append(ii) for it_id in invalid_tickets: del other_tickets[it_id] ticket_fields = {x: [] for x in range(len(rules))} #figure out which fields are valid for which rules for tf in ticket_fields: for rule in rules: if all([rules[rule](t[tf]) for t in other_tickets.values()]): ticket_fields[tf].append(rule) #assign a single rule to each field tf2 = {} while len(tf2) < len(ticket_fields): for tf in ticket_fields: if len(ticket_fields[tf]) == 1: rule_to_remove = ticket_fields[tf][0] tf2[tf] = rule_to_remove for tf in ticket_fields: if rule_to_remove in ticket_fields[tf] and len(ticket_fields[tf]) > 1: ticket_fields[tf].remove(rule_to_remove) print("Answer:",reduce(operator.mul, [my_ticket[num] for num, name in tf2.items() if name.startswith('departure')], 1)) # Answer: 998358379943<file_sep>/2020/day_12/puzzle_2.py def parse_line(line): return line[0], int(line[1:]) def add(a, b): return a+b def subtract(a, b): return a-b def turn(direction, degrees): if degrees==180: state["wayy"] *= -1 state["wayx"] *= -1 elif (degrees == 90 and direction == "L") or (degrees == 270 and direction == "R"): new_wayy = state["wayx"] new_wayx = -state["wayy"] state["wayy"] = new_wayy state["wayx"] = new_wayx else: new_wayy = -1*state["wayx"] new_wayx = state["wayy"] state["wayy"] = new_wayy state["wayx"] = new_wayx dirmap = {"N": ("wayy", add), "S": ("wayy", subtract), "E": ("wayx", add), "W": ("wayx", subtract)} frmap = {"F": add, "R": subtract} def go(line): action, num = parse_line(line) if action in "NEWS": coord, func = dirmap[action] state[coord]=func(state[coord], num) elif action in "RL": turn(action, num) elif action == "F": for ii in range(num): state["x"] += state["wayx"] state["y"] += state["wayy"] print(action, num, state) with open("data.txt") as data: lines = data.read().splitlines() state = {"dir": "E", "x": 0, "y": 0, "wayx": 10, "wayy": 1} for line in lines: go(line) print(abs(state['x'])+abs(state['y'])) # Answer: 45763<file_sep>/2020/day_17/puzzle_2.py import itertools from pprint import pprint import numpy as np from copy import deepcopy def c2h(coord): return "$".join([str(c) for c in coord]) def h2c(hash): return list(map(int, hash.split("$"))) def get_cell_default(cells, coord): try: return cells[c2h(coord)] except KeyError: return '.' def get_neighbor_coords(cells, coord): delta = [-1,0,1] return [(coord[0]+dw, coord[1]+dz, coord[2]+dy, coord[3]+dx) for dw in delta for dz in delta for dy in delta for dx in delta if dz!=0 or dy!=0 or dx!=0 or dw!=0] def get_active_neighbors(cells, coord): neighbor_coords = get_neighbor_coords(cells, coord) neighbors = [get_cell_default(cells, new_coord) for new_coord in neighbor_coords] active_neighbor_count = neighbors.count("#") #print(c2h(coord), active_neighbor_count) return active_neighbor_count def step(cells): #first, add a buffer around all active cells for cell in list(cells): #use list to create a static copy, avoiding runtimeerror (https://stackoverflow.com/questions/11941817) neighbors = get_neighbor_coords(cells, h2c(cell)) for neighbor in neighbors: neighbor_hash = c2h(neighbor) if cells[cell] == '#' and neighbor_hash not in cells: cells[neighbor_hash] = '.' new_cells = deepcopy(cells) for cell in cells: active_neighbors = get_active_neighbors(cells, h2c(cell)) if cells[cell]=='#': if active_neighbors not in [2, 3]: new_cells[cell] = '.' else: new_cells[cell] = '#' if cells[cell]=='.': if active_neighbors == 3: new_cells[cell] = '#' else: new_cells[cell] = '.' return new_cells def count_active(cells): return len([cells[c] for c in cells if cells[c]=='#']) cells = {} with open("data.txt") as data: lines = data.read().splitlines() for ii in range(len(lines)): for jj in range(len(lines[ii])): cells[c2h((0, 0, ii, jj))] = lines[ii][jj] for ii in range(6): cells = step(cells) print("Answer:",count_active(cells)) # Answer: 1624<file_sep>/2020/day_11/puzzle_2.py import itertools from pprint import pprint import numpy as np def get_neighbor_occupied_count(old_seats, row, col): neighbors = [old_seats[row-1][col-1], old_seats[row-1][col], old_seats[row-1][col+1], old_seats[row][col-1], old_seats[row][col+1], old_seats[row+1][col-1], old_seats[row+1][col], old_seats[row+1][col+1], ] return neighbors.count('#') def get_first_visible_occupied_count(old_seats, row, col): nearest_neighbors = [] nearest_neighbor_coords = [] for row_delt in [-1, 0, 1]: for col_delt in [-1, 0, 1]: if row_delt == 0 and col_delt == 0: #don't care about this case; we'll never get anywhere continue examine_seat_row = row examine_seat_col = col while(True): examine_seat_row = examine_seat_row+row_delt examine_seat_col = examine_seat_col+col_delt if len(old_seats)-1 < examine_seat_row or 0 > examine_seat_row or len(old_seats[0])-1 < examine_seat_col or 0 > examine_seat_col: break examine_seat = old_seats[examine_seat_row][examine_seat_col] if examine_seat != '.': nearest_neighbors.append(examine_seat) nearest_neighbor_coords.append([examine_seat_row, examine_seat_col]) break #print(row, col, nearest_neighbors, nearest_neighbor_coords) return nearest_neighbors.count("#") def update_seats(old_seats): new_seats = np.copy(old_seats) for row in range(len(old_seats)): for col in range(len(old_seats[0])): if old_seats[row][col] == "L": if get_first_visible_occupied_count(old_seats, row, col) == 0: new_seats[row][col]="#" else: new_seats[row][col]=old_seats[row][col] elif old_seats[row][col] == "#": if get_first_visible_occupied_count(old_seats, row, col) >= 5: new_seats[row][col]="L" else: new_seats[row][col]=old_seats[row][col] else: new_seats[row][col]=old_seats[row][col] return new_seats with open("data.txt") as data: lines = data.read().splitlines() seats = [[c for c in line] for line in lines] old_seats = np.array(seats) print(old_seats) for ii in itertools.count(1): new_seats = update_seats(old_seats) if np.array_equal(old_seats, new_seats): print("Answer:",np.count_nonzero(new_seats == "#")) break else: old_seats = new_seats.copy() # Answer: 2066<file_sep>/2015/day_13/puzzle_1.py from collections import defaultdict import itertools with open("data.txt") as data: lines = data.read().splitlines() guests = defaultdict(dict) happiness = {} for line in lines: words = line[:-1].split(' ') sign = 1 if words[2] == 'gain' else -1 guests[words[0]][words[-1]] = int(words[3])*sign def calc(guests, sequence): looped_sequence = list(sequence) looped_sequence.append(looped_sequence[0]) looped_sequence.append(looped_sequence[1]) total_happiness = 0 for ii in range(1,len(sequence)+1): total_happiness += guests[looped_sequence[ii]][looped_sequence[ii+1]] total_happiness += guests[looped_sequence[ii]][looped_sequence[ii-1]] return total_happiness max_happiness = 0 sequences = itertools.permutations(list(guests.keys())) for seq in sequences: max_happiness = max(max_happiness, calc(guests,seq)) print(max_happiness) # Answer: 664<file_sep>/2020/day_13/puzzle_2.py import itertools with open("data.txt") as data: lines = data.read().splitlines() buses = [[ii, int(t)] for ii, t in enumerate(lines[1].split(",")) if t != 'x'] print(buses) time = 0 step = 1 for bus in buses: while True: time += step if (time + bus[0]) % bus[1] == 0: break step *= bus[1] print(bus[1], step) print(time) # Answer: 538703333547789<file_sep>/2015/day_02/puzzle_1.py with open("data.txt") as data: lines = data.readlines() def calc_area(l, w, h): sorted_sides = sorted([l,w,h]) smallest_side_area = sorted_sides[0]*sorted_sides[1] return 2*l*w + 2*w*h + 2*l*h + smallest_side_area presents = [] sqft = 0 for ii, line in enumerate(lines): dims = line.split('x') dims = map(int, dims) presents.append(dims) sqft += calc_area(*dims) print(sqft) # Answer: 1586300<file_sep>/2020/day_15/puzzle_2.py import itertools from pprint import pprint with open("data.txt") as data: lines = data.read().splitlines() nums = list(map(int,lines[0].split(","))) last_used = {nums[ii]:ii for ii in range(len(nums))} old_speak = nums[-1] for ii in range(len(nums), 30000000): if old_speak not in last_used: #print("fdsa", speak, last_used[speak], ii) new_speak = 0 else: new_speak = ii - 1 - last_used[old_speak] #last_used[speak] = ii last_used[old_speak] = ii - 1 #print(new_speak) old_speak = new_speak print("Answer:",new_speak) # Answer: 11721679<file_sep>/2020/day_02/puzzle_1.py def is_valid(line): policy, password = line.split(": ") rangetxt, letter = policy.split(" ") mini, maxi = map(int, rangetxt.split("-")) return mini <= password.count(letter) <= maxi num_valid = 0 with open("data.txt") as data: lines = data.readlines() for ii, line in enumerate(lines): if is_valid(line): num_valid += 1 print(num_valid) # Answer: 219<file_sep>/2020/day_02/puzzle_2.py def is_valid(line): policy, password = line.split(": ") positions, letter = policy.split(" ") pos1, pos2 = map(int, positions.split("-")) return bool(password[pos1-1] == letter) != bool(password[pos2-1] == letter) num_valid = 0 with open("data.txt") as data: lines = data.readlines() for ii, line in enumerate(lines): if is_valid(line): num_valid += 1 print(num_valid) # Answer: 593<file_sep>/2020/day_22/puzzle_2.py import itertools from pprint import pprint def score(cards): score = 0 for ii, card in enumerate(cards[::-1]): score += (1+ii)*card return score def hash_cards(cards1, cards2): #this is for making sure we don't infinite loop return "$".join(map(str,cards1)) + "#" + "$".join(map(str,cards2)) def play_game(cards1, cards2): game_states = set() while len(cards1) > 0 and len(cards2) > 0: game_state = hash_cards(cards1, cards2) if game_state in game_states: return "p1", [], [] else: game_states.add(game_state) c1 = cards1.pop(0) c2 = cards2.pop(0) if c1 <= len(cards1) and c2 <= len(cards2): winner, x, y = play_game(cards1[:c1], cards2[:c2]) else: if c1 > c2: winner = "p1" elif c2 > c1: winner = "p2" if winner == "p1": cards1.extend([c1, c2]) elif winner == "p2": cards2.extend([c2, c1]) return winner, cards1, cards2 with open("data.txt") as data: lines = data.read().splitlines() cards1 = [] cards2 = [] adding_cards_to = cards1 for line in lines: if line in ["", "Player 1:"]: continue elif line == "Player 2:": adding_cards_to = cards2 continue adding_cards_to.append(int(line)) winner, cards1, cards2 = play_game(cards1, cards2) if winner == "p1": print("Answer:", score(cards1)) else: print("Answer:", score(cards2)) # Answer: 35436<file_sep>/2015/day_12/puzzle_1.py import re with open("data.txt") as data: text = data.read() numbers = map(int, re.findall(r'-?\d+', text)) print(sum(numbers)) # Answer: 111754<file_sep>/2020/day_09/puzzle_1.py def valid(last_n, current): for i, n in enumerate(last_n): for j, m in enumerate(last_n): if j!=i and n+m==current: return True return False with open("data.txt") as data: lines = list(map(int, data.read().splitlines())) preamble = 25 lookback = 25 for ii in range(preamble, len(lines)): if valid(lines[ii-lookback:ii], lines[ii]): pass else: print(lines[ii]) break # Answer: 15690279<file_sep>/2015/day_02/puzzle_2.py with open("data.txt") as data: lines = data.readlines() def calc_ribbon(l, w, h): sorted_sides = sorted([l,w,h]) smallest_side_perimeter = 2*sorted_sides[0] + 2*sorted_sides[1] return l*w*h + smallest_side_perimeter presents = [] sqft = 0 for ii, line in enumerate(lines): dims = line.split('x') dims = map(int, dims) presents.append(dims) sqft += calc_ribbon(*dims) print(sqft) # Answer: 3737498<file_sep>/2015/day_01/puzzle_2.py with open("data.txt") as data: lines = data.readlines() floor = 0 for ii, char in enumerate(lines[0]): if char == '(': floor += 1 elif char == ')': floor -= 1 if floor == -1: print(ii+1) break # Answer: 1797<file_sep>/2020/day_01/puzzle_1.py with open("data.txt") as data: lines = data.readlines() for ii, line in enumerate(lines): num1 = int(line) for jj, line2 in enumerate(lines): num2=int(line2) if ii!=jj and num1+num2==2020: print(num1*num2) break # Answer: 776064<file_sep>/2015/day_12/puzzle_2.py import re import json with open("data.txt") as data: text = data.read() j = json.loads(text) def sum_children(node): subtotal = 0 # first, check if the node is a primitive if type(node) is int: subtotal = node elif type(node) is str: subtotal = 0 else: # node is a dict or list. See if any property is 'red' try: for child in node: if node[child] == 'red': return 0 except Exception as ex: pass # if no 'red' value found, continue parsing for child in node: if type(child) is int: subtotal += child elif type(child) is dict: subtotal += sum_children(child) elif type(child) is list: subtotal += sum_children(child) elif type(child) is str: try: subtotal += sum_children(node[child]) except Exception as ex: pass return subtotal print(sum_children(j)) # Answer: 65402<file_sep>/2015/day_11/puzzle_1.py import string with open("data.txt") as data: lines = data.read().splitlines() password = lines[0] password = [l for l in password] # convert to list so that we can edit in-place class Password: def __init__(self, password): self.val = [l for l in password] # convert to list so that we can edit in-place def password(self): return ''.join(self.val) def increment(self): for ii, letter in enumerate(self.val[::-1]): if letter != 'z': self.val[-(ii+1)] = chr(ord(letter)+1) break else: self.val[-(ii+1)] = 'a' def check_valid(self): # First check for straights straights = [ch + chr(ord(ch)+1) + chr(ord(ch)+2) for ch in string.ascii_lowercase if ord(ch) < ord('y')] for s in straights: if s in self.password(): break else: return False for ch in "iol": if ch in self.password(): return False count_doubled = 0 for ii in range(1, len(self.val)): if self.val[ii] == self.val[ii-1]: if ii > 2 and self.val[ii] == self.val[ii-2]: # 3-in-a-row doesn't count as two pairs continue count_doubled += 1 if count_doubled < 2: return False return True password = Password(lines[0]) while not password.check_valid(): password.increment() print(password.password()) # Answer: <PASSWORD><file_sep>/2020/day_10/puzzle_2.py from functools import reduce import operator def get_valid_previous(curr_voltage, voltages): return [v for v in voltages if 0 < curr_voltage-v < 4] with open("data.txt") as data: lines = list(map(int, data.read().splitlines())) start = 0 end = max(lines)+3 voltages = [start] voltages.extend(sorted(lines)) voltages.extend([end]) valid_ways = {0: {"previous": [], "num": 1}} for voltage in voltages[1:]: previous = get_valid_previous(voltage, voltages) valid_ways[voltage]={"previous":previous, "num": sum([valid_ways[p]["num"] for p in previous])} print(valid_ways[max(lines)]["num"]) # Answer: 6908379398144<file_sep>/2020/day_10/puzzle_1.py def use_all_adapters(adapters): deltas = {1:0,2:0,3:0} for ii in range(1,len(adapters)): delta = adapters[ii]-adapters[ii-1] deltas[delta]+=1 print(deltas, deltas[1]*deltas[3]) with open("data.txt") as data: lines = list(map(int, data.read().splitlines())) start = 0 end = max(lines)+3 adapters = [start] adapters.extend(sorted(lines)) adapters.extend([end]) use_all_adapters(adapters) # Answer: 2080<file_sep>/2020/day_25/puzzle_1.py def get_loop_size(target): counter = 0 num = 1 while num != target: num = num * 7 num = num % 20201227 counter += 1 return counter dpk = 8458505 cpk = 16050997 card_loop_size = get_loop_size(cpk) num = 1 for ii in range(card_loop_size): num = num * dpk num = num % 20201227 print("Answer:", num) # Answer: 448851 <file_sep>/2020/day_07/puzzle_2.py def get_contained_bags(bags, start_bag): total_bags = 0 for contained_bag in bags[start_bag]: num_contained_bags = int(bags[start_bag][contained_bag]) total_bags += num_contained_bags total_bags += num_contained_bags*get_contained_bags(bags, contained_bag) return total_bags def parse_line(line): name, contents_txt = line.split(" bags contain ") contents = {} contents_txt = contents_txt[:-1] #drop the period if contents_txt == "no other bags": contents = [] else: csplit = contents_txt.split(", ") for x in csplit: content_desc = x.split(" ") num = content_desc[0] content_bag_name = content_desc[1]+" "+content_desc[2] contents[content_bag_name] = num return name, contents groups = [] with open("data.txt") as data: lines = data.read().splitlines() bags = {} for line in lines: name, contents = parse_line(line) bags[name] = contents contained_bags = get_contained_bags(bags, "shiny gold") print(contained_bags) # Answer: 48160<file_sep>/2020/day_03/puzzle_2.py from functools import reduce # slope is expressed as (delta_y, delta_x), y increasing downwards and x increasing to the right def get_next_pos(slope, x1, y1, shape_width): y2 = y1 + slope[0] x2 = (x1 + slope[1]) % shape_width return x2, y2 array = [] with open("data.txt") as data: lines = data.read().splitlines() for line in lines: array.append(line) def num_trees(slope): shape_width = len(array[0]) shape_height = len(array) x = 0 y = 0 print(array) num_trees = 0 while y < shape_height-1: x, y = get_next_pos(slope, x, y, shape_width) if array[y][x] == "#": num_trees += 1 return num_trees slopes = [[1,1],[1,3],[1,5],[1,7],[2,1]] total_num_trees = [num_trees(slope) for slope in slopes] print(reduce(lambda x, y: x*y, total_num_trees)) # Answer: 3521829480<file_sep>/2020/day_23/puzzle_1.py import itertools from pprint import pprint import numpy as np from copy import deepcopy import operator import re def get_next_3(cups): return cups[1:4] def get_destination(cups, next_3): dest = cups[0]-1 while dest == 0 or dest in next_3: if dest == 0: dest = 9 if dest in next_3: dest -= 1 return dest def move_cups(cups, destination): di = cups.index(destination) return [cups[0]] + cups[4:di+1] + cups[1:4] + cups[di+1:] def update_current(cups): return cups[1:] + [cups[0]] def step(cups): #assume that current is always first in the list current = cups[0] next_3 = get_next_3(cups) destination = get_destination(cups, next_3) cups = move_cups(cups, destination) cups = update_current(cups) return cups def get_cups_after_1(cups): i1 = cups.index(1) cups_after_1 = cups[i1+1:] + cups[:i1] return "".join(list(map(str,cups_after_1))) with open("data.txt") as data: lines = data.read().splitlines() cups = list(map(int, [x for x in lines[0]])) for ii in range(100): cups = step(cups) print("Answer:",get_cups_after_1(cups)) # Answer: 29385746<file_sep>/2015/day_14/puzzle_1.py from collections import defaultdict import itertools with open("data.txt") as data: lines = data.read().splitlines() class Deer: def __init__(self, name, speed, flytime, resttime): self.name = name self.speed = speed self.flytime = flytime self.resttime = resttime self.flying = True self.time_remaining = flytime self.position = 0 def fly(self): self.position += self.speed def start_flying(self): self.flying = True self.time_remaining = self.flytime self.fly() def start_resting(self): self.flying = False self.time_remaining = self.resttime def tick(self): if self.time_remaining == 0: if self.flying: self.start_resting() else: self.start_flying() else: if self.flying: self.fly() self.time_remaining -= 1 final_time = 2503 deers = [] for line in lines: words = line[:-1].split(' ') deers.append(Deer(words[0], int(words[3]), int(words[6]), int(words[-2]))) for second in range(final_time): for deer in deers: deer.tick() print(max(deers, key=lambda deer: deer.position).position) # Answer: 2660<file_sep>/2020/day_23/puzzle_2.py import itertools from pprint import pprint import numpy as np from copy import deepcopy import operator import re from tqdm import tqdm def get_destination(current_cup, next_3, max_cup_num): dest = current_cup-1 while dest == 0 or dest in next_3: if dest == 0: dest = max_cup_num if dest in next_3: dest -= 1 return dest def step(cup_dict, current_cup, max_cup_num): n1 = cup_dict[current_cup] n2 = cup_dict[n1] n3 = cup_dict[n2] next_3 = [n1,n2,n3] dest = get_destination(current_cup, next_3, max_cup_num) cup_dict[current_cup] = cup_dict[n3] cup_dict[n3] = cup_dict[dest] cup_dict[dest] = n1 return cup_dict, cup_dict[current_cup] def get_answer(cup_dict): n1 = cup_dict[1] n2 = cup_dict[n1] return n1*n2 with open("data.txt") as data: lines = data.read().splitlines() cups = list(map(int, [x for x in lines[0]])) max_cup_num = 10**6 cups = cups + list(range(10,max_cup_num+1)) cup_dict = {cups[ii]: cups[ii+1] for ii in range(len(cups)-1)} cup_dict[cups[-1]] = cups[0] current_cup = cups[0] for ii in range(10**7): cup_dict, current_cup = step(cup_dict, current_cup, max_cup_num) print("Answer:",get_answer(cup_dict)) # Answer: 680435423892<file_sep>/2020/day_06/puzzle_2.py def count_agreement(group_answers): setlist = [] for ga in group_answers: setlist.append(set(ga)) return len(set.intersection(*setlist)) groups = [] with open("data.txt") as data: lines = data.read().splitlines() lines.append('') #ensure we 'flush' the last group to groups list accumulator = [] for line in lines: if line != '': accumulator.append(line) else: groups.append(accumulator) accumulator = [] sum_answers = 0 for group in groups: sum_answers += count_agreement(group) print(sum_answers) # Answer: 3305<file_sep>/2020/day_15/puzzle_1.py import itertools from pprint import pprint with open("data.txt") as data: lines = data.read().splitlines() nums = list(map(int,lines[0].split(","))) def get_last_occurrence(nums, item): nums.reverse() return len(nums) - nums.index(item) - 1 for ii in range(2020): if ii < len(nums): pass else: last_spoken = nums[ii-1] if last_spoken in nums[:ii-1]: last_index = get_last_occurrence(nums[:-1], last_spoken) next_num = ii - 1 - last_index nums.append(next_num) else: nums.append(0) print("Answer:", nums[-1]) # Answer: 447<file_sep>/2015/day_03/puzzle_1.py from collections import defaultdict with open("data.txt") as data: lines = data.readlines() houses = defaultdict(lambda: 0) x, y = 0, 0 houses[(x,y)] += 1 for ii, direction in enumerate(lines[0]): if direction == '<': x -= 1 elif direction == '>': x += 1 elif direction == 'v': y -= 1 elif direction == '^': y += 1 houses[(x,y)] += 1 print(len(houses)) # Answer: 2592<file_sep>/2020/day_11/puzzle_1.py import itertools from pprint import pprint import numpy as np def get_neighbor_occupied_count(old_seats, row, col): neighbors = [old_seats[row-1][col-1], old_seats[row-1][col], old_seats[row-1][col+1], old_seats[row][col-1], old_seats[row][col+1], old_seats[row+1][col-1], old_seats[row+1][col], old_seats[row+1][col+1], ] return neighbors.count('#') def update_seats(old_seats): new_seats = np.copy(old_seats) for row in range(1,len(old_seats)-1): for col in range(1,len(old_seats[0])-1): if old_seats[row][col] == "L": if get_neighbor_occupied_count(old_seats, row, col) == 0: new_seats[row][col]="#" else: new_seats[row][col]=old_seats[row][col] elif old_seats[row][col] == "#": if get_neighbor_occupied_count(old_seats, row, col) >= 4: new_seats[row][col]="L" else: new_seats[row][col]=old_seats[row][col] else: new_seats[row][col]=old_seats[row][col] return new_seats with open("data.txt") as data: lines = data.read().splitlines() lines = [['.']+[c for c in line]+['.'] for line in lines] seats = [['.']*len(lines[0])] seats.extend(lines) seats.extend([['.']*len(lines[0])]) old_seats = np.array(seats) for ii in itertools.count(1): new_seats = update_seats(old_seats) if np.array_equal(old_seats, new_seats): print(new_seats) print("Answer:",np.count_nonzero(new_seats == "#")) break else: old_seats = new_seats.copy() # Answer: 2277<file_sep>/2020/day_13/puzzle_1.py import itertools with open("data.txt") as data: lines = data.read().splitlines() mytime= int(lines[0]) buses = [[ii, int(t)] for ii, t in enumerate(lines[1].split(",")) if t != 'x'] print(buses) minwait = 999999999999999 for bus in buses: waittime = mytime - (mytime%bus[1]) + bus[1] if waittime < minwait: bestbus = bus minwait = waittime print(bestbus[1]*(minwait-mytime)) # Answer: 5257<file_sep>/2020/day_24/puzzle_1.py from copy import deepcopy def parse_line(line): ins, num = line.split(" ") num = int(num) return ins, num def hash_addr(address): return str(address[0]) + "$" + str(address[1]) with open("data.txt") as data: #lines = list(map(int, data.read().splitlines())) lines = data.read().splitlines() dirs = ['ne', 'e', 'se', 'sw', 'w', 'nw'] tiles = {} for data in lines: address = [0,0] instructions = [] pointer = 0 while pointer < len(data): if pointer < len(data)-1 and data[pointer] + data[pointer+1] in dirs: instructions.append(data[pointer] + data[pointer+1]) pointer += 2 else: instructions.append(data[pointer]) pointer += 1 #print(instructions) for ins in instructions: if ins=='ne': address[0]+=0 address[1]+=1 elif ins=='e': address[0]+=1 address[1]+=0 elif ins=='se': address[0]+=1 address[1]+=-1 elif ins=='sw': address[0]+=0 address[1]+=-1 elif ins=='w': address[0]+=-1 address[1]+=0 elif ins=='nw': address[0]+=-1 address[1]+=1 #print(ins, address) #print(address) addr_str = hash_addr(address) if addr_str not in tiles: tiles[addr_str] = 'b' #print("new black", addr_str) else: if tiles[addr_str] == 'b': print("black to white", addr_str) tiles[addr_str] = 'w' elif tiles[addr_str] == 'w': print("white to black", addr_str) tiles[addr_str] = 'b' black = len([v for k, v in tiles.items() if v=='b']) print("Answer:",black) # Answer: 330<file_sep>/2020/day_05/puzzle_1.py def get_seat_id(seat): row = seat[:7].replace("F","0").replace("B","1") col = seat[7:].replace("L","0").replace("R","1") return int(row+col,2) with open("data.txt") as data: lines = data.read().splitlines() seat_ids = [] for line in lines: seat_ids.append(get_seat_id(line)) print(max(seat_ids)) # Answer: 922<file_sep>/2020/day_09/puzzle_2.py target = 15690279 with open("data.txt") as data: lines = list(map(int, data.read().splitlines())) for ii in range(len(lines)): for jj, line in enumerate(lines): total = sum(lines[ii:jj]) if total == target: print(min(lines[ii:jj])+max(lines[ii:jj])) exit(0) elif total > target: break # Answer: 2174232<file_sep>/2015/day_07/puzzle_1.py import re with open("data.txt") as data: lines = data.read().splitlines() wires = {} for line in lines: left, out = line.split(' -> ') wires[out] = left def memoize(f): # taken from https://www.python-course.eu/python3_memoization.php memo = {} def helper(x): if x not in memo: memo[x] = f(x) return memo[x] return helper @memoize def get_signal(start_wire): if re.match(r'^\d+$', start_wire.strip()): signal = start_wire else: input_str = wires[start_wire] if "NOT" in input_str: signal = ~ get_signal(input_str.split(' ')[1]) + 2**16 elif "AND" in input_str: signal = get_signal(input_str.split(' ')[0]) & get_signal(input_str.split(' ')[2]) elif "OR" in input_str: signal = get_signal(input_str.split(' ')[0]) | get_signal(input_str.split(' ')[2]) elif "LSHIFT" in input_str: signal = get_signal(input_str.split(' ')[0]) << get_signal(input_str.split(' ')[2]) elif "RSHIFT" in input_str: signal = get_signal(input_str.split(' ')[0]) >> get_signal(input_str.split(' ')[2]) else: signal = get_signal(input_str) return int(signal) print(get_signal('a')) # Answer: 3176<file_sep>/2020/day_06/puzzle_1.py def count_distinct(abc): return len(dict.fromkeys(abc)) groups = [] with open("data.txt") as data: lines = data.read().splitlines() lines.append('') #ensure we 'flush' the last group to groups list accumulator = [] for line in lines: if line != '': accumulator.append(line) else: groups.append(''.join(accumulator)) accumulator = [] sum_answers = 0 for group in groups: sum_answers += count_distinct(group) print(sum_answers) # Answer: 6521<file_sep>/2020/day_08/puzzle_2.py def parse_line(line): ins, num = line.split(" ") num = int(num) return ins, num groups = [] with open("data.txt") as data: lines = data.read().splitlines() def get_instructions(): instructions = {} for ii, line in enumerate(lines): ins, num = parse_line(line) instructions[ii] = {"ins": ins, "num": num, "vis": False} return instructions instructions = get_instructions() for ii in range(len(instructions)): instructions = get_instructions() if instructions[ii]['ins'] == 'jmp': instructions[ii]['ins'] = 'nop' elif instructions[ii]['ins'] == 'nop': instructions[ii]['ins'] = 'jmp' else: continue # no change required to test for this step try: accumulator = 0 step = 0 while True: if step==len(instructions): break #done if instructions[step]['vis'] == True: raise Exception if instructions[step]['ins'] == "acc": accumulator += instructions[step]['num'] instructions[step]['vis'] = True step += 1 elif instructions[step]['ins'] == "jmp": instructions[step]['vis'] = True step += instructions[step]['num'] else: instructions[step]['vis'] = True step += 1 except Exception: continue print("Answer:",accumulator) break # Answer: 1976<file_sep>/2020/day_04/puzzle_1.py def is_valid(passport): required_elements = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid', #'cid', ] passport_elements = passport.split(' ') passport_elements = [pe.split(':')[0] for pe in passport_elements] passport_elements.sort() print(passport_elements) for req_el in required_elements: if req_el not in passport_elements: return False return True passports = [] with open("data.txt") as data: lines = data.read().splitlines() lines.append('') #ensure we 'flush' the last passport to passports list accumulator = [] for line in lines: if line != '': accumulator.append(line) else: passports.append(' '.join(accumulator)) accumulator = [] num_valid = 0 for passport in passports: if is_valid(passport): print("valid") num_valid += 1 print(num_valid) # Answer: 254<file_sep>/2015/day_09/puzzle_2.py import networkx as nx with open("data.txt") as data: lines = data.read().splitlines() G = nx.Graph() cities = set() for line in lines: l, r = line.split(' = ') c1, c2 = l.split(' to ') G.add_edge(c1, c2, weight = int(r)) cities.add(c1) cities.add(c2) sp = dict(nx.all_pairs_shortest_path(G)) def get_length(G, path): total_length = 0 for ii in range(len(path)-1): run_length = G[path[ii]][path[ii+1]]['weight'] total_length += run_length return total_length longest_path = 0 for city1 in cities: for city2 in cities: if city1 == city2: break all_paths = [path for path in nx.all_simple_paths(G, city1, city2)] temp_longest_path = get_length(G, max(all_paths, key=lambda path: get_length(G, path))) if temp_longest_path > longest_path: longest_path = temp_longest_path print(longest_path) # Answer: 909<file_sep>/2020/day_03/puzzle_1.py # slope is expressed as (delta_y, delta_x), y increasing downwards and x increasing to the right def get_next_pos(slope, x1, y1, shape_width): y2 = y1 + slope[0] x2 = (x1 + slope[1]) % shape_width return x2, y2 array = [] with open("data.txt") as data: lines = data.read().splitlines() for line in lines: array.append(line) shape_width = len(array[0]) shape_height = len(array) x = 0 y = 0 slope = [1,3] print(array) num_trees = 0 while y < shape_height-1: x, y = get_next_pos(slope, x, y, shape_width) if array[y][x] == "#": num_trees += 1 print(num_trees) # Answer: 156<file_sep>/2020/day_12/puzzle_1.py def parse_line(line): return line[0], int(line[1:]) def add(a, b): return a+b def subtract(a, b): return a-b dirmap = {"N": ("y", add), "S": ("y", subtract), "E": ("x", add), "W": ("x", subtract)} frmap = {"F": add, "R": subtract} def go(line): action, num = parse_line(line) if action in "NEWS": coord, func = dirmap[action] state[coord]=func(state[coord], num) elif action == "R": state["dir"] = "NESWNESW"["NESW".index(state["dir"])+num//90] #awful! elif action == "L": state["dir"] = "WSENWSEN"["WSEN".index(state["dir"])+num//90] elif action == "F": coord, func = dirmap[state["dir"]] state[coord] = func(state[coord], num) print(action, num, state) with open("data.txt") as data: lines = data.read().splitlines() state = {"dir": "E", "x": 0, "y": 0} for line in lines: go(line) print(abs(state['x'])+abs(state['y'])) # Answer: 759<file_sep>/2020/day_01/puzzle_2.py with open("data.txt") as data: lines = data.readlines() for ii, line in enumerate(lines): num1 = int(line) for jj, line2 in enumerate(lines): num2=int(line2) for kk, line3 in enumerate(lines): num3=int(line3) if ii!=jj and jj!=kk and ii!=kk and num1+num2+num3==2020: print(num1*num2*num3) break # Answer: 6964490<file_sep>/2020/day_22/puzzle_1.py import itertools from pprint import pprint def score(cards): score = 0 for ii, card in enumerate(cards[::-1]): score += (1+ii)*card return score with open("data.txt") as data: lines = data.read().splitlines() cards1 = [] cards2 = [] adding_cards_to = cards1 for line in lines: if line in ["", "Player 1:"]: continue elif line == "Player 2:": adding_cards_to = cards2 continue adding_cards_to.append(int(line)) while len(cards1) > 0 and len(cards2) > 0: c1 = cards1.pop(0) c2 = cards2.pop(0) if c1 > c2: cards1.extend([c1, c2]) elif c2 > c1: cards2.extend([c2, c1]) if len(cards1) > 0: print("Answer:", score(cards1)) else: print("Answer:", score(cards2)) # Answer: 31754<file_sep>/2015/day_05/puzzle_2.py import re with open("data.txt") as data: lines = data.read().splitlines() def is_nice(word): pairs = [] for ii in range(len(word)-1): newpair = word[ii]+word[ii+1] if newpair in pairs[:-1]: # [:-1] because the most recent pair added would be an overlap break else: pairs.append(newpair) else: return False for ii in range(2,len(word)): if word[ii-2] == word[ii]: break else: return False return True count_nice = 0 for ii, line in enumerate(lines): if is_nice(line): count_nice += 1 print(count_nice) # Answer: 51<file_sep>/2015/day_09/puzzle_1.py import networkx as nx with open("data.txt") as data: lines = data.read().splitlines() G = nx.Graph() for line in lines: l, r = line.split(' = ') c1, c2 = l.split(' to ') G.add_edge(c1, c2, weight = int(r)) sp = dict(nx.all_pairs_shortest_path(G)) shortest_path = nx.algorithms.approximation.traveling_salesman.traveling_salesman_problem(G, cycle=False, method=nx.algorithms.approximation.traveling_salesman.greedy_tsp) total_length = 0 for ii in range(len(shortest_path)-1): run_length = G[shortest_path[ii]][shortest_path[ii+1]]['weight'] total_length += run_length print(total_length) # Answer: 117<file_sep>/2015/day_04/puzzle_2.py from hashlib import md5 with open("data.txt") as data: lines = data.readlines() secret = lines[0] for ii in range(10000000): md5hash = md5((secret + str(ii)).encode()).hexdigest() if md5hash[:6] == '000000': print(ii) break # Answer: 9958218<file_sep>/2020/day_14/puzzle_2.py import itertools from pprint import pprint from copy import deepcopy def parse_line(line): a, b = line.split(" = ") a = int(a[4:-1]) return a, int(b) def get_floating_mems(binval): if len(binval) == 0: return [] mems = [[]] for ii in range(len(binval)): if binval[ii] != 'X': for mem in mems: mem.append(binval[ii]) else: newmems1 = [mem + ['1'] for mem in mems] newmems0 = [mem + ['0'] for mem in mems] mems = newmems1 + newmems0 return mems def get_memory_addresses(mask, val): binval = [x for x in bin(val)[2:].zfill(len(mask))] for ii in range(len(mask)): if mask[-ii] =="1": binval[-ii] = "1" elif mask[-ii] =="X": binval[-ii] = "X" binvals = get_floating_mems(binval) decvals = [] for b in binvals: decvals.append(int("".join(b), 2)) return decvals with open("data.txt") as data: lines = data.read().splitlines() vals = {} for ii, line in enumerate(lines): if line[:4] == "mask": mask = line[7:] continue mem, val = parse_line(line) mems = get_memory_addresses(mask, mem) for mem in mems: vals[mem] = val print("Answer:",sum(vals.values())) # Answer: 4288986482164<file_sep>/2020/day_14/puzzle_1.py import itertools from pprint import pprint def parse_line(line): a, b = line.split(" = ") a = int(a[4:-1]) return a, int(b) def apply_mask(mask, val): binval = [x for x in bin(val)[2:].zfill(len(mask))] for ii in range(len(mask)): if mask[-ii] !="X": binval[-ii] = mask[-ii] return int("".join(binval), 2) with open("data.txt") as data: lines = data.read().splitlines() vals = {} for line in lines: if line[:4] == "mask": mask = line[7:] continue mem, val = parse_line(line) val = apply_mask(mask, val) vals[mem]=val print("Answer:",sum(vals.values())) # Answer: 6386593869035<file_sep>/2020/day_21/puzzle_2.py import itertools from pprint import pprint def parse_line(line): ing_str, aller_str = line.split(" (contains ") ingredients = set(ing_str.split(" ")) allergens = aller_str[:-1].split(", ") return allergens, ingredients with open("data.txt") as data: lines = data.read().splitlines() allergen_dict = {} ingredients_set = set() ingredient_counts = {} for ii, line in enumerate(lines): allergens, ingredients = parse_line(line) for allergen in allergens: if allergen not in allergen_dict: allergen_dict[allergen] = set(ingredients) else: allergen_dict[allergen] = allergen_dict[allergen].intersection(ingredients) ingredients_set = ingredients_set.union(ingredients) for ingredient in ingredients: if ingredient not in ingredient_counts: ingredient_counts[ingredient] = 1 else: ingredient_counts[ingredient] += 1 ad2 = {} while len(ad2) < len(allergen_dict): for allergen in allergen_dict: if len(allergen_dict[allergen]) == 1: ingredient_to_remove = next(iter(allergen_dict[allergen])) ad2[allergen] = ingredient_to_remove for allergen in allergen_dict: if ingredient_to_remove in allergen_dict[allergen] and len(allergen_dict[allergen]) > 1: allergen_dict[allergen].remove(ingredient_to_remove) #invert dictionary inverted = ",".join([v for k, v in sorted(ad2.items(), key=lambda item: item[0])]) print("Answer:",inverted) # Answer: ntft,nhx,kfxr,xmhsbd,rrjb,xzhxj,chbtp,cqvc<file_sep>/2020/day_16/puzzle_1.py import itertools from pprint import pprint def parse_rules(line): field, rules = line.split(": ") r1, r2 = rules.split(" or ") r1min, r1max = list(map(int, r1.split("-"))) r2min, r2max = list(map(int, r2.split("-"))) #return field, lambda x: r1min <= x <= r1max or r2min <= x <= r2max return lambda x: r1min <= x <= r1max or r2min <= x <= r2max with open("data.txt") as data: lines = data.read().splitlines() section = 0 rules = {} other_tickets = {} for ii, line in enumerate(lines): if section == 0: if line == "": section += 1 else: func = parse_rules(line) rules[ii] = func elif section == 1: if line == "": section += 1 elif line == "your ticket:": continue else: my_ticket = list(map(int,line.split(","))) elif section == 2: if line == "nearby tickets:": continue else: other_tickets[ii] = list(map(int,line.split(","))) invalid_tickets = [] for ii, t in other_tickets.items(): for f in t: if not any([rules[r](f) for r in rules]): invalid_tickets.append(f) print(sum(invalid_tickets)) # Answer: 22977<file_sep>/2020/day_20/puzzle_2.py import math def get_edge(tile, edge): edges = {"top": tile[0], "bottom": tile[-1], "left": [t[0] for t in tile], "right": [t[-1] for t in tile] } return edges[edge] def get_edges(tile): return get_edge(tile, "top"), get_edge(tile, "bottom"), get_edge(tile, "left"), get_edge(tile, "right") def rotate_tile(tile): # https://stackoverflow.com/questions/5164642/python-print-a-generator-expression return list(zip(*tile[::-1])) def flip_tile(tile): return [t[::-1] for t in tile] def get_permutations(tile): functions_list = [lambda x: x, lambda x: rotate_tile(x), lambda x: rotate_tile(rotate_tile(x)), lambda x: rotate_tile(rotate_tile(rotate_tile(x))), lambda x: flip_tile(x), lambda x: flip_tile(rotate_tile(x)), lambda x: flip_tile(rotate_tile(rotate_tile(x))), lambda x: flip_tile(rotate_tile(rotate_tile(rotate_tile(x))))] return [f(tile) for f in functions_list] def edge_match(tile1, tile2): e1 = get_edges(tile1) e2 = get_edges(tile2) for edge1 in e1: for edge2 in e2: if edge1 == edge2: return True return False def compare_tiles(tile1, tile2): match_count = 0 for ii, t2p in enumerate(get_permutations(tile2)): if edge_match(tile1, t2p): match_count+=1 return match_count def get_matches(tile1, unused_tiles): matches = [] for tilenum2, tile2 in unused_tiles.items(): match = compare_tiles(tile1['tile'], tile2['tile']) if match>0: matches.append(tilenum2) return matches def single_edge_match(tile1edge, tile2): for t2p in get_permutations(tile2): e2 = get_edges(t2p) for edge2 in e2: if tile1edge == edge2: return t2p return False def opposite(input_dir): dirs = {'left': 'right', 'right': 'left', 'top': 'bottom', 'bottom': 'top'} return dirs[input_dir] def specific_edge_match(tile1edge, tile2, tile2edgedir): for t2p in get_permutations(tile2): tile2edge = get_edge(t2p, tile2edgedir) if tuple(tile1edge) == tuple(tile2edge): return t2p return False def get_oriented_match(tile1, tile1edgedir, unused_tiles, log=False): if log: print(tile1) matches = [] tile1edge = get_edge(tile1, tile1edgedir) if log: print(tile1edge) for tile2 in unused_tiles.values(): if log: print(tile2) match = specific_edge_match(tile1edge, tile2['tile'], opposite(tile1edgedir)) if match: return tile2['tileNum'], match return False, False def unused(tiles, jigsaw): tiles_in_jigsaw = [t[0] for line in jigsaw for t in line] unused_tiles = {tile: tiles[tile] for tile in tiles if tile not in tiles_in_jigsaw} return unused_tiles def parse_tiles(lines): tiles = {} tile = [] for ii, line in enumerate(lines): if line[:4]=="Tile": x, tilenum = line.split(" ") tilenum = int(tilenum[:-1]) tiles[tilenum] = [] elif line=="": tiles[tilenum] = {'tile': tile, 'tileNum': tilenum} tile = [] else: tile.append([l for l in line]) return tiles def remove_border(tile): return [row[1:-1] for row in tile[1:-1]] def get_big_image(jigsaw): jigsaw_dim = len(jigsaw[0]) tile_dim = len(jigsaw[0][0][1])-2 big_image = [['x']*tile_dim*jigsaw_dim for c in range(tile_dim*jigsaw_dim)] for ii, row in enumerate(jigsaw): for jj, jigsawtile in enumerate(row): borderless = remove_border(jigsawtile[1]) #print("jj",jj) for ii2, row2 in enumerate(borderless): #print(row2) for jj2, col2 in enumerate(row2): big_image[ii*tile_dim+ii2][jj*tile_dim+jj2] = borderless[ii2][jj2] return big_image def get_monster(): return [ ' # ', '# ## ## ###', ' # # # # # # ' ] def count_monster_hashes(): return len([cell for row in get_monster() for cell in row if cell == "#"]) def get_monster_offsets(): monster = get_monster() offsets = [] for ii, row in enumerate(monster): for jj, col in enumerate(row): if monster[ii][jj] == "#": offsets.append((ii, jj)) return offsets def check_monster(big_image, row, col): monster_offsets = get_monster_offsets() big_image_shape = (len(big_image), len(big_image[0])) for offset in monster_offsets: search_x = row+offset[0] search_y = col+offset[1] if search_x > big_image_shape[0]-1 or search_y > big_image_shape[1]-1 or big_image[search_x][search_y] != "#": return False return True def get_monsters(big_image): monsters = 0 for row in range(len(big_image)): for col in range(len(big_image[0])): if check_monster(big_image, row, col): monsters += 1 return monsters def count_seas(big_image, monsters_count): return len([cell for row in big_image for cell in row if cell == "#"]) - count_monster_hashes()*monsters_count with open("data.txt") as data: lines = data.read().splitlines() tiles = parse_tiles(lines) corners = [] for tilenum1, tile1 in tiles.items(): matches = get_matches(tile1, {i:tiles[i] for i in tiles if i!=tilenum1}) if len(matches) == 2: corners.append(tilenum1) corner1 = corners[0] jigsaw_dim = int(math.sqrt(len(tiles))) jigsaw = [[] for x in range(jigsaw_dim)] # This represents the joined-up tiles, in order latestnum = corner1 for orientation in get_permutations(tiles[corner1]['tile']): #Figure out which way to orient the first corner so that there's a match to the right and bottom match_num, oriented = get_oriented_match(orientation, 'right', {tile: tiles[tile] for tile in tiles if tile != corner1}) match_num2, oriented2 = get_oriented_match(orientation, 'bottom', {tile: tiles[tile] for tile in tiles if tile != corner1}) if match_num and match_num2: jigsaw[0].append((corner1, orientation)) break #Fill out the top row for ii in range(jigsaw_dim-1): match_num, oriented = get_oriented_match(jigsaw[0][ii][1], 'right', unused(tiles, jigsaw)) jigsaw[0].append((match_num, oriented)) #Fill down each column for col in range(jigsaw_dim): for row in range(1, jigsaw_dim): match_num, oriented = get_oriented_match(jigsaw[row-1][col][1], 'bottom', unused(tiles, jigsaw)) jigsaw[row].append((match_num, oriented)) big_image = get_big_image(jigsaw) for orientation in get_permutations(big_image): monsters_count = get_monsters(orientation) if monsters_count > 0: print("Answer:",count_seas(big_image, monsters_count)) break # Answer: 2209<file_sep>/2015/day_03/puzzle_2.py from collections import defaultdict with open("data.txt") as data: lines = data.readlines() houses = defaultdict(lambda: 0) x, y = 0, 0 rx, ry = 0, 0 houses[(x,y)] += 1 houses[(rx,ry)] += 1 for ii, direction in enumerate(lines[0]): if ii % 2 == 0: if direction == '<': x -= 1 elif direction == '>': x += 1 elif direction == 'v': y -= 1 elif direction == '^': y += 1 houses[(x,y)] += 1 else: if direction == '<': rx -= 1 elif direction == '>': rx += 1 elif direction == 'v': ry -= 1 elif direction == '^': ry += 1 houses[(rx,ry)] += 1 print(len(houses)) # Answer: 2360<file_sep>/2015/day_08/puzzle_2.py import re with open("data.txt") as data: lines = data.read().splitlines() def len_inmem(string): string2 = string string2 = re.sub(r'"', '--', string2) # "escape" quotes string2 = re.sub(r'\\', '--', string2) # "escape" backslashes string2 = string2 + "--" # add 2 more chars for external quotes return len(string2) count_literal = 0 count_inmem = 0 for line in lines: l1 = len(line) l2 = len_inmem(line) count_literal += l1 count_inmem += l2 print(count_inmem - count_literal) # Answer: 1342<file_sep>/2020/day_08/puzzle_1.py def parse_line(line): ins, num = line.split(" ") num = int(num) return ins, num groups = [] with open("data.txt") as data: lines = data.read().splitlines() instructions = {} for ii, line in enumerate(lines): ins, num = parse_line(line) instructions[ii] = {"ins": ins, "num": num, "vis": False} accumulator = 0 step = 0 while True: if instructions[step]['vis'] == True: print(accumulator) break if instructions[step]['ins'] == "acc": accumulator += instructions[step]['num'] instructions[step]['vis'] = True step += 1 elif instructions[step]['ins'] == "jmp": instructions[step]['vis'] = True step += instructions[step]['num'] else: instructions[step]['vis'] = True step += 1 # Answer: 1709<file_sep>/2020/day_18/puzzle_2.py import itertools from pprint import pprint import numpy as np from copy import deepcopy import operator def get_matching_close_paren(section, start): paren_stack = 0 for ii, char in enumerate(section): if ii < start: continue if char == '(': paren_stack += 1 elif char == ')': paren_stack -= 1 if paren_stack == 0: return ii def remove_one(expression, op): lookup = {'+': operator.add, '*': operator.mul} func = lookup[op] ind = expression.index(op) new_expression = expression[:ind-1] + [func(int(expression[ind-1]), int(expression[ind+1]))] + expression[ind+2:] return new_expression def evaluate_no_parens(expression): expression = expression.split(" ") while '+' in expression: expression = remove_one(expression, '+') while '*' in expression: expression = remove_one(expression, '*') return expression[0] def evaluate(section): if '(' in section: for ii, char in enumerate(section): if char == '(': matching_close_paren = get_matching_close_paren(section, ii) inside_parens = evaluate(section[ii+1:matching_close_paren]) return evaluate(section[:ii] + str(inside_parens) + section[matching_close_paren+1:]) else: return evaluate_no_parens(section) with open("data.txt") as data: lines = data.read().splitlines() print("Answer:",sum([evaluate(line) for line in lines])) # Answer: 45283905029161<file_sep>/2015/day_04/puzzle_1.py from hashlib import md5 with open("data.txt") as data: lines = data.readlines() secret = lines[0] for ii in range(1000000): md5hash = md5((secret + str(ii)).encode()).hexdigest() if md5hash[:5] == '00000': print(ii) break # Answer: 346386<file_sep>/2015/day_06/puzzle_2.py import re with open("data.txt") as data: lines = data.read().splitlines() class Grid: side_length = 1000 def __init__(self): self.lights = [[0 for ii in range(self.side_length)] for jj in range(self.side_length)] def _apply_to_rectangle(self, c1, c2, r1, r2, func): for cc in range(c1,c2+1): for rr in range(r1,r2+1): self.lights[cc][rr] = func(self.lights[cc][rr]) def off(self, c1, c2, r1, r2): self._apply_to_rectangle(c1,c2,r1,r2,lambda x: max(x - 1, 0)) def on(self, c1, c2, r1, r2): self._apply_to_rectangle(c1,c2,r1,r2,lambda x: x + 1) def toggle(self, c1, c2, r1, r2): self._apply_to_rectangle(c1,c2,r1,r2,lambda x: x + 2) def count_on(self): count = 0 for col in self.lights: for light in col: count += light return count grid = Grid() for line in lines: matches = re.findall(r"\d+", line) c1 = int(matches[0]) r1 = int(matches[1]) c2 = int(matches[2]) r2 = int(matches[3]) if "toggle" in line: grid.toggle(c1, c2, r1, r2) elif "turn on" in line: grid.on(c1, c2, r1, r2) elif "turn off" in line: grid.off(c1, c2, r1, r2) print(grid.count_on()) # Answer: 543903<file_sep>/2015/day_08/puzzle_1.py import re with open("data.txt") as data: lines = data.read().splitlines() def len_inmem(string): string2 = string[1:-1] # remove outside quotes string2 = re.sub(r'\\"', '"', string2) # remove escaped quotes string2 = re.sub(r'\\\\', '$', string2) # remove double-backslash string2 = re.sub(r'\\x..', '$', string2) # remove hex return len(string2) count_literal = 0 count_inmem = 0 for line in lines: l1 = len(line) l2 = len_inmem(line) count_literal += l1 count_inmem += l2 print(count_literal - count_inmem) # Answer: 1342
e58bd4d6dc79043b96e4668bb9973cc6ef3aeee1
[ "Python" ]
69
Python
jackcarter/advent_of_code_2020
6c2698d6277750c0af31993a7f711191ab7ab367
da8a23e322a1f1cbcaa068fb8c0dc62ce665ced1
refs/heads/master
<repo_name>kkimatx/RBP_project<file_sep>/retrieve_seqs.py ## Given the sequence positions in the LINK-Seq database, retrieve sequences ## from local human genome, find the proper strand, and convert to RNA import os import numpy as np import pandas as pd import re import pysam as pys import sys def retrieve_seq(RBP, flanking = True, n = 60,neg_con=False): """Given a chrosome position in the database, fetch sequence,\ convert to proper RNA strand, and add the sequence column to \ the database """ #import local genome data print('fetching genome...') genome = pys.Fastafile("GRCh38.p12.genome.fa") print('genome fetched') prot_dir = os.getcwd() + '/' + RBP if neg_con == True: db1 = pd.read_csv(prot_dir + '/neg_seq_locs.csv',index_col=0) else: db1 = pd.read_csv(prot_dir + '/seq_dat_HEKc2.csv',index_col=0) strand = db1['Strand'] pos = db1['Position'] #split the position string into [chr#,start pos, end pos] pos1 = pos.apply(lambda x: re.split('[: -]',x)) chrom = pos1.apply(lambda x: x[0]).rename('chrom') start = pos1.apply(lambda x: int(x[1])).rename('start') end = pos1.apply(lambda x: int(x[2])).rename('end') #combine the three info into one dataframe, include flanking sequences if flanking == True: five_start = pos1.apply(lambda x: int(x[1])-n).rename('5_start') three_end = pos1.apply(lambda x: int(x[2])+n).rename('3_end') seqdb = pd.concat([chrom,start,end,five_start,three_end,strand],axis=1) five_seq_list = [] three_seq_list = [] else: seqdb = pd.concat([chrom,start,end,strand],axis=1) #complement dictionary for fetching negative strands complement = {'A':'T','T':'A','G':'C','C':'G','N':'N'} #reverse complement lambda rev_compl = lambda x: ''.join([{'A':'T','C':'G','G':'C','T':'A'}[base] \ for base in x][::-1]) #counter seq_list= [] total = seqdb.shape[0] count = 0 #start a list of fetched sequences, and using a for loop, #fetch sequences for each row, convert negative strands, and convert to RNA. for idx,row in seqdb.iterrows(): sequence = genome.fetch(row['chrom'],row['start'],row['end']) #if in negative strand, find reverse complement if row['Strand'] == '-': sequence = rev_compl(sequence) sequence = sequence.replace('T','U') seq_list.append(sequence) if flanking == True: five_seq = genome.fetch(row['chrom'],row['5_start'],row['start']) three_seq = genome.fetch(row['chrom'],row['end'],row['3_end']) if row['Strand'] == '-': five_seq = rev_compl(five_seq).replace('T','U') three_seq = rev_compl(three_seq).replace('T','U') #since this is RC strand, switch out #five and three prime flanks five_seq_list.append(three_seq) three_seq_list.append(five_seq) else: five_seq = five_seq.replace('T','U') three_seq = three_seq.replace('T','U') five_seq_list.append(five_seq) three_seq_list.append(three_seq) #counter count +=1 countstr = 'sequence ' + str(count) + ' of ' + str(total) sys.stdout.write("\r{}".format(countstr)) db1['sequence'] = seq_list if flanking == True: db1['5 flanking seq'] = five_seq_list db1['3 flanking seq'] = three_seq_list if neg_con == True: db1.to_csv(prot_dir + '/neg_con_seqs_RNA.csv') else: db1.to_csv(prot_dir + '/seq_dat_HEKc3_RNA.csv') def make_fasta(RBP, neg_con = False): """Make fasta file from sequences to feed in to DREME for motif searches""" prot_dir = os.getcwd() + '/' + RBP #import sequence data to convert to a fasta file if neg_con == True: db1 = pd.read_csv(prot_dir + '/neg_con_seqs_RNA.csv') else: db1 = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA.csv') #initiate text files if neg_con == False: filename = prot_dir + '/' + RBP + '_fasta_seqs_RNA' txt = open(filename+'.txt','w') else: filename = prot_dir + '/' + RBP + '_neg_fasta_seqs_RNA' txt = open(filename+'.txt','w') #counters total = db1.shape[0] count = 0 #For each sequence entry, write a fasta line of seq ID and the sequence for idx, row in db1.iterrows(): txt.write('>' + row['Gene Name'] + row['Position'] + '\r\n') txt.write(row['sequence'] + '\r\n') count += 1 countstr = 'sequence ' + str(count) + ' of ' + str(total) sys.stdout.write("\r{}".format(countstr)) #close the text file, rename extension to fasta format txt.close() os.rename(filename+'.txt',filename+'.fa' ) <file_sep>/motif_finder.py import re import os import numpy as np import pandas as pd import sys IUPAC_dict = {'A':'A','C':'C','G':'G','T':'T','U':'T','R':'[AG]','Y':'[CT]','S':'[GC]', 'W':'[AT]','K':'[GT]','M':'[AC]','B':'[CGT]','D':'[AGT]','H':'[ACT]', 'V':'[ACG]','N':'[ACGT]'} struct_dict = {'H':0,'I':1,'B':2,'S':3,'M':4,'E':5} complement = {'A':'T','T':'A','G':'C','C':'G','N':'N'} # def create_features(): # motif = 'AGTW' #some motif (should be an input to the function) # seq = 'AGTAAGTTTTGA' #some sequence (also an input) # struct = 'EEMMSSHHSSEE' #corresponding structure (also input) # motif = motif.upper() #change to upper case # r_motif = motif[::-1] #also search for the reverse motif # ambig_motif = ''.join([IUPAC_dict[x] for x in list(motif)]) #create regex from IUPAC degenerate alphabet # r_ambig_motif = ''.join([IUPAC_dict[x] for x in list(r_motif)]) #for reverse as well # seq = seq.upper() #change to upper case # seq = seq.replace('U','T') #get rid of U's # matches = [struct[m.start():m.end()] for m in re.finditer(ambig_motif,seq)] \ # +[struct[m.start():m.end()] for m in re.finditer(r_ambig_motif,seq)] #search for all instances of motif, return structure # features = np.zeros(6) #how many motifs occured at each structure type # for ii in range(len(matches)): # struct_hit = set(list(matches[ii])) # for key,val in struct_dict.items(): # if key in struct_hit: # features[val]+=1 #add feature if motif occurs over structure type (with priorites set in dicitionary, e.g if the motif overlaps a stem and hairpin it will be noted as a hairpin) # break # return features def add_features_to_pandas(RBP,structuresize=10,attract=False,peaks_as_negs=False): #adds a column to seq_df that gives number of motif instances on the sequence. add along column to find total number of motif instances prot_dir = os.getcwd() + '/' +RBP pos_seq_df = pd.read_csv(prot_dir+'/seq_dat_HEKc3_RNA_with_struc.csv',index_col=0) pos_seq_df = pos_seq_df[pos_seq_df['sequence'].apply(lambda x: len(x))<30] if peaks_as_negs: neg_seq_df = pd.read_csv(prot_dir+'/neg_peaks_with_struc.csv',index_col=0) else: neg_seq_df = pd.read_csv(prot_dir+'/neg_con_seqs_RNA_with_struc.csv',index_col=0) motif_df = pd.read_csv('~/RBP_project/'+RBP+'/motifs.csv',index_col=0) motifname_list = list(motif_df.loc[:,'name']) motif_list = list(motif_df.loc[:,'seq']) if attract: attract_df = pd.read_csv('~/RBP_project/'+RBP+'/attract_motifs.csv',index_col=0) motifname_list += ['attract_m'+str(x) for x in range(attract_df.shape[0])] motif_list += list(attract_df.loc[:,'Motif']) pos_length = pos_seq_df.shape[0] neg_length = neg_seq_df.shape[0] feature_names = ['feature: %s/%s' %(motif_name,struc_name) for motif_name in motifname_list for struc_name in struct_dict.keys()] for i in range(len(feature_names)): pos_seq_df[feature_names[i]] = 0 pos_seq_df[feature_names[i]].astype('float') neg_seq_df[feature_names[i]] = 0 neg_seq_df[feature_names[i]].astype('float') # if i %100==0: # countstr = 'at sequence '+str(i) # sys.stdout.write("\r{}".format(countstr)) pos_seq_df[feature_names] = pos_seq_df.apply(find_features_in_sequence,args = (motif_list,structuresize), axis=1,result_type = 'expand') neg_seq_df[feature_names] = neg_seq_df.apply(find_features_in_sequence,args = (motif_list,structuresize), axis=1,result_type = 'expand') pos_seq_df.to_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv') if peaks_as_negs: neg_seq_df.to_csv(prot_dir + '/neg_peaks_with_features.csv') else: neg_seq_df.to_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv') def find_features_in_sequence(rows,motif_list,structuresize): if rows[0]%1000==0: countstr = 'at sequence '+str(rows[0]) sys.stdout.write("\r{}".format(countstr)) #function to apply to panda, finds all isntances of motif for given sequence seq = rows['sequence'] struc = rows['structure'] seq = seq.upper() #change to upper case seq = ''.join(['T' if x=='U' else x for x in seq]) all_features = [] for jj in range(len(motif_list)): motif = motif_list[jj] motif = motif.upper() #change to upper case ambig_motif = ''.join([IUPAC_dict[x] for x in list(motif)]) #create regex from IUPAC degenerate alphabet Max = len(struc) matches = [struc[np.max([0,m.start()+round((len(motif)-structuresize)/2)]):np.min([Max,m.start()+round((len(motif)+structuresize)/2)])] for m in re.finditer('(?='+ambig_motif+')',seq)] #search for all instances of motif, return structure features = [0]*6 #how many motifs occured at each structure type for ii in range(len(matches)): struct_hit = list(matches[ii]) for key,val in struct_dict.items(): features[val]+=struct_hit.count(key)/len(struct_hit) #add feature if motif occurs over structure type (with priorites set in dicitionary, e.g if the motif overlaps a stem and hairpin it will be noted as a hairpin) all_features+=features return all_features def add_instances_to_pandas(RBP,Index): #adds a column to seq_df that gives number of motif instances on the sequence. add along column to find total number of motif instances prot_dir = os.getcwd() + '/' +RBP pos_seq_df = pd.read_csv(prot_dir+'/seq_dat_HEKc3_RNA.csv',index_col=0) neg_seq_df = pd.read_csv(prot_dir+'/neg_con_seqs_RNA.csv',index_col=0) motif_df = pd.read_csv('~/RBP_project/'+RBP+'/motifs.csv',index_col=0) motifname = motif_df.loc[Index,'name'] motif = motif_df.loc[Index,'seq'] print(motif) pos_seq_df['instances of motif: '+motifname] = pos_seq_df.apply(count_instances,args = (motif,), axis=1) neg_seq_df['instances of motif: '+motifname] = neg_seq_df.apply(count_instances,args = (motif,), axis=1) return pos_seq_df,neg_seq_df def count_instances(rows,motif): #function to apply to panda, finds all isntances of motif for given sequence seq = rows['sequence'] motif = motif.upper() #change to upper case ambig_motif = ''.join([IUPAC_dict[x] for x in list(motif)]) #create regex from IUPAC degenerate alphabet seq = seq.upper() #change to upper case seq = ''.join(['T' if x=='U' else x for x in seq]) matches = [(m.start(),m.start()+len(motif)) for m in re.finditer('(?='+ambig_motif+')',seq)] #search for all instances of motif, return structure # matches = list(set(matches)) return len(matches)>0 # if len(matches)>0: # return seq[matches[0][0]:matches[0][1]] # else: # ''<file_sep>/README.md ## RBP_project #### Identifying which RNA sequences that RNA-binding-proteins (RBPs) can bind to could be an important phase in biological/bioinformatic investigations. Generally, one can use consensus RNA sequences of RBP binding sites to search for matching sequences in a transcriptome (transcripted parts of the genome). This project utilizes random forest algorithm to predict RNA-binding sites given a sequence, using features of the sequence such as presence and location of consensus seqs, secondary structure of RNA, nearby protein binding sites, characteristics of the flanking regions, etc. With this algorithm, we investigate whether secondary features other than the consensus sequences allow higher perfomance in predicting sequences, and if weights for such features vary significantly amongst multiple RBPs. #### Below is a list of .py scripts and description of functions used. #### rbp_scrape.py: uses Selenium package to browse POSTAR2 (http://lulab.life.tsinghua.edu.cn/postar2/rbp2.php) and collect CLIP-seq database. Postar website only allows downloading of one RBP-gene pair dataset in csv format. this code allows to scrape data of all RBP-gene pairs for a given RBP, and merge the data into one csv file. - scrape_genelist: a function that takes a name of a RBP, and scrapes a csv list of all the genes of RNA that the protein is known to bind - scrape_seq_locs: Uses the scraped genelist, and download sequence addressses of each CLIP-Seq peak, aggregates the data into one csv. #### clean_db.py: a collection of pandas functions to clean up and organize the raw data. - clean_repeat_transcripts: there are multiple replicates with same data but with different transcript IDs, merge the replicates into one single line - get_HEK: Although there are clip-seq data from different sources (e.g. brain, HEK, HELA cells), vast majority (>90%) of the data is from HEK cells. filter only HEK cells - get_clip_seq: there are multiples of CLIP-seq protocols/analyses, but the vast majority is Par-CLIP, Paralzyer. Filter only this protocol. - make_peak_lengths: The scraped data gives a string chromosomal positions of the CLIP peaks. Convert the string to a length of the peak and return the lengths as a new column in the database #### retrieve_seqs.py: from local Fasta file of human HG38 genome, retrieve sequences of the peak positions - retrieve_seq : parse the Position string and input the chromosome number, start, and end positions to fetch sequence from human genome using the Pysam package - make_fasta: make fasta files from sequence database to be used for different bioinformatic tools such as DREME #### neg_con.py: make a negative control dataset for each RBP by choosing from genes that do not contain any LINK-seq peaks. - make_neg_genelist: Given a transcriptome of a cell line used in the database, exclude all genes that had peaks and return the remainder of genes that will be used to obtain negative control sequences. - make_random_positions: Using the gene list made by make_neg_genelist, randomly retrieve n number of positions to be used as negative control sequences. #### motifs_xml_parser.py: DREME, a tool that identifies probable consensus sequences from peak and negative control sequences, gives an XML output. This code parses the xml file into a csv list of motifs that can be converted to pandas - parse_dreme_xml: using ElementTree XML API, construct a dataframe of motif and its number of identified positions in positive and negative sequences #### motif_finder.py: For a given list of enriched motifs, parse through positive peak sequences and negative sequences and search for presence and location of the motifs. Further, analyze the RNA structure of the sequences including the flanking regions, and find where the motif in peaks is colocalizing with RNA structures. - add_features_to_pandas: For each sequence in positive/negative database, search for presence of motifs in the sequence, and identify whether the found motif is colocalized to either [hairpin, inner loop, bulge, stock, multiloop, or E] RNA secondary structure. Add this information to the existing dataframe. - find_features_in_sequence: Uses Vienna RNA package to construct a model of a given RNA sequence of N size, outputs structural information by base pair. - add_instances_to_pandas: If one is not concerned with the secondary RNA sequence, this function simply returns the number of motif occurences for a given sequence. #### logistic_regression.py: Despite the name, these codes are used to prepare the dataframe for any data analysis tool in sklearn package. Prepares the database for analyses such as logistic regression / random forest. - prep_database: Combines the positive peaks and negative control database of features, outputs train/cross-validation/test sets. Also applies feature normalization or peak-score cutoffs when prompted. - just_motifs: Uses regular expression to return only the occurences of motifs for regressions instead of full secondary-structure features. ALso returns train/cv/test sets. - feture_standard: Normalizes features from 0-1. Uses the eq: x - min(X) / max(X) - even_features: a control for secondary structures, creates an evenly distributed feature set for a given motif. <file_sep>/clean_db.py ## After the sequence data is scraped from PASTA, the data has to be cleaned ## THere are multiple entries with exact same sequence but different Transcript IDs ## We should first clean that data and save the transcript IDs into a single tab import os import pandas as pd import sys import re def clean_repeat_transcripts(RBP): """the raw data file contains multiple replicates with same data, \ but different transcript IDs. This will unify the repeats, and save\ all the transcript ID to a vector and finally return a new, cleaned\ database in csv form""" prot_dir = os.getcwd() + '/' + RBP db1 = pd.read_csv(prot_dir + '/seq_dat.csv',index_col=0) # Entries with the same genomic positions are identical, so group accordingly db1 = db1.groupby('Position') group_list = list(db1.groups.keys()) group_size = len(group_list) count = 0 pd_list = [] # iterate through groups, get a single row of dataframe, and save a list of transcript IDs for idx,i in enumerate(group_list): #progress line countstr = "sequence " + str(idx+1) + " of " + str(group_size) sys.stdout.write("\r{}".format(countstr)) #access group seq_group = db1.get_group(i) ##trans_list = list(seq_group['Transcript ID']) #get the first entry of the group, convert to DF seq_unified = seq_group.iloc[0] seq_db = seq_unified.to_frame().T #append to DF lists pd_list.append(seq_db) #concatenate all the dfs in the df list master_db = pd.concat(pd_list) master_db.to_csv(prot_dir + "/seq_dat_v1.csv") def get_HEK(RBP): """From the summary statistics of the database, most of the peaks come from\ experiments that had HEK293/HEK293T as sources. This function filters \ the database for only HEK sources""" prot_dir = os.getcwd() + '/' + RBP db1 = pd.read_csv(prot_dir + '/seq_dat_v1.csv',index_col=0) master_db = db1[(db1['Tissue type']=='HEK293') | \ (db1['Tissue type']=='HEK293T')] master_db.to_csv(prot_dir + "/seq_dat_HEK.csv") def get_clip_seq(RBP): """From the summary statistics of the database, most of the peaks\ come from Clip-seq technology ('Par-CLIP,Paralyzer'). For consistency,\ we'll filter only these set of data""" prot_dir = os.getcwd() + '/' + RBP db1 = pd.read_csv(prot_dir + '/seq_dat_HEK.csv',index_col=0) master_db = db1[db1['CLIP-seq technology and peak calling method']\ =='PAR-CLIP,PARalyzer'] master_db.to_csv(prot_dir + "/seq_dat_HEKc1.csv") def make_peak_lengths(RBP): """Peak position values in the database have different lengths, find the\ lengths and add it as a column in database""" prot_dir = os.getcwd() + '/' + RBP db1 = pd.read_csv(prot_dir + '/seq_dat_HEKc1.csv',index_col=0) pos = db1['Position'] #split the position string into [chr#,start pos, end pos] pos1 = pos.apply(lambda x: re.split('[: -]',x)) #calculate peak length from end pos - start pos peak_length = pos1.apply(lambda x: int(x[2])-int(x[1])) db1['Peak length'] = peak_length db1.to_csv(prot_dir + "/seq_dat_HEKc2.csv")<file_sep>/logistic_regression.py ## From the final database, compile and run logistic regressions import os import numpy as np import pandas as pd import re # import pysam as pys import sys import sklearn.model_selection as skl_ms import sklearn.linear_model as skl_lin import sklearn.metrics as skl_mets def prep_database(RBP, test = 0.4, feat_norm = True,attract=False,peaks_as_negs=False): """From the databases containing features, create training, cross-validate, \ and test sets, save the csvs to a final directory""" prot_dir = os.getcwd() + '/'+ RBP #retrieve positive and negative database pos_db = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv') if peaks_as_negs: neg_db = pd.read_csv(prot_dir + '/neg_peaks_with_features.csv') else: neg_db = pd.read_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv') col_titles = list(pos_db) if attract: Reg = ".*m[0-9][0-9]*.*" else: Reg = ".*: m[0-9][0-9]*.*" # Reg = ".*m01.*" pos_feat = pos_db.filter(regex=Reg) neg_feat = neg_db.filter(regex=Reg) #make a dataFrame just with features column #make combined database final_db = pd.concat([pos_feat,neg_feat]) if feat_norm == True: final_db = feature_standard(final_db) #make a boolean 1 or 0 for whether sequences are peaks or not final_db = final_db.assign(y = [1]*pos_feat.shape[0]+[0]*neg_feat.shape[0]) #divide the final database into training, cross-validate, and test samples X_train, X_Atest, y_train, y_Atest = \ skl_ms.train_test_split(final_db.drop('y',axis=1),final_db['y'], test_size = test) X_Cvalid, X_test, y_Cvalid, y_test = \ skl_ms.train_test_split(X_Atest,y_Atest, test_size = 0.5) #save the files to a final, separate folder save_dir = os.getcwd() + '/' + RBP + '_final_data/' X_train.to_csv(save_dir + 'X_train.csv') y_train.to_csv(save_dir + 'y_train.csv') X_Cvalid.to_csv(save_dir + 'X_crossval.csv') y_Cvalid.to_csv(save_dir + 'y_crossval.csv') X_test.to_csv(save_dir + 'X_test.csv') y_test.to_csv(save_dir + 'y_test.csv') def just_motifs(RBP, test = 0.4, feat_norm = True,attract = False,peaks_as_negs=False): prot_dir = os.getcwd() + '/' + RBP pos_db = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv') # pos_db = pos_db.assign(y = pd.Series([1]*pos_db.shape[0])) if peaks_as_negs: neg_db = pd.read_csv(prot_dir + '/neg_peaks_with_features.csv') else: neg_db = pd.read_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv') # neg_db = neg_db.assign(y = pd.Series([0]*neg_db.shape[0])) col_titles = list(pos_db) if attract: reg_motif = ".*m[0-9][0-9]*" else: reg_motif = ".*: m[0-9][0-9]*" # reg_motif = 'm[0-9][0-9]' motifs = [] for a in col_titles: motif = re.search(reg_motif,a) if motif and (motif.group() not in motifs): motifs.append(motif.group()) psum_db = pd.DataFrame() nsum_db = pd.DataFrame() for motif in motifs: motif_feat = [] for title in col_titles: if motif in title: motif_feat.append(title) pmotif_all = pos_db[motif_feat] pmotif_sums = pmotif_all.sum(axis=1) nmotif_all = neg_db[motif_feat] nmotif_sums = nmotif_all.sum(axis=1) psum_db[motif] = pmotif_sums nsum_db[motif] = nmotif_sums # psum_db['y'] = pos_db['y'] # nsum_db['y'] = neg_db['y'] #make combined database final_db = pd.concat([psum_db,nsum_db]) if feat_norm == True: final_db = feature_standard(final_db) #make a boolean 1 or 0 for whether sequences are peaks or not final_db = final_db.assign(y = [1]*pos_db.shape[0]+[0]*neg_db.shape[0]) #divide the final database into training, cross-validate, and test samples X_train, X_Atest, y_train, y_Atest = \ skl_ms.train_test_split(final_db.drop('y',axis=1),final_db['y'], test_size = test) X_Cvalid, X_test, y_Cvalid, y_test = \ skl_ms.train_test_split(X_Atest,y_Atest, test_size = 0.5) #save the files to a final, separate folder save_dir = os.getcwd() + '/' + RBP + '_just_motifs/' X_train.to_csv(save_dir + 'X_train.csv') y_train.to_csv(save_dir + 'y_train.csv') X_Cvalid.to_csv(save_dir + 'X_crossval.csv') y_Cvalid.to_csv(save_dir + 'y_crossval.csv') X_test.to_csv(save_dir + 'X_test.csv') y_test.to_csv(save_dir + 'y_test.csv') def prep_database_only_seqs_with_motifs(RBP, test = 0.4, feat_norm = True,attract=False,peaks_as_negs=False): """From the databases containing features, create training, cross-validate, \ and test sets, save the csvs to a final directory""" prot_dir = os.getcwd() + '/'+ RBP #retrieve positive and negative database pos_db = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv') if peaks_as_negs: neg_db = pd.read_csv(prot_dir + '/neg_peaks_with_features.csv') else: neg_db = pd.read_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv') col_titles = list(pos_db) #make a dataFrame just with features column if attract: Reg = ".*m[0-9][0-9]*.*" else: Reg = ".*: m[0-9][0-9]*.*" # Reg = ".*m01.*" pos_feat = pos_db.filter(regex=Reg) neg_feat = neg_db.filter(regex=Reg) pos_feat_sum = pos_feat.sum(axis=1) neg_feat_sum = neg_feat.sum(axis=1) pos_feat = pos_feat[pos_feat_sum>0] neg_feat = neg_feat[neg_feat_sum>0] #make combined database final_db = pd.concat([pos_feat,neg_feat]) if feat_norm == True: final_db = feature_standard(final_db) #make a boolean 1 or 0 for whether sequences are peaks or not final_db = final_db.assign(y = [1]*pos_feat.shape[0]+[0]*neg_feat.shape[0]) #divide the final database into training, cross-validate, and test samples X_train, X_Atest, y_train, y_Atest = \ skl_ms.train_test_split(final_db.drop('y',axis=1),final_db['y'], test_size = test) X_Cvalid, X_test, y_Cvalid, y_test = \ skl_ms.train_test_split(X_Atest,y_Atest, test_size = 0.5) #save the files to a final, separate folder save_dir = os.getcwd() + '/' + RBP + '_just_seqs_with_motifs/' X_train.to_csv(save_dir + 'X_train.csv') y_train.to_csv(save_dir + 'y_train.csv') X_Cvalid.to_csv(save_dir + 'X_crossval.csv') y_Cvalid.to_csv(save_dir + 'y_crossval.csv') X_test.to_csv(save_dir + 'X_test.csv') y_test.to_csv(save_dir + 'y_test.csv') final_db.to_csv(save_dir + '_final_db.csv') def just_motifs_only_seqs_with_motifs(RBP, test = 0.4, feat_norm = True,attract=False,peaks_as_negs=False): prot_dir = os.getcwd() + '/' + RBP pos_db = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv') # pos_db = pos_db.assign(y = pd.Series([1]*pos_db.shape[0])) if peaks_as_negs: neg_db = pd.read_csv(prot_dir + '/neg_peaks_with_features.csv') else: neg_db = pd.read_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv') # neg_db = neg_db.assign(y = pd.Series([0]*neg_db.shape[0])) col_titles = list(pos_db) if attract: reg_motif = ".*m[0-9][0-9]*" else: reg_motif = ".*: m[0-9][0-9]*" # reg_motif = 'm[0-9][0-9]' # reg_motif = ".*m01.*" motifs = [] for a in col_titles: motif = re.search(reg_motif,a) if motif and (motif.group() not in motifs): motifs.append(motif.group()) psum_db = pd.DataFrame() nsum_db = pd.DataFrame() for motif in motifs: motif_feat = [] for title in col_titles: if motif in title: motif_feat.append(title) pmotif_all = pos_db[motif_feat] pmotif_sums = pmotif_all.sum(axis=1) nmotif_all = neg_db[motif_feat] nmotif_sums = nmotif_all.sum(axis=1) psum_db[motif] = pmotif_sums nsum_db[motif] = nmotif_sums # psum_db['y'] = pos_db['y'] # nsum_db['y'] = neg_db['y'] psum_db_sum = psum_db.sum(axis=1) nsum_db_sum = nsum_db.sum(axis=1) psum_db = psum_db[psum_db_sum>0] nsum_db = nsum_db[nsum_db_sum>0] final_db = pd.concat([psum_db,nsum_db]) if feat_norm == True: final_db = feature_standard(final_db) #make a boolean 1 or 0 for whether sequences are peaks or not final_db = final_db.assign(y = [1]*psum_db.shape[0]+[0]*nsum_db.shape[0]) #divide the final database into training, cross-validate, and test samples X_train, X_Atest, y_train, y_Atest = \ skl_ms.train_test_split(final_db.drop('y',axis=1),final_db['y'], test_size = test) X_Cvalid, X_test, y_Cvalid, y_test = \ skl_ms.train_test_split(X_Atest,y_Atest, test_size = 0.5) #save the files to a final, separate folder save_dir = os.getcwd() + '/' + RBP + '_just_motifs_just_seqs_with_motifs/' X_train.to_csv(save_dir + 'X_train.csv') y_train.to_csv(save_dir + 'y_train.csv') X_Cvalid.to_csv(save_dir + 'X_crossval.csv') y_Cvalid.to_csv(save_dir + 'y_crossval.csv') X_test.to_csv(save_dir + 'X_test.csv') y_test.to_csv(save_dir + 'y_test.csv') def feature_standard(db): """from a dataframe containing only features, standardize the features \ by subtracting the mean and dividing by the standard deviation""" col_names = list(db) new_db = pd.DataFrame() # for feature in col_names: # feature_db = db[feature].astype('float') # mean = feature_db.mean() # stdev = feature_db.std() # if stdev == 0: # stddev =1 # norm_db = feature_db.apply(lambda x : (x - mean)/stdev) # new_db[feature] = norm_db for feature in col_names: feature_db = db[feature].astype('float') maxx = feature_db.max() minn = feature_db.min() if maxx == 0: maxx =1 norm_db = feature_db.apply(lambda x : (x - minn)/maxx) new_db[feature] = norm_db return new_db <file_sep>/directory_operations.py import os import os.path import time def check_download(file_dir,time_lim = 10): """wait for the download to finish, given time limit. if the\ file specified is downloaded, return True.""" sleep_time = 0; while not os.path.exists(file_dir) | (sleep_time == time_lim): time.sleep(1) sleep_time += 1 if sleep_time == time_lim: return False return True def create_dbdir(prot_name): """create a new database directory with a protein name""" current_dir = os.getcwd() prot_dir = current_dir + '\\' + prot_name os.mkdir(prot_dir) return prot_dir def rename_move(source,rename,dest): """find genericly named downloaded file, rename and move to a target directory""" os.rename(source, os.path.join(dest, rename))<file_sep>/rbp_scrape.py import pandas as pd import os import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException import directory_operations as dio import sys import time """ Scrape functions using Selenium to browse through POSTAR website\ to scrape for CLIP-sequence data""" def scrape_genelist(rbp,filedir = os.getcwd()): """Use selenium to scrape a list of genes/RNA that a specific RBP \ is known to bind. The list will be renamed/saved in a protein specific folder \ and further be used to scrape sequence locations.""" #This initializes chrome web browser and sets the download path dest_dir = dio.create_dbdir(rbp) chrome_options = webdriver.ChromeOptions() prefs = {'download.default_directory' : filedir} chrome_options.add_experimental_option('prefs', prefs) browser = webdriver.Chrome(chrome_options=chrome_options) #initiate Chrome driver browser.get('http://lulab.life.tsinghua.edu.cn/postar2/rbp2.php') # locate the search RBP text-fill and fill in the RBP to search elem = browser.find_element_by_id('searchRBPbinding') elem.send_keys(rbp + Keys.RETURN) #sometimes google pops up auto search, click away to remove the pop-up action = webdriver.common.action_chains.ActionChains(browser) action.move_to_element_with_offset(elem, -50, -50) action.click() action.perform() # locate the search RBP button and click it to browse to new web search_button = browser.find_element_by_xpath\ ("//button[contains(.,'Search a RBP')]") search_button.click() # Wait for the RBP search result to show, download the genes list csv_button = WebDriverWait(browser, 20).until( EC.presence_of_element_located\ ((By.LINK_TEXT, "Export data to CSV file"))) csv_button.click() # Check for the download to finish, rename from generic name and move to # the protein directory dl_dir = filedir + '/' + 'POSTAR.csv' if dio.check_download(dl_dir): dio.rename_move(source = 'POSTAR.csv',rename = rbp +'_genelist.csv',\ dest = dest_dir) browser.quit() def scrape_seq_locs(rbp): """used the scraped gene list, clean up the data, and for each gene \ utilizes Selenium to scrape the genome location of where the RBP binds.""" print('seq_scraper v1.02') #start timer start_time = int(time.time()) #import gene list as pandas df prot_dir = os.getcwd() + '/{}'.format(rbp) gene_dir = prot_dir + '/{}_genelist.csv'.format(rbp) genes = pd.read_csv(gene_dir) # Genes that have binding site records less than 3 mostly tend to have # unreliable significance values in peak-calling. Only take genes with # greather than 3 binding site records m_genes = genes[genes['Binding site records'] > 3] gene_list = m_genes['Target gene symbol'] #set download directory and initiate chrome driver chrome_options = webdriver.ChromeOptions() prefs = {'download.default_directory' : prot_dir} chrome_options.add_experimental_option('prefs', prefs) browser = webdriver.Chrome(chrome_options=chrome_options) # for every gene in the gene list, scrape the csv file that contains # all binding sites #set counter variable to see progress count = 1 total = len(gene_list) dfs_list = [] for i in gene_list: if (count % 1000) == 0: browser.quit() browser = webdriver.Chrome(chrome_options=chrome_options) gene_link = 'http://lulab.life.tsinghua.edu.cn/postar2/bindingSites.php? \ RBP={}&geneName={}&table=human_clipdb_par2&species=human& \ selectType=clipdb&search_total=yes'.format(rbp,i) #get the gene link browser.get(gene_link) #to get full information, the browser needs to click 'details' button details_button = WebDriverWait(browser,10).until\ (EC.presence_of_element_located((By.XPATH,\ "//button[contains(.,'Details')]"))) details_button.click() #download the CSV of all positions download_button = browser.find_element_by_link_text\ ("Export data to CSV file") download_button.click() generic_name = prot_dir + '/POSTAR.csv' master_name = prot_dir + '/seq_dat.csv' #confirm download, copy to DF, and append to a DF list if dio.check_download(generic_name): add_df = pd.read_csv(generic_name) dfs_list.append(add_df) os.remove(generic_name) # count progress and time spent end_time = int(time.time()) min_spent = round(((end_time-start_time)/60),2) countstr = 'processed ' + str(count) + ' / ' + str(total) +\ ' genes in total ' + str(min_spent) + ' minutes' sys.stdout.write("\r{}".format(countstr)) count += 1 #concatenate all the downloaded dfs master_df = pd.concat(dfs_list) #after all the genes are added to dataframe, export to a master csv browser.quit() master_df.to_csv(master_name) <file_sep>/analyze_features.py import os import numpy as np import pandas as pd import re import sys import matplotlib.pyplot as plt def import_data(RBP,pos = True): prot_dir = os.getcwd() + '/'+ RBP #retrieve positive or negative con database if pos == True: p_db = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv',index_col=0) else: p_db = pd.read_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv',index_col=0) return p_db def structures_perc(df,motif = 'm01'): """For each motif,make bar chart of structures""" #make a dataFrame just with features column for a given motif feat_db = df.filter(regex = '.*' + motif + '.*') #rename features to structures old_name = list(feat_db) new_name = ['Hairpin loop','Interior loop','Bulge','Stack','Multi-loop',\ 'External elements'] new_cols = dict(zip(old_name,new_name)) feat_db.rename(columns = new_cols,inplace = True) sums = feat_db.sum() sums['percent'] = sums.apply(lambda x : 100*x / sums.sum()) fig, ax = plt.subplots() ax = sums['percent'].plot.bar() ax.set_title(motif + ' structure percentiles') ax.set_ylabel('%') ax.set_xlabel('RNA secondary structure') def count_structures(df): dfnew = pd.DataFrame() col_name = ['H','I','B','S','M','E'] for s in col_name: dfnew[s] = df['structure'].apply(lambda x: x.count(s)) all_sums = dfnew.sum(axis=0) percents = all_sums.apply(lambda x : 100*x / all_sums.sum()) fig, ax = plt.subplots() ax = percents.plot.bar() ax.set_title('structure percentiles') ax.set_ylabel('%') ax.set_xlabel('RNA secondary structure') <file_sep>/structures.py import sys sys.path.append('/home/hnunns/Downloads/ViennaRNA-2.4.10/interfaces/Python3') import RNA import re import os import pandas as pd import numpy as np # complement = {'A':'T','T':'A','G':'C','C':'G','N':'N'} def add_structures_to_pandas(RBP,pos=True): prot_dir = os.getcwd() + '/' +RBP if pos: pos_seq_df = pd.read_csv(prot_dir+'/seq_dat_HEKc3_RNA.csv') pos_seq_df['structure'] = pos_seq_df.apply(sub_add,axis=1) pos_seq_df.to_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_struc.csv') else: neg_seq_df = pd.read_csv(prot_dir+'/neg_con_seqs_RNA.csv') neg_seq_df['structure'] = neg_seq_df.apply(sub_add,axis=1) neg_seq_df.to_csv(prot_dir + '/neg_con_seqs_RNA_with_struc.csv') def sub_add(rows): if rows[0]%100==0: countstr = 'at sequence '+str(rows[0]) sys.stdout.write("\r{}".format(countstr)) seq = rows['sequence'] seqLength = len(seq) if seqLength<160: flank5 = rows['5 flanking seq'][20+round(seqLength/2):] flank3 = rows['3 flanking seq'][:-20-round(seqLength/2)] else: flank5 = rows['5 flanking seq'][100:] flank3 = rows['3 flanking seq'][:-100] seqind0 = len(flank5) seqind1 = len(seq)+seqind0 long_seq = flank5+seq+flank3 rr = RNA.fold(long_seq) #outputs the rna structure in dot-bracket notation r2 = RNA.b2Shapiro(rr[0]) #converts to shapiro notation #(H:hairpin loop, I:interior loop, B:bulge,M:multi-loop,S:stack,E:external elements,R:root) translated_str = translatetoShapiro(rr[0],r2) #translates the string to the alphabet of features #(H:hairpin loop, I:interior loop, B:bulge,M:multi-loop,S:stack,E:external elements,R:root) return translated_str[seqind0:seqind1] #removes flanking structures sanity_dict = {'H':0,'S':1,'I':2,'B':3,'E':4,'M':5,'R':6} #check if correct number of each structure type were inputted sanity_mult = {'H':1,'S':2,'I':1,'B':1,'E':1,'M':1,'R':1} #multiplies the Stem length by two since double stranded def translatetoShapiro(dot_br,shapiro): shap_list = re.split('[()]',shapiro) #remove parentheses from shapiro notated string, split into list shap_list[:] = [x for x in shap_list if x!=''] out_str = dot_br #initialize the output string as the dot-bracket notated string out_list = list(out_str) #split string into list sanity_check = [0]*len(sanity_dict) #list with each element corresponding to the number of each structure element for jj in range(len(shap_list)): #get shapiro-notation letter and the length from shap_list lett = shap_list[jj][0] #type of structure if len(shap_list[jj])>1: val = int(shap_list[jj][1:]) #length of structure else: val =int(0) sanity_check[sanity_dict[lett]]+=val*sanity_mult[lett] if lett=='H': #replace hairpin "dots" with "H" m = re.search(r'\(\.*\)',out_str).span() ind1 = m[0]+1 ind2 = m[1]-1 out_list[ind1:ind2] = ['H']*(ind2-ind1) elif lett=='S': #replace stem "parenthese" with "S" out_list[ind1-val:ind1] = ['S']*val out_list[ind2:ind2+val] = ['S']*val ind1 -=val ind2 +=val elif lett in ['I','B']: #replace internal loop and bulge "dots" with "I" or "B" while out_list[ind1-1]=='.': out_list[ind1-1] = lett ind1-=1 while out_list[ind2] == '.': out_list[ind2] = lett ind2 +=1 elif lett=='M': #replace multiloop "parenthese" with "M" m = re.search(r'\([HSIBM.]*\)',out_str).span() ind1 = m[0]+1 ind2 = m[1]-1 out_list[ind1:ind2] = ['M' if x=='.' else x for x in out_list[ind1:ind2]] elif lett == 'E': #Replace out_list = ['E' if x=='.' else x for x in out_list] out_str = ''.join(out_list) for key, val in sanity_dict.items(): #throw an error if the number of each structure element does not match the original if sanity_check[val]!=out_str.count(key): raise valueError('An incorrect translation occured') return out_str def estimate_rna_structure_stability(RBP): #tests how much the rna structure changes as the flanking length decreases prot_dir = os.getcwd() + '/' +RBP pos_seq_df = pd.read_csv(prot_dir+'/seq_dat_HEKc3_RNA.csv',index_col=0)[0:100] # neg_seq_df = pd.read_csv(prot_dir+'/neg_con_seqs_RNA.csv',index_col=0)[0:100] changes = range(0,100,10) phrase = "structure similarity for flank - " col_names = [] for i in changes: col_names+=[phrase +str(i)] pos_seq_df[phrase +str(i)] = 0 pos_seq_df[phrase +str(i)].astype('float') # neg_seq_df[phrase +str(i)] = 0 # neg_seq_df[phrase +str(i)].astype('float') pos_seq_df.filter(regex="structure similarity for flank - .*") pos_seq_df[col_names] = pos_seq_df.apply(sub_check,args=(changes,),axis=1,result_type='expand') # neg_seq_df[col_names] = neg_seq_df.apply(sub_check,args = (changes,),axis=1,result_type='expand') return pos_seq_df.filter(regex = phrase+'.*').mean(axis=0)#,neg_seq_df.filter(regex = phrase+'.*').mean(axis=0) def sub_check(rows,changes): Similarity = [] for i in changes: seq = rows['sequence'] seqLength = len(seq) flank5 = rows['5 flanking seq'][i+20+round(seqLength/2):] flank3 = rows['3 flanking seq'][:-20-round(seqLength/2)-i] seqind0 = len(flank5) seqind1 = len(seq)+seqind0 long_seq = flank5+seq+flank3 rr = RNA.fold(long_seq) #outputs the rna structure in dot-bracket notation r2 = RNA.b2Shapiro(rr[0]) #converts to shapiro notation #(H:hairpin loop, I:interior loop, B:bulge,M:multi-loop,S:stack,E:external elements,R:root) translated_str = translatetoShapiro(rr[0],r2) #translates the string to the alphabet of features #(H:hairpin loop, I:interior loop, B:bulge,M:multi-loop,S:stack,E:external elements,R:root) final_str = translated_str[seqind0:seqind1] #removes flanking structures if i==0: comp_str = final_str Length = len(final_str) Similarity += [np.sum([1 if x==y else 0 for x,y in zip(list(final_str),list(comp_str))])/Length] # comp_str = final_str # print(len(Similarity)) return Similarity <file_sep>/motifs_xml_parser.py ## This code will parse XML output from DREME import xml.etree.cElementTree as et import os import pandas as pd def parse_dreme_xml(RBP): """using ElementTree XML API, parse DREME outputs and construct a pandas Dataframe that includes each motif sequence, and number of identified positions in positive peaks and negative sequences""" prot_dir = os.getcwd() + '/' +RBP #initiate empty dataframe and an empty list for each columns name = [] seq = [] num_p = [] num_n = [] #retrieve and parse dreme xml file xml = et.parse(prot_dir + '/dreme.xml') root = xml.getroot() # In a for loop iterating every motifs in the xml, find the consensus #seqs and number of identified positions in positives and negatives for motif in root.iter('motif'): name.append(motif.attrib['id']) seq.append(motif.attrib['seq']) num_p.append(motif.attrib['p']) num_n.append(motif.attrib['n']) #construct the dataframe, export to csv df_dreme = pd.DataFrame(data = {'name':name,'seq':seq,\ 'num_p': num_p,'num_n':num_n}) df_dreme.to_csv(prot_dir + '/motifs.csv') def get_attract(RBP): """From the Attract RBP motif database, retrieve specific motifs for a given RBP""" dire = os.getcwd() + '/Attract/' a_db = pd.read_csv(dire + 'ATtRACT_db.csv') #select only the specific RBP and for human consensus seqs prot_db = a_db[(a_db['Gene_name'] == RBP) & \ (a_db['Organism'] == 'Homo_sapiens')] prot_db.to_csv(os.getcwd() + '/' + RBP + '/attract_motifs.csv') <file_sep>/neg_con.py ## Create negative control dataset. Assuming the CLIP-seq database captured all of the ## positive (RBP-binding) RNA in HEK293T cells, we can collect RNA sequences of 'negatives'. ## To do so, we'll exclude all the genes that had positive peaks from HEK293 transcriptome ## and collect random sequences from genes that did not have positive peaks. import os import numpy as np import pandas as pd import re # import pysam as pys import sys import numpy.random as rand def make_neg_genelist(RBP): """From the HEK293 transcriptome, exclude all the genes that had positive peaks in CHIP-LINK dataset, and return the remainder of the genes as negative control genes""" prot_dir = os.getcwd() + "/" + RBP prot_trans = pd.read_csv(prot_dir + '/' + RBP + '_genelist.csv') hek_trans = pd.read_csv('HEK_transcriptome.csv') hek_trans = hek_trans[['Gene','Chromosome','Position']] #extract genes from both HEK transcriptome and RBP binding genes hek_genes = hek_trans['Gene'] prot_genes = prot_trans['Target gene symbol'] #find the intersection between the two genes int_genes = hek_genes[hek_genes.isin(prot_genes)] #exclude the intersection from the hek transcriptome, obtaining negative #control genes neg_trans = hek_trans[hek_trans['Gene'].isin(int_genes)\ .apply(lambda x : not(x))] #For ease of future functions, format the dataframe new_chr = neg_trans['Chromosome'].apply(lambda x: "chr"+x+':') pos = neg_trans['Position'].apply(lambda x: re.split('[-]',x)) start = pos.apply(lambda x: int(x[0])) end = pos.apply(lambda x: int(x[1])) length = end-start neg_trans = neg_trans.drop(['Chromosome','Position'],axis = 1) neg_trans['Chromosome'] = new_chr neg_trans['Start'] = start neg_trans['End'] = end neg_trans['Length'] = length #There are unmapped chromosomes present in the database, get rid of those neg_trans = neg_trans[neg_trans['Chromosome'] != 'chrUnmapped:'] #save this list neg_trans.to_csv(prot_dir + '/neg_genelist.csv') def make_random_positions(RBP,n=100000): """once we get the gene list for negatives, we want to make a list of n number of random gene positions that we can retrieve sequences from\ to serve as negative controls""" #get the negative genelist, filter out gene transcripts that are too short prot_dir = os.getcwd() + "/" + RBP neg_list = pd.read_csv(prot_dir + "/neg_genelist.csv",index_col = 0) neg_list = neg_list[neg_list['Length'] > 750] neg_size = neg_list.shape[0] print("Choosing from " + str(neg_size) + " of negative control genes") count = 0 #create a 30 bp random chromosome position from a gene transcript in the negative #gene list positions = [] genes = [] #for now, every strand will be positive strand = [] while count < n+1: rand_gene = neg_list.iloc[rand.randint(0,neg_size)] start = rand_gene['Start'] + 50 end = rand_gene['End'] - 50 rand_seq = rand.randint(start,end) seq_start = rand_seq - 15 seq_end = rand_seq + 15 pos_string = rand_gene['Chromosome'] + str(seq_start) + '-' + str(seq_end) positions.append(pos_string) genes.append(rand_gene['Gene']) strand.append('+') #counter count += 1 countstr = 'sequence ' + str(count) + ' of ' + str(n) sys.stdout.write("\r{}".format(countstr)) neg_seqs = pd.DataFrame({'Gene Name' : genes, 'Position' : positions,\ 'Strand' : strand}) #drop duplicates neg_seqs = neg_seqs.drop_duplicates() print("Total of "+ str(neg_seqs.shape[0])+" control sequences" ) neg_seqs.to_csv(prot_dir + '/neg_seq_locs.csv') def peaks_neg_cons(RBP,RBP1): """obtains negative control peaks from another RBP peak that does not\ overlap in gene targets""" RBP_dir = os.getcwd() + '/' + RBP +'/' RBP1_dir = os.getcwd() + '/' + RBP1 +'/' RBP_db = pd.read_csv(RBP_dir + 'seq_dat_HEKc3_RNA_with_struc.csv', index_col = 0 ) RBP1_db = pd.read_csv(RBP1_dir + 'seq_dat_HEKc3_RNA_with_struc.csv', index_col = 0 ) #Find the intersection betweet the genes of two database, #exclude those genes from each database RBP_genes = RBP_db['Gene Name'].unique() RBP1_genes = RBP1_db['Gene Name'].unique() int_genes = list(set(RBP_genes)&set(RBP1_genes)) new_db = RBP_db[RBP_db['Gene Name'].apply(lambda x: not(x in int_genes))] new_db1 = RBP1_db[RBP1_db['Gene Name'].apply(lambda x: not(x in int_genes))] new_db.to_csv(RBP1_dir + 'neg_peaks_with_struc.csv') new_db1.to_csv(RBP_dir + 'neg_peaks_with_struc.csv') <file_sep>/significance_frequency.py import os import numpy as np import pandas as pd import re import sys import matplotlib.pyplot as plt from scipy.stats import binom def import_data(RBP,pos = True,peaks_as_negs=False): prot_dir = os.getcwd() + '/'+ RBP #retrieve positive or negative con database if pos == True: p_db = pd.read_csv(prot_dir + '/seq_dat_HEKc3_RNA_with_features.csv',index_col=0) else: if peaks_as_negs: p_db = pd.read_csv(prot_dir + '/neg_peaks_with_features.csv',index_col=0) else: p_db = pd.read_csv(prot_dir + '/neg_con_seqs_RNA_with_features.csv',index_col=0) return p_db def structures_perc(RBP,num_motifs,peaks_as_negs=False): """For each motif,make pie chart of structures""" pdb = import_data(RBP,pos = True) ndb = import_data(RBP,pos=False,peaks_as_negs=True) pos_struc_freq = count_structures(pdb) print('good') neg_struc_freq = count_structures(ndb) print('good') new_name = ['Hairpin loop','Interior loop','Bulge','Stack','Multi-loop',\ 'External elements'] for ii in range(len(new_name)): pos_frac = pos_struc_freq[ii]/100 neg_frac = neg_struc_freq[ii]/100 Thresh = .05 if abs(pos_frac-neg_frac)>Thresh: print('totals for pos and neg differ in: '+new_name[ii]+' by > '+str(Thresh)) print('pos fraction: '+str(pos_frac)) print('neg fraction: '+str(neg_frac)) for i in range(1,num_motifs+1): motif = "m0*"+str(i) feat_pdb = pdb.filter(regex = '.*' + motif + '/.*') old_name = list(feat_pdb) new_cols = dict(zip(old_name,new_name)) feat_ndb = ndb.filter(regex = '.*' + motif + '/.*') #rename features to structures feat_pdb.rename(columns = new_cols,inplace = True) feat_ndb.rename(columns = new_cols,inplace = True) psums = feat_pdb.sum() nsums = feat_ndb.sum() for ii in range(len(psums)): pos_sample_frac = psums[ii]/psums.sum() neg_sample_frac = nsums[ii]/nsums.sum() probs=binom.cdf(round(psums[ii]),round(psums.sum()),neg_sample_frac) Thresh = .05 if (probs>.99 or probs<.01) and abs(pos_sample_frac-neg_sample_frac)>Thresh: print('pos and neg for '+motif + ' differ in structure ' +new_name[ii]+' by > '+ str(Thresh)) print('pos fraction for '+motif + '= '+str(pos_sample_frac)) print('neg fraction for '+motif + '= '+str(neg_sample_frac)) # sums['percent'] = sums.apply(lambda x : 100*x / sums.sum()) # fig, ax = plt.subplots() # ax = sums['percent'].plot.bar() # ax.set_title(motif + ' structure percentiles') # ax.set_ylabel('%') # ax.set_xlabel('RNA secondary structure') # sums['percent'] = sums.apply(lambda x : 100*x / sums.sum()) # fig, ax = plt.subplots() # ax = sums['percent'].plot.bar() # ax.set_title(motif + ' structure percentiles') # ax.set_ylabel('%') # ax.set_xlabel('RNA secondary structure') def count_structures(df): dfnew = pd.DataFrame() col_name = ['H','I','B','S','M','E'] for s in col_name: dfnew[s] = df['structure'].apply(lambda x: x.count(s)) all_sums = dfnew.sum(axis=0) percents = all_sums.apply(lambda x : 100*x / all_sums.sum()) fig, ax = plt.subplots() ax = percents.plot.bar() ax.set_title('structure percentiles') ax.set_ylabel('%') ax.set_xlabel('RNA secondary structure') return percents
0b6148019fe035a3e0713ffd974f8bc041c42f9e
[ "Markdown", "Python" ]
12
Python
kkimatx/RBP_project
04fac40b92f8db913d23bdd6e3fe113c7e6837ba
2f49d632395a8c5fe49d4f73c82b1ea9d4aefe69
refs/heads/master
<repo_name>guoyu07/Java-Dynamic-Web-App<file_sep>/README.md # Java-Dynamic-Web-App Servlets, JSP, HTML and Tomcat. A simple beginning to a web application. This is part of an application. There is a login screen which will allow authorized users to accesss. Behind the scenes a servlet takes care of this in conjunction with a Filter. A hit counter will log the number of successful logins during the session. There is a button menu to select options from only one is implemented at the moment. You will get an HTTP error if you select the unimplemented options. When you select schedule a JSP file will be launched and present an example schedule created by a scriplet. There is a logout screen and confirmation of logout. The application uses Servlets, Filters, Annotations, JSP pages, HTML pages and a little CSS. <file_sep>/SchoolLogin/src/com/justin/servlets/MenuItemsServlet.java package com.justin.servlets; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ScheduleServlet * @author <NAME> * Deals with items selected from menu buttons. Some unimplemented. */ @WebServlet("/MenuItemsServlet") public class MenuItemsServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MenuItemsServlet() { super(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) * Takes appropriate action depending on which button clicked. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; //Loop through all parameters, there should be only one. Set the variable and use to direct //to the correct page. Enumeration<String> en = request.getParameterNames(); while(en.hasMoreElements()) { param = en.nextElement(); } //Conditionals below check and the set page variable. if(param.equals("schedule")) { //Get context and forward on the page request. getServletContext().getRequestDispatcher("/schedule.jsp").forward(request, response); }else if(request.getParameter("new") == null) { //Send HTTP error as the other pages haven't been implemented. response.sendError(501, "I'm sorry, but this content hasn't been created yet."); } } }
17f8baf66f998488a69780988f60e698799a0d54
[ "Markdown", "Java" ]
2
Markdown
guoyu07/Java-Dynamic-Web-App
d5718713ea202bbdba515e1d2c6ae5104b47900d
0d1b6623d48a246a8dbc0fb510cba08237ca2c52
refs/heads/master
<file_sep>import tkinter as tk import tkinter.filedialog from tkinter import messagebox import stix2 import urllib from urllib.parse import * from urllib.request import * from urllib.response import * def bugreport(parent, msg): try: message = urllib.parse.quote_plus(msg) req = urllib.request.Request("http://server.ddns.net/bugreport.php?bodyofmessage=" + message) req.add_header("Content-type", "application/x-www-form-urlencoded") urllib.request.urlopen(req) tk.messagebox.showinfo("Success!", "Bug report submitted successfully.\nThank you very much for your involvement!", parent=parent) except: tk.messagebox.showerror("Error", "Failed to send bug report.\n Check your internet connection and try again later.", parent=parent) parent.destroy() window = tk.Toplevel(relief=tk.FLAT, highlightthickness=0) window.geometry("445x210") window.resizable(width=False, height=False) window.title("Report Bug") window.attributes('-topmost', 'true') window.grab_set() label = tk.Label(window, text="Please describe the issue with as many details as possible,\nprovide your contact info if you want us to reach you back.") label.pack(pady=5) reportEntry = tk.Text(window, font=("OpenSans", 9), width=60, height=8, wrap=tk.WORD) reportEntry.pack(padx=10) submit = tk.Button(window, text="Submit", command = lambda : [(label.config(text="Sending the report...\n", fg="black"), submit.config(text="Please wait..."), label.update(), submit.update(), bugreport(window, reportEntry.get("1.0", tk.END))) if not reportEntry.compare("end-1c", "==", "1.0") else label.config(text="Warning: You cannot submit an empty form!\n", fg="red")]) submit.pack(pady=10) window.mainloop() <file_sep># Bug-Report-Server ### Dependencies Ubuntu Server sendmail (sudo apt-get install sendmail) ### Edit edit the /etc/hosts file: 127.0.0.1 localhost.localdomain localhost hostname (<-here goes the hostname type "hostname" to view) ### Format the php request has the following format: http://serverddns.com/bugreport.php?bodyofmessage=<here goes a url encoded string> <file_sep><?php // the message $msg = $_GET["bodyofmessage"]; // use wordwrap() if lines are longer than 70 characters $msg = wordwrap($msg,70); // send email mail("<EMAIL>","BUG-REPORT",$msg); ?>
db5526ce828c4fec8d13650e0b6fa859a8088e03
[ "Markdown", "Python", "PHP" ]
3
Python
SakisPap/Bug-Report-Server
73a5ee0959172d81c172e1236054f08d54d93fc4
51470e1ed5ad7191601f53680911dfd61522ade1
refs/heads/main
<file_sep>using System; using System.Collections.Generic; namespace CERelayBoard8Serial { public class Factory { #region Singelton private static Lazy<Factory> _Instance; public static Factory Instance => _Instance.Value; static Factory() { _Instance = new Lazy<Factory>(new Factory()); } #endregion private readonly Lazy<Dictionary<string, Controller>> _ControllerCache; private Factory() { _ControllerCache = new Lazy<Dictionary<string, Controller>>(); } public Controller GetController(string port) { if(_ControllerCache.Value.ContainsKey(port)) { return _ControllerCache.Value[port]; } else { var controller = new Controller(port); _ControllerCache.Value.Add(port, controller); return controller; } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using CERelayBoard8Serial.Utils; namespace CERelayBoard8Serial { public class Board { private readonly Lazy<Dictionary<ushort, bool>> _Data; public readonly ushort Address; public event EventHandler<RequestSendMessageEventArgs> RequestSendMessage; #region Relay public bool R1 { get { return _Data.Value[1]; } set { SetData(1, value); } } public bool R2 { get { return _Data.Value[2]; } set { SetData(2, value); } } public bool R3 { get { return _Data.Value[3]; } set { SetData(3, value); } } public bool R4 { get { return _Data.Value[4]; } set { SetData(4, value); } } public bool R5 { get { return _Data.Value[5]; } set { SetData(5, value); } } public bool R6 { get { return _Data.Value[6]; } set { SetData(6, value); } } public bool R7 { get { return _Data.Value[7]; } set { SetData(7, value); } } public bool R8 { get { return _Data.Value[8]; } set { SetData(8, value); } } #endregion internal Board(ushort address) { Address = address; _Data = new Lazy<Dictionary<ushort, bool>>(new Dictionary<ushort, bool> { {1, false }, {2, false }, {3, false }, {4, false }, {5, false }, {6, false }, {7, false }, {8, false }, }); } private void SetData(ushort relay, bool state) { _Data.Value[relay] = state; CallRequestSendMessage(SendCommand.SET_PORT, DataToByte()); } private void CallRequestSendMessage(SendCommand command, byte data) { RequestSendMessage?.Invoke(this, new RequestSendMessageEventArgs { Command = command, Address = Address, Data = data, }); } #region Converters private byte DataToByte() { var res = new byte[1]; var d = new BitArray(new bool[] { _Data.Value[1], _Data.Value[2], _Data.Value[3], _Data.Value[4], _Data.Value[5], _Data.Value[6], _Data.Value[7], _Data.Value[8], }); d.CopyTo(res, 0); return res[0]; } internal void ByteToData(byte data) { var d = new BitArray(new byte[] { data }); _Data.Value[1] = d[0]; _Data.Value[2] = d[1]; _Data.Value[3] = d[2]; _Data.Value[4] = d[3]; _Data.Value[5] = d[4]; _Data.Value[6] = d[5]; _Data.Value[7] = d[6]; _Data.Value[8] = d[7]; } #endregion } } <file_sep># CERelayBoard8Serial .Net library to control the eight fold relay board from Conrad Electronic <file_sep>namespace CERelayBoard8Serial.Utils { public enum SendCommand { NO_OPERATION = 0, SETUP = 1, GET_PORT = 2, SET_PORT = 3, GET_OPTION = 4, SET_OPTION = 5, } public enum RecieveCommand { NO_OPERATION = 255, SETUP = 254, GET_PORT = 243, SET_PORT = 252, GET_OPTION = 251, SET_OPTION = 250, } } <file_sep>using System; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Extensions.Logging; using SerialPortLibNetCore; using CERelayBoard8Serial.Utils; namespace CERelayBoard8Serial { public class Controller { private readonly Lazy<SerialPortInput> _Serial; private readonly WaitForSilence _SilenceWaiter = new WaitForSilence(); public readonly Lazy<Dictionary<ushort,Board>> Boards = new Lazy<Dictionary<ushort,Board>>(); private readonly string _Port; private bool _Initialized; internal Controller(string port) { _Port = port; _Initialized = false; _Serial = new Lazy<SerialPortInput>(new SerialPortInput(new LoggerFactory().CreateLogger<SerialPortInput>())); } public async Task<bool> Init() { if (!_Initialized) { _Serial.Value.SetPort(_Port, 19200, RJCP.IO.Ports.StopBits.One, RJCP.IO.Ports.Parity.None, DataBits.Eight); if (_Serial.Value.Connect()) { //setup & collect boards _Serial.Value.MessageReceived += Setup_MessageReceived; SendMessage(SendCommand.SETUP, 1, 0); await _SilenceWaiter.Wait(1500); _Serial.Value.MessageReceived -= Setup_MessageReceived; if (Boards.Value.Count > 0) { //disable all SendMessage(SendCommand.SET_PORT, 0, 0); //register message reciever _Serial.Value.MessageReceived += Serial_MessageReceived; //prevent double initialization _Initialized = true; } else //no boaards detected { if(_Serial.Value.IsConnected) { _Serial.Value.Disconnect(); } } } } return _Initialized; } private bool SendMessage(SendCommand command, ushort address, byte data) { if (_Serial.Value.IsConnected) { var message = new byte[4]; message[0] = (byte)command; message[1] = (byte)address; message[2] = data; message[3] = (byte)((ushort)command ^ address ^ data); return _Serial.Value.SendMessage(message); } return false; } private void Setup_MessageReceived(object sender, MessageReceivedEventArgs args) { if((RecieveCommand)args.Data[0]==RecieveCommand.SETUP) { _SilenceWaiter.Reset(); var address = (ushort)args.Data[1]; if (!Boards.Value.ContainsKey(address)) { var b = new Board(address); b.RequestSendMessage += RequestSendMessage; Boards.Value.Add(address, b); } } } private void RequestSendMessage(object sender, RequestSendMessageEventArgs e) { SendMessage(e.Command, e.Address, e.Data); } private void Serial_MessageReceived(object sender, MessageReceivedEventArgs args) { var command = (RecieveCommand)args.Data[0]; var address = (ushort)args.Data[1]; var data = args.Data[2]; if (Boards.Value.ContainsKey(address)) { if (command == RecieveCommand.GET_PORT) { Boards.Value[address].ByteToData(data); } } } } } <file_sep>using System; namespace CERelayBoard8Serial.Utils { public class RequestSendMessageEventArgs : EventArgs { public SendCommand Command { get; set; } public ushort Address { get; set; } public byte Data { get; set; } } } <file_sep>using System; using System.Linq; using System.IO.Ports; using System.Threading.Tasks; using NUnit.Framework; namespace CERelayBoard8Serial.Test { class RelayTest { private readonly Lazy<string[]> _Ports; private readonly Lazy<bool> _HasPorts; public RelayTest() { _Ports = new Lazy<string[]>(SerialPort.GetPortNames()); _HasPorts = new Lazy<bool>(_Ports.Value.Length > 0); } [Test] public async Task Initalization1() { var b = Factory.Instance.GetController("not a serial port"); var res = await b.Init(); Assert.IsFalse(res); } [Test] public async Task Initalization2() { if (_HasPorts.Value) { var res = false; foreach(var p in _Ports.Value) { var b = Factory.Instance.GetController(_Ports.Value.First()); res = await b.Init(); if(res) { break; } } Assert.IsTrue(res); } else { Assert.Fail("No serial port detected."); } } } } <file_sep>using System.Threading.Tasks; namespace CERelayBoard8Serial.Utils { internal class WaitForSilence { private int _Awaiter = 0; private int _BaseAwaiter = 0; public async Task Wait(int ms) { _Awaiter = ms; _BaseAwaiter = ms; do { await Task.Delay(1); _Awaiter--; } while (_Awaiter > 0); } public void Reset() { _Awaiter = _BaseAwaiter; } } }
7c7ec3e134fa094343997f2fcfb49fa3a4d922b7
[ "Markdown", "C#" ]
8
C#
kwitsch/CERelayBoard8Serial
11be3367dd6c670048e8fe0b95fa3ba4aef419e0
f27738223bf760ed87ccfabebef7b404326f66d1
refs/heads/main
<file_sep>#pragma once #include "game.h" static ALLEGRO_BITMAP* display_get_icon() { ALLEGRO_BITMAP* icon = al_create_bitmap(16, 16); al_set_target_bitmap(icon); al_put_pixel(0, 0, al_map_rgb(214, 204, 195)); al_put_pixel(0, 1, al_map_rgb(218, 207, 187)); al_put_pixel(0, 2, al_map_rgb(217, 206, 188)); al_put_pixel(0, 3, al_map_rgb(216, 205, 187)); al_put_pixel(0, 4, al_map_rgb(215, 204, 198)); al_put_pixel(0, 5, al_map_rgb(216, 208, 189)); al_put_pixel(0, 6, al_map_rgb(217, 205, 189)); al_put_pixel(0, 7, al_map_rgb(219, 206, 189)); al_put_pixel(0, 8, al_map_rgb(220, 202, 190)); al_put_pixel(0, 9, al_map_rgb(222, 209, 193)); al_put_pixel(0, 10, al_map_rgb(217, 209, 188)); al_put_pixel(0, 11, al_map_rgb(213, 199, 198)); al_put_pixel(0, 12, al_map_rgb(220, 208, 182)); al_put_pixel(0, 13, al_map_rgb(218, 202, 187)); al_put_pixel(0, 14, al_map_rgb(219, 208, 190)); al_put_pixel(0, 15, al_map_rgb(212, 203, 194)); al_put_pixel(1, 0, al_map_rgb(217, 207, 197)); al_put_pixel(1, 1, al_map_rgb(232, 221, 199)); al_put_pixel(1, 2, al_map_rgb(236, 223, 204)); al_put_pixel(1, 3, al_map_rgb(234, 223, 203)); al_put_pixel(1, 4, al_map_rgb(217, 207, 198)); al_put_pixel(1, 5, al_map_rgb(230, 222, 201)); al_put_pixel(1, 6, al_map_rgb(236, 225, 207)); al_put_pixel(1, 7, al_map_rgb(235, 222, 203)); al_put_pixel(1, 8, al_map_rgb(221, 205, 192)); al_put_pixel(1, 9, al_map_rgb(232, 219, 203)); al_put_pixel(1, 10, al_map_rgb(231, 223, 200)); al_put_pixel(1, 11, al_map_rgb(217, 204, 198)); al_put_pixel(1, 12, al_map_rgb(235, 223, 197)); al_put_pixel(1, 13, al_map_rgb(237, 221, 205)); al_put_pixel(1, 14, al_map_rgb(234, 223, 203)); al_put_pixel(1, 15, al_map_rgb(216, 206, 196)); al_put_pixel(2, 0, al_map_rgb(217, 205, 191)); al_put_pixel(2, 1, al_map_rgb(236, 224, 198)); al_put_pixel(2, 2, al_map_rgb(222, 210, 186)); al_put_pixel(2, 3, al_map_rgb(233, 221, 197)); al_put_pixel(2, 4, al_map_rgb(219, 207, 193)); al_put_pixel(2, 5, al_map_rgb(233, 223, 198)); al_put_pixel(2, 6, al_map_rgb(221, 209, 187)); al_put_pixel(2, 7, al_map_rgb(237, 222, 199)); al_put_pixel(2, 8, al_map_rgb(214, 205, 188)); al_put_pixel(2, 9, al_map_rgb(217, 209, 188)); al_put_pixel(2, 10, al_map_rgb(235, 225, 200)); al_put_pixel(2, 11, al_map_rgb(217, 207, 195)); al_put_pixel(2, 12, al_map_rgb(236, 224, 200)); al_put_pixel(2, 13, al_map_rgb(223, 212, 192)); al_put_pixel(2, 14, al_map_rgb(233, 223, 198)); al_put_pixel(2, 15, al_map_rgb(216, 204, 188)); al_put_pixel(3, 0, al_map_rgb(215, 203, 189)); al_put_pixel(3, 1, al_map_rgb(238, 226, 200)); al_put_pixel(3, 2, al_map_rgb(239, 224, 201)); al_put_pixel(3, 3, al_map_rgb(236, 224, 200)); al_put_pixel(3, 4, al_map_rgb(215, 203, 189)); al_put_pixel(3, 5, al_map_rgb(237, 227, 202)); al_put_pixel(3, 6, al_map_rgb(237, 225, 203)); al_put_pixel(3, 7, al_map_rgb(238, 223, 200)); al_put_pixel(3, 8, al_map_rgb(216, 207, 192)); al_put_pixel(3, 9, al_map_rgb(234, 223, 205)); al_put_pixel(3, 10, al_map_rgb(237, 227, 202)); al_put_pixel(3, 11, al_map_rgb(213, 206, 190)); al_put_pixel(3, 12, al_map_rgb(246, 217, 187)); al_put_pixel(3, 13, al_map_rgb(245, 221, 193)); al_put_pixel(3, 14, al_map_rgb(244, 221, 187)); al_put_pixel(3, 15, al_map_rgb(229, 203, 178)); al_put_pixel(4, 0, al_map_rgb(217, 207, 197)); al_put_pixel(4, 1, al_map_rgb(215, 204, 184)); al_put_pixel(4, 2, al_map_rgb(216, 205, 187)); al_put_pixel(4, 3, al_map_rgb(218, 207, 189)); al_put_pixel(4, 4, al_map_rgb(215, 205, 196)); al_put_pixel(4, 5, al_map_rgb(213, 206, 187)); al_put_pixel(4, 6, al_map_rgb(215, 207, 188)); al_put_pixel(4, 7, al_map_rgb(216, 205, 185)); al_put_pixel(4, 8, al_map_rgb(219, 204, 197)); al_put_pixel(4, 9, al_map_rgb(217, 205, 191)); al_put_pixel(4, 10, al_map_rgb(216, 204, 180)); al_put_pixel(4, 11, al_map_rgb(212, 210, 197)); al_put_pixel(4, 12, al_map_rgb(237, 178, 134)); al_put_pixel(4, 13, al_map_rgb(229, 180, 137)); al_put_pixel(4, 14, al_map_rgb(225, 177, 128)); al_put_pixel(4, 15, al_map_rgb(228, 181, 137)); al_put_pixel(5, 0, al_map_rgb(217, 204, 195)); al_put_pixel(5, 1, al_map_rgb(236, 223, 204)); al_put_pixel(5, 2, al_map_rgb(235, 222, 205)); al_put_pixel(5, 3, al_map_rgb(235, 222, 205)); al_put_pixel(5, 4, al_map_rgb(217, 204, 196)); al_put_pixel(5, 5, al_map_rgb(232, 224, 205)); al_put_pixel(5, 6, al_map_rgb(234, 223, 205)); al_put_pixel(5, 7, al_map_rgb(236, 223, 204)); al_put_pixel(5, 8, al_map_rgb(217, 202, 195)); al_put_pixel(5, 9, al_map_rgb(234, 220, 207)); al_put_pixel(5, 10, al_map_rgb(238, 226, 204)); al_put_pixel(5, 11, al_map_rgb(209, 207, 194)); al_put_pixel(5, 12, al_map_rgb(245, 172, 121)); al_put_pixel(5, 13, al_map_rgb(229, 167, 118)); al_put_pixel(5, 14, al_map_rgb(231, 169, 112)); al_put_pixel(5, 15, al_map_rgb(237, 175, 124)); al_put_pixel(6, 0, al_map_rgb(215, 203, 189)); al_put_pixel(6, 1, al_map_rgb(239, 227, 203)); al_put_pixel(6, 2, al_map_rgb(221, 209, 187)); al_put_pixel(6, 3, al_map_rgb(234, 222, 200)); al_put_pixel(6, 4, al_map_rgb(218, 206, 194)); al_put_pixel(6, 5, al_map_rgb(235, 224, 202)); al_put_pixel(6, 6, al_map_rgb(219, 207, 185)); al_put_pixel(6, 7, al_map_rgb(238, 223, 200)); al_put_pixel(6, 8, al_map_rgb(218, 205, 196)); al_put_pixel(6, 9, al_map_rgb(219, 207, 191)); al_put_pixel(6, 10, al_map_rgb(236, 222, 196)); al_put_pixel(6, 11, al_map_rgb(210, 202, 189)); al_put_pixel(6, 12, al_map_rgb(248, 177, 125)); al_put_pixel(6, 13, al_map_rgb(227, 164, 113)); al_put_pixel(6, 14, al_map_rgb(237, 172, 116)); al_put_pixel(6, 15, al_map_rgb(241, 173, 124)); al_put_pixel(7, 0, al_map_rgb(229, 203, 180)); al_put_pixel(7, 1, al_map_rgb(246, 220, 187)); al_put_pixel(7, 2, al_map_rgb(246, 219, 189)); al_put_pixel(7, 3, al_map_rgb(248, 221, 191)); al_put_pixel(7, 4, al_map_rgb(226, 199, 178)); al_put_pixel(7, 5, al_map_rgb(246, 221, 190)); al_put_pixel(7, 6, al_map_rgb(247, 222, 191)); al_put_pixel(7, 7, al_map_rgb(247, 218, 186)); al_put_pixel(7, 8, al_map_rgb(232, 199, 182)); al_put_pixel(7, 9, al_map_rgb(250, 215, 195)); al_put_pixel(7, 10, al_map_rgb(255, 220, 194)); al_put_pixel(7, 11, al_map_rgb(233, 200, 183)); al_put_pixel(7, 12, al_map_rgb(231, 177, 131)); al_put_pixel(7, 13, al_map_rgb(229, 181, 135)); al_put_pixel(7, 14, al_map_rgb(230, 178, 130)); al_put_pixel(7, 15, al_map_rgb(232, 177, 138)); al_put_pixel(8, 0, al_map_rgb(227, 179, 139)); al_put_pixel(8, 1, al_map_rgb(226, 179, 127)); al_put_pixel(8, 2, al_map_rgb(228, 180, 132)); al_put_pixel(8, 3, al_map_rgb(227, 179, 131)); al_put_pixel(8, 4, al_map_rgb(227, 179, 141)); al_put_pixel(8, 5, al_map_rgb(227, 181, 131)); al_put_pixel(8, 6, al_map_rgb(228, 180, 132)); al_put_pixel(8, 7, al_map_rgb(229, 179, 130)); al_put_pixel(8, 8, al_map_rgb(217, 141, 117)); al_put_pixel(8, 9, al_map_rgb(219, 135, 111)); al_put_pixel(8, 10, al_map_rgb(222, 138, 110)); al_put_pixel(8, 11, al_map_rgb(215, 138, 112)); al_put_pixel(8, 12, al_map_rgb(252, 225, 196)); al_put_pixel(8, 13, al_map_rgb(241, 221, 186)); al_put_pixel(8, 14, al_map_rgb(242, 222, 185)); al_put_pixel(8, 15, al_map_rgb(231, 203, 179)); al_put_pixel(9, 0, al_map_rgb(237, 175, 128)); al_put_pixel(9, 1, al_map_rgb(236, 174, 115)); al_put_pixel(9, 2, al_map_rgb(233, 170, 116)); al_put_pixel(9, 3, al_map_rgb(238, 177, 122)); al_put_pixel(9, 4, al_map_rgb(235, 174, 129)); al_put_pixel(9, 5, al_map_rgb(235, 176, 118)); al_put_pixel(9, 6, al_map_rgb(230, 169, 114)); al_put_pixel(9, 7, al_map_rgb(239, 177, 120)); al_put_pixel(9, 8, al_map_rgb(234, 133, 105)); al_put_pixel(9, 9, al_map_rgb(230, 122, 96)); al_put_pixel(9, 10, al_map_rgb(235, 127, 99)); al_put_pixel(9, 11, al_map_rgb(234, 130, 103)); al_put_pixel(9, 12, al_map_rgb(236, 223, 204)); al_put_pixel(9, 13, al_map_rgb(217, 210, 182)); al_put_pixel(9, 14, al_map_rgb(236, 229, 201)); al_put_pixel(9, 15, al_map_rgb(215, 201, 190)); al_put_pixel(10, 0, al_map_rgb(239, 176, 132)); al_put_pixel(10, 1, al_map_rgb(228, 166, 109)); al_put_pixel(10, 2, al_map_rgb(227, 164, 111)); al_put_pixel(10, 3, al_map_rgb(241, 178, 125)); al_put_pixel(10, 4, al_map_rgb(235, 172, 129)); al_put_pixel(10, 5, al_map_rgb(236, 175, 120)); al_put_pixel(10, 6, al_map_rgb(232, 171, 117)); al_put_pixel(10, 7, al_map_rgb(241, 176, 122)); al_put_pixel(10, 8, al_map_rgb(233, 132, 102)); al_put_pixel(10, 9, al_map_rgb(236, 126, 101)); al_put_pixel(10, 10, al_map_rgb(227, 119, 93)); al_put_pixel(10, 11, al_map_rgb(241, 132, 109)); al_put_pixel(10, 12, al_map_rgb(234, 222, 206)); al_put_pixel(10, 13, al_map_rgb(230, 222, 199)); al_put_pixel(10, 14, al_map_rgb(233, 225, 204)); al_put_pixel(10, 15, al_map_rgb(220, 203, 196)); al_put_pixel(11, 0, al_map_rgb(229, 177, 140)); al_put_pixel(11, 1, al_map_rgb(233, 181, 133)); al_put_pixel(11, 2, al_map_rgb(229, 176, 132)); al_put_pixel(11, 3, al_map_rgb(230, 179, 134)); al_put_pixel(11, 4, al_map_rgb(227, 177, 142)); al_put_pixel(11, 5, al_map_rgb(230, 182, 134)); al_put_pixel(11, 6, al_map_rgb(225, 174, 129)); al_put_pixel(11, 7, al_map_rgb(232, 180, 133)); al_put_pixel(11, 8, al_map_rgb(222, 140, 116)); al_put_pixel(11, 9, al_map_rgb(221, 135, 112)); al_put_pixel(11, 10, al_map_rgb(222, 138, 114)); al_put_pixel(11, 11, al_map_rgb(223, 136, 117)); al_put_pixel(11, 12, al_map_rgb(220, 208, 192)); al_put_pixel(11, 13, al_map_rgb(217, 204, 185)); al_put_pixel(11, 14, al_map_rgb(219, 206, 187)); al_put_pixel(11, 15, al_map_rgb(221, 203, 199)); al_put_pixel(12, 0, al_map_rgb(226, 201, 181)); al_put_pixel(12, 1, al_map_rgb(245, 220, 189)); al_put_pixel(12, 2, al_map_rgb(248, 223, 193)); al_put_pixel(12, 3, al_map_rgb(246, 221, 191)); al_put_pixel(12, 4, al_map_rgb(224, 199, 179)); al_put_pixel(12, 5, al_map_rgb(247, 224, 193)); al_put_pixel(12, 6, al_map_rgb(247, 221, 194)); al_put_pixel(12, 7, al_map_rgb(246, 219, 190)); al_put_pixel(12, 8, al_map_rgb(235, 200, 180)); al_put_pixel(12, 9, al_map_rgb(249, 214, 195)); al_put_pixel(12, 10, al_map_rgb(254, 219, 197)); al_put_pixel(12, 11, al_map_rgb(237, 198, 183)); al_put_pixel(12, 12, al_map_rgb(230, 219, 199)); al_put_pixel(12, 13, al_map_rgb(238, 226, 204)); al_put_pixel(12, 14, al_map_rgb(236, 224, 202)); al_put_pixel(12, 15, al_map_rgb(215, 201, 192)); al_put_pixel(13, 0, al_map_rgb(218, 206, 194)); al_put_pixel(13, 1, al_map_rgb(232, 220, 196)); al_put_pixel(13, 2, al_map_rgb(220, 208, 186)); al_put_pixel(13, 3, al_map_rgb(236, 224, 202)); al_put_pixel(13, 4, al_map_rgb(216, 204, 192)); al_put_pixel(13, 5, al_map_rgb(235, 224, 202)); al_put_pixel(13, 6, al_map_rgb(221, 208, 189)); al_put_pixel(13, 7, al_map_rgb(237, 222, 201)); al_put_pixel(13, 8, al_map_rgb(217, 204, 188)); al_put_pixel(13, 9, al_map_rgb(221, 209, 193)); al_put_pixel(13, 10, al_map_rgb(234, 223, 203)); al_put_pixel(13, 11, al_map_rgb(216, 202, 189)); al_put_pixel(13, 12, al_map_rgb(241, 228, 209)); al_put_pixel(13, 13, al_map_rgb(219, 204, 185)); al_put_pixel(13, 14, al_map_rgb(237, 222, 199)); al_put_pixel(13, 15, al_map_rgb(222, 208, 197)); al_put_pixel(14, 0, al_map_rgb(219, 205, 194)); al_put_pixel(14, 1, al_map_rgb(236, 224, 202)); al_put_pixel(14, 2, al_map_rgb(237, 222, 203)); al_put_pixel(14, 3, al_map_rgb(238, 225, 206)); al_put_pixel(14, 4, al_map_rgb(216, 203, 194)); al_put_pixel(14, 5, al_map_rgb(237, 226, 206)); al_put_pixel(14, 6, al_map_rgb(234, 221, 202)); al_put_pixel(14, 7, al_map_rgb(240, 225, 204)); al_put_pixel(14, 8, al_map_rgb(218, 204, 191)); al_put_pixel(14, 9, al_map_rgb(235, 223, 209)); al_put_pixel(14, 10, al_map_rgb(232, 224, 203)); al_put_pixel(14, 11, al_map_rgb(216, 204, 188)); al_put_pixel(14, 12, al_map_rgb(237, 223, 210)); al_put_pixel(14, 13, al_map_rgb(239, 224, 205)); al_put_pixel(14, 14, al_map_rgb(237, 225, 203)); al_put_pixel(14, 15, al_map_rgb(216, 203, 194)); al_put_pixel(15, 0, al_map_rgb(218, 204, 193)); al_put_pixel(15, 1, al_map_rgb(217, 205, 183)); al_put_pixel(15, 2, al_map_rgb(221, 206, 187)); al_put_pixel(15, 3, al_map_rgb(217, 204, 185)); al_put_pixel(15, 4, al_map_rgb(217, 204, 195)); al_put_pixel(15, 5, al_map_rgb(217, 206, 186)); al_put_pixel(15, 6, al_map_rgb(217, 204, 185)); al_put_pixel(15, 7, al_map_rgb(220, 205, 184)); al_put_pixel(15, 8, al_map_rgb(218, 204, 191)); al_put_pixel(15, 9, al_map_rgb(217, 205, 191)); al_put_pixel(15, 10, al_map_rgb(218, 210, 189)); al_put_pixel(15, 11, al_map_rgb(216, 208, 189)); al_put_pixel(15, 12, al_map_rgb(218, 201, 191)); al_put_pixel(15, 13, al_map_rgb(221, 205, 189)); al_put_pixel(15, 14, al_map_rgb(217, 205, 183)); al_put_pixel(15, 15, al_map_rgb(217, 204, 195)); // https://github.com/liballeg/allegro5/blob/b70f37412a082293f26e86ff9c0b6ac7c151d2d0/examples/ex_icon.c#L70 al_set_target_backbuffer(game_display); return icon; }<file_sep>#pragma once #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> ALLEGRO_FONT* font_grid_mobile; ALLEGRO_FONT* font_grid_desktop; ALLEGRO_FONT* font_credits; void font_load_all();<file_sep>#include <math.h> #include <stdio.h> #include <assert.h> #include <string.h> #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> #include "game.h" #include "game_grid.h" #include "game_palette.h" #include "game_renderer.h" #include "game_font.h" GameScreen game_current_screen = GameScreen_HOME; void render_home_screen(); void render_ingame_screen(); void render_victory_screen(); void render_current_screen() { switch (game_current_screen) { case GameScreen_HOME: render_home_screen(); break; case GameScreen_INGAME: render_ingame_screen(); break; case GameScreen_VICTORY: render_victory_screen(); break; } al_flip_display(); }<file_sep>#include <allegro5/allegro.h> #include <allegro5/allegro_ttf.h> #include "game.h" #include "game_font.h" #include "game_palette.h" #include "game_renderer.h" GameButtonPosition game_play_button_position = { 0 }; void render_home_screen() { // Set background color al_clear_to_color(COLOR_BACKGROUND); float width = (float)al_get_display_width(game_display); float height = (float)al_get_display_height(game_display); // Draw play button float half_width = width / 2; float half_height = height / 2; float pb_side = min(width, height) * 25 / 100; float pb_half_side = pb_side / 2; float pb_start_x = half_width - pb_half_side; float pb_end_x = half_width + pb_half_side; float pb_start_y = half_height - pb_half_side; float pb_end_y = half_height + pb_half_side; const float pb_border_radius = 6; //px game_play_button_position.start_x = pb_start_x; game_play_button_position.end_x = pb_end_x; game_play_button_position.start_y = pb_start_y; game_play_button_position.end_y = pb_end_y; al_draw_filled_rounded_rectangle(pb_start_x, pb_start_y, pb_end_x, pb_end_y, pb_border_radius, pb_border_radius, COLOR_PLAY_BUTTON_BACKGROUND); float icon_half_side = pb_side * 20 / 100; float icon_center_x = (pb_start_x + pb_end_x) / 2 + icon_half_side * 14 / 100; float icon_center_y = (pb_start_y + pb_end_y) / 2; al_draw_filled_triangle(icon_center_x - icon_half_side, icon_center_y - icon_half_side, icon_center_x - icon_half_side, icon_center_y + icon_half_side, icon_center_x + icon_half_side, icon_center_y, COLOR_PLAY_BUTTON_TRIANGLE); // Draw credits int text_height = al_get_font_line_height(font_credits); float text_x = 4; float text_y = height - (text_height + 4); al_draw_text(font_credits, COLOR_SQUARE_TEXT, text_x, text_y, 0, "loiury"); text_y -= text_height; al_draw_text(font_credits, COLOR_SQUARE_TEXT, text_x, text_y, 0, "Wdestroier"); text_y -= text_height; al_draw_text(font_credits, COLOR_SQUARE_TEXT, text_x, text_y, 0, "Credits"); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "game.h" #include "game_resource.h" #include "game_font.h" char* game_get_folder() { char* unix_executable_name = strrchr(game_executable_path, '/') + 1; char* nt_executable_name = strrchr(game_executable_path, '\\') + 1; char* executable_name = max(unix_executable_name, nt_executable_name); size_t folder_path_length = (size_t)(executable_name - game_executable_path); char* game_folder = calloc(folder_path_length + 1, 1); if (game_folder != 0) { memcpy(game_folder, game_executable_path, folder_path_length); } return game_folder; } char* resource_extract(char* file_name, char* file_bytes, size_t file_length) { char* file_absolute_path = calloc(strlen(game_folder) + strlen(file_name) + 1, 1); if (file_absolute_path != 0) { strcat(file_absolute_path, game_folder); strcat(file_absolute_path, file_name); FILE* file = fopen(file_absolute_path, "wb"); fwrite(file_bytes, file_length, 1, file); } return file_absolute_path; }<file_sep>#include "game.h" #include "game_logger.h" int main(int argc, char** argv) { char* executable_path = argv[0]; game_run(executable_path); return 0; }<file_sep>#pragma once #include <stdint.h> char* game_get_folder(); char* resource_extract(char* file_name, char* file_bytes, size_t file_length);<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <time.h> #include <stdio.h> #include <stdlib.h> #include "game_logger.h" char* logger_get_current_time() { time_t now; time(&now); char* buffer = malloc(32); if (buffer != 0) { strftime(buffer, 32, "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); } return buffer; } void log_level(char* level, char* message) { char* current_time = logger_get_current_time(); printf("%s [%s] %s\n", current_time, level, message); free(current_time); } void log_info(char* message) { log_level("INFO", message); } void log_debug(char* message) { #ifdef DEBUG log_any("DEBUG", message); #endif } void log_warn(char* message) { log_level("WARN", message); } void log_error(char* message) { log_level("ERROR", message); }<file_sep>#pragma once typedef enum { GameScreen_HOME, GameScreen_INGAME, GameScreen_VICTORY, } GameScreen; typedef struct { float start_x; float end_x; float start_y; float end_y; } GameButtonPosition; extern GameScreen game_current_screen; extern GameButtonPosition game_play_button_position; void render_current_screen();<file_sep>#pragma once #include <allegro5/allegro.h> #define COLOR_BACKGROUND al_map_rgb(251,248,239) #define COLOR_PLAY_BUTTON_BACKGROUND al_map_rgb(246,93,59) #define COLOR_PLAY_BUTTON_TRIANGLE al_map_rgb(255,255,255) #define COLOR_GRID_BACKGROUND al_map_rgb(189,173,160) #define COLOR_SQUARE_VALUE_0 al_map_rgb(214,205,196) #define COLOR_SQUARE_VALUE_1 al_map_rgb(238,228,218) #define COLOR_SQUARE_VALUE_2 al_map_rgb(236,224,200) #define COLOR_SQUARE_VALUE_3 al_map_rgb(242,177,121) #define COLOR_SQUARE_VALUE_4 al_map_rgb(245,149,99) #define COLOR_SQUARE_VALUE_5 al_map_rgb(245,124,95) #define COLOR_SQUARE_VALUE_6 al_map_rgb(246,93,59) #define COLOR_SQUARE_VALUE_7 al_map_rgb(237,206,113) #define COLOR_SQUARE_VALUE_8 al_map_rgb(237,204,97) #define COLOR_SQUARE_VALUE_9 al_map_rgb(236,200,80) #define COLOR_SQUARE_VALUE_10 al_map_rgb(239,197,63) #define COLOR_SQUARE_VALUE_11 al_map_rgb(238,194,46) #define COLOR_SQUARE_TEXT al_map_rgb(124,114,105) #define COLOR_CROWN_SMALL_SPHEROID al_map_rgb(151,29,19) #define COLOR_CROWN_BIG_SPHEROID al_map_rgb(194,44,31) #define COLOR_CROWN_DIM_SPINE al_map_rgb(251,182,60) #define COLOR_CROWN_BRIGHT_SPINE al_map_rgb(255,203,86) #define COLOR_CROWN_SPINE_BALL al_map_rgb(224,160,38) #define COLOR_CROWN_BASE_OUTER al_map_rgb(250,184,61) #define COLOR_CROWN_BASE_INNER al_map_rgb(255,196,71) #define COLOR_CROWN_REFLEX al_map_rgb(253,207,99) #define COLOR_VICTORY_TEXT al_map_rgb(124,114,105)<file_sep>#include <allegro5/allegro.h> #include <allegro5/allegro_ttf.h> #include "game.h" #include "game_font.h" #include "game_palette.h" #include "game_renderer.h" void draw_crown(float pos_x, float pos_y) { // Draw velvet al_draw_filled_ellipse(pos_x, pos_y - 3 - 60, 6, 4, COLOR_CROWN_SMALL_SPHEROID); al_draw_filled_ellipse(pos_x, pos_y - 3 - 30, 45, 30, COLOR_CROWN_BIG_SPHEROID); // Draw spines const float first_ball_x = pos_x - 45 - 18; const float first_ball_y = pos_y - 60; al_draw_filled_triangle(pos_x - 45, pos_y, first_ball_x, first_ball_y, pos_x - 10, pos_y, COLOR_CROWN_DIM_SPINE); al_draw_filled_circle(first_ball_x, first_ball_y, 6, COLOR_CROWN_SPINE_BALL); const float fourth_ball_x = pos_x + 45 + 16; const float fourth_ball_y = pos_y - 63; al_draw_filled_triangle(pos_x + 10, pos_y, fourth_ball_x, fourth_ball_y, pos_x + 45 + 1, pos_y, COLOR_CROWN_DIM_SPINE); al_draw_filled_circle(fourth_ball_x, fourth_ball_y, 6, COLOR_CROWN_SPINE_BALL); const float second_ball_x = pos_x - 45 + 18; const float second_ball_y = pos_y - 74; al_draw_filled_triangle(pos_x - 45 + 7, pos_y, second_ball_x, second_ball_y, pos_x + 9, pos_y, COLOR_CROWN_BRIGHT_SPINE); al_draw_filled_circle(second_ball_x, second_ball_y, 6, COLOR_CROWN_SPINE_BALL); const float third_ball_x = pos_x + 45 - 18; const float third_ball_y = pos_y - 73; al_draw_filled_triangle(pos_x - 8, pos_y, third_ball_x, third_ball_y, pos_x + 45 - 6, pos_y, COLOR_CROWN_BRIGHT_SPINE); al_draw_filled_circle(third_ball_x, third_ball_y, 6, COLOR_CROWN_SPINE_BALL); // Draw base al_draw_filled_rectangle(pos_x - 45, pos_y, pos_x + 45 + 1, pos_y + 14, COLOR_CROWN_BASE_INNER); al_draw_filled_rectangle(pos_x - 45, pos_y - 3, pos_x + 45, pos_y + 3, COLOR_CROWN_BASE_OUTER); al_draw_filled_circle(pos_x - 45 - 1, pos_y, 3, COLOR_CROWN_BASE_OUTER); al_draw_filled_circle(pos_x + 45 + 2, pos_y, 3, COLOR_CROWN_BASE_OUTER); al_draw_filled_rectangle(pos_x - 45, pos_y + 14 - 3, pos_x + 45, pos_y + 14 + 3, COLOR_CROWN_BASE_OUTER); al_draw_filled_circle(pos_x - 45 - 1, pos_y + 14, 3, COLOR_CROWN_BASE_OUTER); al_draw_filled_circle(pos_x + 45 + 2, pos_y + 14, 3, COLOR_CROWN_BASE_OUTER); // Draw reflex al_draw_line(pos_x - 45, pos_y - 1, pos_x - 45 + 16, pos_y - 2, COLOR_CROWN_REFLEX, 1); al_draw_line(pos_x - 43, pos_y, pos_x - 40 + 8, pos_y - 1, COLOR_CROWN_REFLEX, 1); al_draw_line(pos_x - 45, pos_y - 1, pos_x - 45 + 16, pos_y - 2, COLOR_CROWN_REFLEX, 1); al_draw_line(pos_x - 43, pos_y, pos_x - 40 + 8, pos_y - 1, COLOR_CROWN_REFLEX, 1); } void render_victory_screen() { // Set background color al_clear_to_color(COLOR_BACKGROUND); // Draw crown float width = (float)al_get_display_width(game_display); float height = (float)al_get_display_height(game_display); float half_width = width / 2; float half_height = height / 2; draw_crown(half_width, half_height); ALLEGRO_FONT* font = width < 500 ? font_grid_mobile : font_grid_desktop; const char* message = "V i c t o r y !"; int text_width = al_get_text_width(font, message); int text_height = al_get_font_line_height(font); float text_start_x = half_width - text_width / 2; float text_start_y = half_height - text_height / 2 + 88; al_draw_text(font, COLOR_SQUARE_TEXT, text_start_x, text_start_y, 0, message); }<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <math.h> #include <stdio.h> #include <allegro5/allegro.h> #include <allegro5/allegro_ttf.h> #include "game.h" #include "game_grid.h" #include "game_font.h" #include "game_palette.h" #include "game_renderer.h" ALLEGRO_COLOR grid_get_square_color(int value) { ALLEGRO_COLOR color; int exponent = (int)round(log(value) / log(2)); switch (exponent) { case 1: // 2 color = COLOR_SQUARE_VALUE_1; break; case 2: // 4 color = COLOR_SQUARE_VALUE_2; break; case 3: // 8 color = COLOR_SQUARE_VALUE_3; break; case 4: // 16 color = COLOR_SQUARE_VALUE_4; break; case 5: // 32 color = COLOR_SQUARE_VALUE_5; break; case 6: // 64 color = COLOR_SQUARE_VALUE_6; break; case 7: // 128 color = COLOR_SQUARE_VALUE_7; break; case 8: // 256 color = COLOR_SQUARE_VALUE_8; break; case 9: // 512 color = COLOR_SQUARE_VALUE_9; break; case 10: // 1024 color = COLOR_SQUARE_VALUE_10; break; case 11: // 2048 color = COLOR_SQUARE_VALUE_11; break; default: // 0 or any number beyond 2048 color = COLOR_SQUARE_VALUE_0; break; } return color; } void render_ingame_screen() { // Set the background color al_clear_to_color(COLOR_BACKGROUND); float width = (float)al_get_display_width(game_display); float height = (float)al_get_display_height(game_display); float half_width = width / 2; float half_height = height / 2; // Draw the grid background float bg_side = min(width, height) * 80 / 100; float bg_half_side = bg_side / 2; const float bg_padding = 8; //px float bg_start_x = half_width - bg_half_side + bg_padding; float bg_start_y = half_height - bg_half_side + bg_padding; float bg_end_x = half_width + bg_half_side - bg_padding; float bg_end_y = half_height + bg_half_side - bg_padding; const float bg_border_radius = 10; //px al_draw_filled_rounded_rectangle(bg_start_x, bg_start_y, bg_end_x, bg_end_y, bg_border_radius, bg_border_radius, COLOR_GRID_BACKGROUND); // Draw the grid float bg_width = bg_end_x - bg_start_x; float bg_height = bg_end_y - bg_start_y; const float sq_padding = 7; //px const float sq_border_radius = 5; //px float square_size = (bg_width - sq_padding * (GRID_SIDE_SQUARE_COUNT + 1)) / GRID_SIDE_SQUARE_COUNT; for (int r = 0; r < GRID_SIDE_SQUARE_COUNT; r++) { float square_start_y = bg_start_y + sq_padding * (r + 1) + square_size * r; float square_end_y = square_start_y + square_size; for (int c = 0; c < GRID_SIDE_SQUARE_COUNT; c++) { float square_start_x = bg_start_x + sq_padding * (c + 1) + square_size * c; float square_end_x = square_start_x + square_size; int square_value = game_grid[r][c]; al_draw_filled_rounded_rectangle(square_start_x, square_start_y, square_end_x, square_end_y, sq_border_radius, sq_border_radius, grid_get_square_color(square_value)); if (square_value) { // Draw the square value char square_value_str[21]; // long long largest width + 1 sprintf(square_value_str, "%d", square_value); ALLEGRO_FONT* font_grid = width < 500 ? font_grid_mobile : font_grid_desktop; int text_width = al_get_text_width(font_grid, square_value_str); int text_height = al_get_font_line_height(font_grid); float text_start_x = square_start_x + square_size / 2 - text_width / 2; float text_start_y = square_start_y + square_size / 2 - text_height / 2; al_draw_text(font_grid, COLOR_SQUARE_TEXT, text_start_x, text_start_y, 0, square_value_str); } } } }<file_sep>#include <stdio.h> #include "game_grid.h" bool grid_move_up() { bool moved = false; for (int n = 0; n < GRID_SIDE_SQUARE_COUNT - 1; n++) { for (int c = 0; c < GRID_SIDE_SQUARE_COUNT; c++) { // Ignore the last square (GRID_SIDE_SQUARE_COUNT - 1), because the // next value (GRID_SIDE_SQUARE_COUNT) doesn't exist for (int r = 0; r < GRID_SIDE_SQUARE_COUNT - 1; r++) { int* current_square_value = &game_grid[r][c]; int* next_square_value = &game_grid[r + 1][c]; if (*next_square_value == 0) { continue; } else if (*next_square_value == *current_square_value) { *current_square_value += *next_square_value; *next_square_value = 0; moved = true; } else if (*current_square_value == 0) { *current_square_value = *next_square_value; *next_square_value = 0; moved = true; } } } } return moved; } bool grid_move_down() { bool moved = false; for (int n = 0; n < GRID_SIDE_SQUARE_COUNT - 1; n++) { for (int c = 0; c < GRID_SIDE_SQUARE_COUNT; c++) { // Ignore the last square (0), because the prev value (-1) doesn't exist for (int r = GRID_SIDE_SQUARE_COUNT - 1; r > 0; r--) { int* current_square_value = &game_grid[r][c]; int* prev_square_value = &game_grid[r - 1][c]; if (*prev_square_value == 0) { continue; } else if (*prev_square_value == *current_square_value) { *current_square_value += *prev_square_value; *prev_square_value = 0; moved = true; } else if (*current_square_value == 0) { *current_square_value = *prev_square_value; *prev_square_value = 0; moved = true; } } } } return moved; } bool grid_move_left() { bool moved = false; for (int n = 0; n < GRID_SIDE_SQUARE_COUNT - 1; n++) { for (int r = 0; r < GRID_SIDE_SQUARE_COUNT; r++) { int* current_row = game_grid[r]; // Ignore the last square (GRID_SIDE_SQUARE_COUNT - 1), because the // next value (GRID_SIDE_SQUARE_COUNT) doesn't exist for (int c = 0; c < GRID_SIDE_SQUARE_COUNT - 1; c++) { int* current_square_value = &current_row[c]; int* next_square_value = &current_row[c + 1]; if (*next_square_value == 0) { continue; } else if (*next_square_value == *current_square_value) { *current_square_value += *next_square_value; *next_square_value = 0; moved = true; } else if (*current_square_value == 0) { *current_square_value = *next_square_value; *next_square_value = 0; moved = true; } } } } return moved; } bool grid_move_right() { bool moved = false; for (int n = 0; n < GRID_SIDE_SQUARE_COUNT - 1; n++) { for (int r = 0; r < GRID_SIDE_SQUARE_COUNT; r++) { int* current_row = game_grid[r]; // Ignore the last square (0), because the previous value (-1) doesn't exist for (int c = GRID_SIDE_SQUARE_COUNT - 1; c > 0; c--) { int* current_square_value = &current_row[c]; int* prev_square_value = &current_row[c - 1]; if (*prev_square_value == 0) { continue; } else if (*prev_square_value == *current_square_value) { *current_square_value += *prev_square_value; *prev_square_value = 0; moved = true; } else if (*current_square_value == 0) { *current_square_value = *prev_square_value; *prev_square_value = 0; moved = true; } } } } return moved; }<file_sep>#pragma once void log_info(char* message); void log_debug(char* message); void log_warn(char* message); void log_error(char* message);<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include "game_grid.h" GameGrid game_grid = { 0 }; int* grid_find_free_square() { int valid_square_count = 0; int* valid_squares[GRID_SIDE_SQUARE_COUNT * GRID_SIDE_SQUARE_COUNT]; for (int r = 0; r < GRID_SIDE_SQUARE_COUNT; r++) { for (int c = 0; c < GRID_SIDE_SQUARE_COUNT; c++) { if (game_grid[r][c] == 0) { valid_squares[valid_square_count] = &game_grid[r][c]; valid_square_count++; } } } int* square = 0; if (valid_square_count != 0) { // Generate a random number between 0 and valid_square_count - 1 int square_index = rand() % valid_square_count; square = valid_squares[square_index]; } return square; } bool grid_is_full() { return grid_find_free_square() == 0; } bool grid_spawn_square(int value) { bool spawned = false; int* free_square = grid_find_free_square(); if (free_square) { *free_square = value; spawned = true; } return spawned; } void grid_reset() { memset(game_grid, 0, sizeof game_grid); grid_spawn_square(2); grid_spawn_square(2); } bool grid_contains_square(int value) { bool contains_square = false; int grid_square_count = sizeof game_grid[0] / sizeof game_grid[0][0]; for (int r = 0; r < grid_square_count; r++) { for (int c = 0; c < grid_square_count; c++) { if (game_grid[r][c] == value) { contains_square = true; goto iteration_over; } } } iteration_over: return contains_square; }<file_sep>#include <stdio.h> #include "game_logger.h" #include "game_mouse.h" #include "game_renderer.h" #include "game_grid.h" void mouse_button_down(int button, int x, int y) { // Left click if (button == 1) { switch (game_current_screen) { case GameScreen_HOME: if (x >= game_play_button_position.start_x && x <= game_play_button_position.end_x && y >= game_play_button_position.start_y && y <= game_play_button_position.end_y) { grid_reset(); game_current_screen = GameScreen_INGAME; log_info("Grid reset"); } break; } } }<file_sep>#include <math.h> #include <stdio.h> #include <string.h> #include <stdbool.h> #include "game.h" #include "game_logger.h" #include "game_resource.h" #include "game_font.h" #include "resource_helvetica_font.h" bool font_initialized = false; char* font_absolute_path = 0; ALLEGRO_FONT* font_grid_mobile; ALLEGRO_FONT* font_grid_desktop; ALLEGRO_FONT* font_credits; void font_load_all() { int width = al_get_display_width(game_display); if (font_initialized) { al_destroy_font(font_grid_mobile); al_destroy_font(font_grid_desktop); } else { font_absolute_path = resource_extract("HelveticaNeueInterface.ttf", font_helvetica_neue_interface, sizeof font_helvetica_neue_interface); font_credits = al_load_font(font_absolute_path, width * 2 / 100, 0); } font_grid_mobile = al_load_font(font_absolute_path, width * 3 / 100, 0); font_grid_desktop = al_load_font(font_absolute_path, width * 5 / 100, 0); font_initialized = true; }<file_sep>#pragma once void mouse_button_down(int button, int x, int y);<file_sep>#pragma once #include <allegro5/allegro.h> #include <allegro5/allegro_primitives.h> extern char* game_executable_path; extern char* game_folder; //TODO If the project has errors related to allegro_font.h, then comment these lines in allegro_font.h: //ALLEGRO_FONT_PRINTFUNC(void, al_draw_textf, (const ALLEGRO_FONT *font, ALLEGRO_COLOR color, float x, float y, int flags, char const *format, ...), 6, 7); //ALLEGRO_FONT_PRINTFUNC(void, al_draw_justified_textf, (const ALLEGRO_FONT *font, ALLEGRO_COLOR color, float x1, float x2, float y, float diff, int flags, char const *format, ...), 8, 9); extern ALLEGRO_DISPLAY* game_display; void game_run(char* executable_path);<file_sep>#pragma once void keyboard_key_down(int key_code);<file_sep>#pragma once #include <stdbool.h> #define GRID_SIDE_SQUARE_COUNT 4 typedef int GameGrid[GRID_SIDE_SQUARE_COUNT][GRID_SIDE_SQUARE_COUNT]; extern GameGrid game_grid; bool grid_spawn_square(int value); bool grid_contains_square(int value); bool grid_is_full(); void grid_reset(); bool grid_move_up(); bool grid_move_down(); bool grid_move_left(); bool grid_move_right();<file_sep>#define _CRT_SECURE_NO_WARNINGS #include <math.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <allegro5/allegro_ttf.h> #include <allegro5/allegro_image.h> #include "game.h" #include "game_logger.h" #include "game_resource.h" #include "resource_display_icon.h" #include "game_mouse.h" #include "game_renderer.h" #include "game_font.h" #include "game_keyboard.h" char* game_executable_path; char* game_folder; ALLEGRO_DISPLAY* game_display; void game_run(char* executable_path) { log_info("Starting game"); game_executable_path = executable_path; game_folder = game_get_folder(); srand((unsigned int)time(0)); if (!al_init()) { log_error("Could not initialize Allegro"); exit(-1); } al_set_new_display_flags(ALLEGRO_WINDOWED | ALLEGRO_RESIZABLE); game_display = al_create_display(800, 600); if (!game_display) { log_error("Could not initialize the display"); exit(-1); } al_set_window_title(game_display, "2048"); al_install_mouse(); al_install_keyboard(); al_init_primitives_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_image_addon(); ALLEGRO_BITMAP* display_icon = display_get_icon(); al_set_display_icon(game_display, display_icon); font_load_all(); ALLEGRO_EVENT_QUEUE* event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_display_event_source(game_display)); const int fps = 30; ALLEGRO_TIMER* timer = al_create_timer(1.0 / fps); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_start_timer(timer); bool running = true; while (running) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); switch (event.type) { case ALLEGRO_EVENT_TIMER: render_current_screen(); break; case ALLEGRO_EVENT_KEY_DOWN: keyboard_key_down(event.keyboard.keycode); break; case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: mouse_button_down(event.mouse.button, event.mouse.x, event.mouse.y); break; case ALLEGRO_EVENT_DISPLAY_RESIZE: al_acknowledge_resize(game_display); break; case ALLEGRO_EVENT_DISPLAY_CLOSE: running = false; break; } } al_destroy_event_queue(event_queue); al_destroy_display(game_display); log_info("Closing game"); }<file_sep><table align="center"> <tr> <td align="center"> <img src="images/Icon.jpg" alt="game icon" width="32"/> </td> <td> <a>Combine squares to get 2048 points inside a square and win the game</a> </td> </tr> </table> <br/> <p>Game screenshots</p> <br/> <p align="center"> <img src="images/Mobile.png" alt="game icon" width="760"/> </p> <br/> <p align="center"> <img src="images/Desktop.png" alt="game icon" width="760"/> </p> <file_sep>#include <stdbool.h> #include <allegro5/allegro.h> #include "game_logger.h" #include "game_keyboard.h" #include "game_renderer.h" #include "game_grid.h" void keyboard_key_down_ingame(key_code) { bool moved = false; switch (key_code) { case ALLEGRO_KEY_UP: moved = grid_move_up(); break; case ALLEGRO_KEY_DOWN: moved = grid_move_down(); break; case ALLEGRO_KEY_LEFT: moved = grid_move_left(); break; case ALLEGRO_KEY_RIGHT: moved = grid_move_right(); break; } if (moved) { if (grid_contains_square(2048)) { log_info("Player has won the game"); game_current_screen = GameScreen_VICTORY; } else { // Spawns a square if the grid is not full int square_value = (rand() % 5 == 4) ? 4 : 2; grid_spawn_square(square_value); } } else { if (grid_is_full()) { log_info("Player has lost the game"); grid_reset(); //TODO Create a defeat screen and show it? } } } void keyboard_key_down(int key_code) { if (game_current_screen == GameScreen_INGAME) { keyboard_key_down_ingame(key_code); } if (key_code == ALLEGRO_KEY_F5) { grid_reset(); game_current_screen = GameScreen_INGAME; } }
dab7b6ae7fca22220eda63e4ed4568552a9afc2f
[ "Markdown", "C" ]
24
C
Wdestroier/2048
48efdc0d58d7c54c44da58aedc8088de3a41a9bf
600d6b7f735ee8ab84cf4ae8bc92f3c429c95350
refs/heads/master
<file_sep>package oquantour.data.datahelper; import oquantour.po.UserPO; import oquantour.util.tools.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Session; /** * Created by island on 5/5/17. */ public class UserDataHelper { //Session session = HibernateUtil.getSession(); /** * 数据库中新增用户 * @param userPO * @return */ public boolean addUser(UserPO userPO){ Session session = null; try { session = HibernateUtil.getSession(); session.beginTransaction(); session.save(userPO); return true; } catch (HibernateException e) { e.printStackTrace(); return false; } finally { if (null != session) { session.getTransaction().commit(); HibernateUtil.closeSession(session); } } //setHibernateTemplate(); //this.hibernateTemplate.save(userPO); } /** * 数据库中更新用户信息 * @param userPO * @return */ public boolean modifyUser(UserPO userPO) { Session session = null; try { session = HibernateUtil.getSession(); session.beginTransaction(); session.update(userPO); return true; } catch (HibernateException e) { e.printStackTrace(); return false; } finally { if (null != session) { session.getTransaction().commit(); HibernateUtil.closeSession(session); } } } /** * 根据用户名在数据库中查找用户 * @param username * @return */ public UserPO findUserByName(String username) { Session session = null; try { session = HibernateUtil.getSession(); session.beginTransaction(); UserPO userPO = (UserPO) session.get(UserPO.class, username); return userPO; } catch (HibernateException e) { e.printStackTrace(); return null; } finally { if (session != null) { session.getTransaction().commit(); HibernateUtil.closeSession(session); } } } } <file_sep>import sys import tushare as ts df = ts.get_h_data(sys.argv[2], start=sys.argv[4], end=sys.argv[4], autype=sys.argv[3]) path = sys.argv[1] df.to_csv(path, encoding="utf8") <file_sep>var getval = ""; var theComponents = []; var rangeSlider = function () { var slider = $('.range-slider'), range = $('.range-slider__range'), value = $('.range-slider__value'); //value.html(range.value); slider.each(function () { value.each(function () { var value = $(this).prev().attr('value'); $(this).html(); }); range.on('input', function () { $(this).next(value).html(this.value); }); }); }; $(document).ready(function () { if (window.localStorage.getItem("allStock") == null) { $.ajax({ url: "getAllStockNameAndCode.action", dataType: 'json', success: function (data) { var jsonObj = eval('(' + data + ')'); addAllStockToDownList(jsonObj["stockNameAndCode"]); window.localStorage.setItem("allStock", list2str(jsonObj["stockNameAndCode"])); }, error: function () { fail_prompt("ajax error", 1500); } }); } else { addAllStockToDownList(str2list(window.localStorage.getItem("allStock"))); } var thisURL = document.URL; getval = thisURL.split('?')[1]; if (getval != null) { getval = decodeURI(getval); document.getElementById("combineName").value = getval; $("#combineName").attr("disabled", "disabled"); console.log(getval); } }); content = []; window.allStock = ""; function addAllStockToDownList(data) { for (var i = 0; i < data.length; i++) { var row = '' + data[i].split(";")[0] + " " + data[i].split(";")[1]; window.allStock += data[i].split(";")[0] + ";"; content.push(row); } $("#search_ui").select2({ data: content }); $('.select2-selection__rendered').text('添加股票'); } function list2str(list) { var str = ""; for (var i = 0; i < list.length; i++) { str += list[i].split(";")[0] + "," + list[i].split(";")[1] + ";"; } return str; } function str2list(str) { var list = str.split(";"); var newList = []; for (var i = 0; i < list.length; i++) { newList[i] = list[i].split(",")[0] + ";" + list[i].split(",")[1]; } return newList; } function addStockToCombine(stock) { var table = document.getElementById("combineTable"); var rows = table.rows; for (var i = 1; i < rows.length; i++) { //$("#combineTable tr:eq(" + i + ") td:eq(0)").css("background-color", "#000"); //console.log($("#combineTable tr:eq(" + i + ") td:eq(1)").html()); if ($("#combineTable tr:eq(" + i + ") td:eq(1)").html() == stock.split(" ")[0]) { fail_prompt("已存在该股票!", 2000); return; } } var insertTr = document.getElementById("combineTable").insertRow(1); var insertTd = insertTr.insertCell(0); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = stock.split(" ")[1]; var insertTd = insertTr.insertCell(1); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = stock.split(" ")[0]; // var insertTd = insertTr.insertCell(2); // insertTd.className = "mdl-data-table__cell--non-numeric"; // insertTd.innerHTML = "行业"; var insertTd = insertTr.insertCell(2); insertTd.innerHTML = "<div class='range-slider'> <input class='range-slider__range' type='range' value='0' min='0' max='100' onchange='checkOverflow(this)'> <span class='range-slider__value'></span> </div>"; var insertTd = insertTr.insertCell(3); insertTd.innerHTML = "<img src='../css/pic/delete.png' class='deleteButton' width='25' onclick='deleteStock(this)'>"; rangeSlider(); } function deleteStock(cell) { var rowIndex = $(cell).parent().parent().index(); //console.log(rowIndex); var table = document.getElementById("combineTable"); table.deleteRow(rowIndex); } function addCombineStock() { if (getval != null) { var username = getCookie("account"); var table = document.getElementById("combineTable"); $.ajax({ url: 'getCurrentStocks.action', dataType: 'json', type: 'GET', data: { username: username, portfolioName: getval }, success: function (data) { var jsonObj = eval('(' + data + ')'); console.log(jsonObj); for (var i = 0; i < jsonObj.length; i++) { var insertTr = table.insertRow(1); var insertTd = insertTr.insertCell(0); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = getStockName(jsonObj[i]["stock"]); var insertTd = insertTr.insertCell(1); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = jsonObj[i]["stock"]; // var insertTd = insertTr.insertCell(2); // insertTd.className = "mdl-data-table__cell--non-numeric"; // insertTd.innerHTML = "行业"; var position = jsonObj[i]["position"] * 100; console.log("position:" + position); var insertTd = insertTr.insertCell(2); insertTd.innerHTML = "<div class='range-slider'> <input class='range-slider__range' type='range' value='5' min='0' max='100' onchange='checkOverflow(this)'> <span class='range-slider__value'></span> </div>"; var insertTd = insertTr.insertCell(3); insertTd.innerHTML = "<img src='../css/pic/delete.png' class='deleteButton' width='25' onclick='deleteStock(this)'>"; rangeSlider(); } } }); // console.log("11111"); // var content = theComponents[theComponents.length - 1]; // console.log(content); } } function getStockName(code) { var allStock = window.localStorage.getItem("allStock").split(";"); for (var i = 0; i < allStock.length; i++) { if (allStock[i].split(",")[0] == code) return allStock[i].split(",")[1]; } } function initialStocks(components) { theComponents = components; console.log(theComponents); } function checkOverflow(theInput) { var table = document.getElementById("combineTable"); var rows = table.rows; var total = 0; for (var i = 1; i < rows.length; i++) { // $("#combineTable tr:eq(" + i + ")").css("background-color", "#000"); // console.log(parseInt($("#combineTable tr:eq(" + i + ") td:eq(3) .range-slider .range-slider__range").val())); total += parseInt($("#combineTable tr:eq(" + i + ") td:eq(2) .range-slider .range-slider__range").val()); //console.log($('#combineTable td:eq(3) .range-slider .range-slider__range').val()); } // console.log("++++++++++++"); // console.log(total); if (total > 100) { fail_prompt("总仓位不能超过100%!"); var value = $(theInput).prev().attr('value'); $(theInput).html(0); $(theInput).next(value).html(0); theInput.value = '0'; } } function confirmCreateCombine() { if ($("#combineName").val() == "") { fail_prompt("请填写组合名称!", 2000); } else if (document.getElementById("combineTable").rows.length - 1 == 0) { fail_prompt("请选择组合股票!", 2000); } else { if (getval == null) { var username = getCookie("account"); var portfolioName = $('#combineName').val(); var stocks = ""; var positions = ""; console.log(username); console.log(portfolioName); for (var i = 1; i < document.getElementById("combineTable").rows.length; i++) { //console.log($("#combineTable tr:eq(" + i + ") td:eq(1)").html() + $("#combineTable tr:eq(" + i + ") td:eq(3) .range-slider .range-slider__range").val() / 100); stocks += $("#combineTable tr:eq(" + i + ") td:eq(1)").html() + ";"; positions += $("#combineTable tr:eq(" + i + ") td:eq(3) .range-slider .range-slider__range").val() / 100 + ";"; } $.ajax({ url: "addPortfolio.action", dataType: 'json', type: 'POST', data: { username: username, portfolioName: portfolioName, stocks: stocks, positions: positions, }, success: function (data) { var jsonObj = eval('(' + data + ')'); if (jsonObj[0]["info"] == "添加组合成功") { success_prompt("创建成功!", 2000); setTimeout('getBack()', 2000); } else { fail_prompt(jsonObj[0]["info"], 2000); } }, error: function () { fail_prompt("ajax error", 2000); } }); } else { success_prompt("调仓成功!", 2000); setTimeout('getBack()', 2000); } } } function getBack() { self.location = "/jsp/userHomepage.jsp"; }<file_sep>package oquantour.service; import oquantour.po.StockRealTimePO; import oquantour.po.util.ChartInfo; import oquantour.po.util.RelationGraph; import java.sql.Date; import java.util.List; import java.util.Map; /** * 行业相关 * <p> * Created by keenan on 02/06/2017. */ public interface IndustryService { /** * 得到所有行业名称 * * @return */ List<String> getAllIndustriesName(); /** * 得到行业板块间的最小生成树 * * @return 最小生成树 */ RelationGraph getIndustryTree(); /** * 根据行业名,日期区间获得行业内所有股票数据 * * @param industryName 行业名 * @return 行业内股票数据 key: 股票号,value: 股票数据 */ Map<String, StockRealTimePO> getIndustryStocks(String industryName); /** * 获得一段时间的行业收益率 * @param industries 行业名 * @param startDate 开始日期 * @param endDate 结束日期 * @return 行业收益率 */ Map<String, List<ChartInfo>> getAllIndustryReturnRate(List<String> industries, Date startDate, Date endDate); } <file_sep>package bl.tools.utils; import po.PlatePO; import java.util.Date; /** * 用于画基准收益率折线图的类 * <p> * Created by keenan on 26/03/2017. */ public class StdValueInfo extends ValueInfo { public StdValueInfo(Date theDate, double theValue) { date = theDate; value = theValue; } public StdValueInfo(PlatePO platePO) { date = platePO.getDate(); value = platePO.getReturnRate() / 100; } } <file_sep>package oquantour.data.daoImpl; import oquantour.data.dao.PlateDao; import oquantour.data.datagetter.RealTimeInfoGetter; import oquantour.po.PlateRealTimePO; import oquantour.po.PlateinfoPO; import oquantour.po.StockPO; import oquantour.po.util.StockNameInfo; import org.springframework.orm.hibernate5.HibernateTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.sql.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by island on 5/11/17. */ @Transactional(readOnly = false) @Repository public class PlateDaoImpl implements PlateDao{ //使用Spring注入HibernateTemplate的一个实例 private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource(name="hibernateTemplate") public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } /** * 根据板块名称,获得该段时间内存在数据的股票 * @param plateName * @param startDate * @param endDate * @return */ @Override public Map<String, List<StockPO>> getStockInStockPlate(String plateName, Date startDate, Date endDate) { List<String> stockIds = (List<String>) this.getHibernateTemplate().find("select stockId from oquantour.po.StockInfoPO where plate = ?", plateName); // List<StockPO> stockPOS1 = (List<StockPO>) this.getHibernateTemplate() // .find("from oquantour.po.StockInfoPO where = ? and dateValue between ? and ?" // , new Object[]{plateName, startDate, endDate}); Map<String, List<StockPO>> stockMap = new HashMap<>(); for(int i = 0; i < stockIds.size(); i++){ List<StockPO> stockPOS = (List<StockPO>)this.getHibernateTemplate().find("from oquantour.po.StockPO where stockId = ? and dateValue between ? and ?", new Object[]{stockIds.get(i), startDate, endDate}); for(int j = 0; j < stockPOS.size(); j++){ this.getHibernateTemplate().evict(stockPOS.get(j)); } stockMap.put(stockIds.get(i), stockPOS); } /* if(stockPOS.size() > 0) { String stockID = stockPOS.get(0).getStockId(); List<StockPO> stockPOSofStockID = new ArrayList<>(); StockPO stockPO; for (int i = 0; i < stockPOS.size(); i++) { stockPO = stockPOS.get(i); if(stockPO.getStockId().equals(stockID)){ stockPOSofStockID.add(stockPO); } else{ stockMap.put(stockID, stockPOSofStockID); stockPOSofStockID.clear(); stockID = stockPO.getStockId(); stockPOSofStockID.add(stockPO); } } }*/ return stockMap; } /** * 根据股票信息获得它所在的板块 * @param stockInfo 股票名或代码 * @return 板块名 */ @Override public String getStockPlate(String stockInfo) { List<String> plates= (List<String>) this.getHibernateTemplate() .find("select distinct plate from oquantour.po.StockInfoPO where stockId = ? or stockName = ?", new String[]{stockInfo, stockInfo}); if(plates.size() > 0) return plates.get(0); else return ""; } /** * 得到板块中的所有股票 代码;名称 * @param plateName 板块名 * @return 板块中的所有股票的stockID;stockName */ @Override public List<String> getAllStockInfoInPlate(String... plateName) { List<String> stocks = new ArrayList<>(); for(int j = 0; j < plateName.length; j++) { List<StockNameInfo> stockNameInfos = (List<StockNameInfo>) this.getHibernateTemplate() .find("select distinct new oquantour.po.util.StockNameInfo(stockId, stockName) " + "from oquantour.po.StockInfoPO where plate = ?" , plateName[j]); String nameInfo; for (int i = 0; i < stockNameInfos.size(); i++) { nameInfo = stockNameInfos.get(i).getStockID() + ";" + stockNameInfos.get(i).getStockName(); if (!stocks.contains(nameInfo)) { stocks.add(nameInfo); } } } return stocks; } /** * 获得板块一段时间内每个交易日的收益率 * @param plateName * @param startDate * @param endDate * @return */ @Override public List<PlateinfoPO> getPlateInfo(String plateName, Date startDate, Date endDate) { List<PlateinfoPO> plateinfoPOS = (List<PlateinfoPO>) this.getHibernateTemplate().find("from oquantour.po.PlateinfoPO where plateName = ? and dateValue between ? and ?", new Object[]{plateName, startDate, endDate}); for(int i = 0; i < plateinfoPOS.size(); i++){ this.getHibernateTemplate().evict(plateinfoPOS.get(i)); } return plateinfoPOS; } /** * 获得所有板块名称 * @return */ @Override public List<String> getAllPlateName() { List<String> plateName = (List<String>) this.getHibernateTemplate().find("select distinct plate from oquantour.po.StockInfoPO"); return plateName; } /** * 获得实时板块数据 * @return Map<板块名称, PlateRealTimePO></> */ @Override public Map<String, PlateRealTimePO> getRealTimePlateInfo() { List<PlateRealTimePO> plateRealTimePOS = (List<PlateRealTimePO>)this.getHibernateTemplate().find("from oquantour.po.PlateRealTimePO"); Map<String, PlateRealTimePO> map = new HashMap<>(); for(int i = 0; i < plateRealTimePOS.size(); i++){ this.getHibernateTemplate().evict(plateRealTimePOS.get(i)); map.put(plateRealTimePOS.get(i).getPlateName(), plateRealTimePOS.get(i)); } return map; } /** * 更新实时板块数据 */ @Override public void updateRealTimePlateInfo() { RealTimeInfoGetter realTimeInfoGetter = new RealTimeInfoGetter(); Map<String, PlateRealTimePO> map = realTimeInfoGetter.getRealTimePlate(); for(String s: map.keySet()){ this.getHibernateTemplate().saveOrUpdate(map.get(s)); } } /** * 添加板块信息 */ @Override public void addPlateInfo() { List<String> plates = getAllPlateName(); Map<String, List<String>> stocksInPlate = new HashMap<>(); for(int i = 0; i < plates.size(); i++){ List<String> stocks = (List<String>) this.getHibernateTemplate().find("select stockId from oquantour.po.StockInfoPO where plate = ?", plates.get(i)); stocksInPlate.put(plates.get(i), stocks); } // for() // ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(plates.size()); try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = new Date(simpleDateFormat.parse("2005-01-01").getTime()); Date endDate = new Date(simpleDateFormat.parse("2017-12-31").getTime()); System.out.println(startDate); List<Date> dates = (List<Date>) this.getHibernateTemplate().find("select distinct dateValue from oquantour.po.StockPO"); for(int i = 0; i < dates.size(); i++){ System.out.println(dates.get(i)); if(dates.get(i).before(endDate) && dates.get(i).after(startDate)){ for(int j = 0; j < plates.size(); j++) { List<Double> rr = (List<Double>) this.getHibernateTemplate().find("select avg(stockPO.returnRate) from oquantour.po.StockPO stockPO, oquantour.po.StockInfoPO stockInfoPO where stockInfoPO.plate = ? and stockPO.dateValue = ?", new Object[]{plates.get(j), dates.get(i)}); PlateinfoPO plateinfoPO = new PlateinfoPO(); plateinfoPO.setDateValue(dates.get(i)); plateinfoPO.setPlateName(plates.get(j)); plateinfoPO.setReturnRate(rr.get(0)); System.out.println(plates.get(j) + " " + dates.get(i) + " " + rr.get(0)); } } } }catch (ParseException e){ e.printStackTrace(); } } /** * 更新板块信息 * @param plateinfoPO */ @Override public void updatePlateInfo(PlateinfoPO plateinfoPO) { this.getHibernateTemplate().saveOrUpdate(plateinfoPO); } } <file_sep>package exception; /** * Created by keenan on 31/03/2017. */ public class ParameterErrorException extends Exception { public ParameterErrorException() { super(); } public ParameterErrorException(String msg) { super(msg); } } <file_sep>This is a project named Oquantour by Octopus.<file_sep>import sys import tushare as ts df = ts.top_list(sys.argv[2]) path = sys.argv[1] df.to_csv(path, encoding="utf8") <file_sep>package bl.tools.utils; import vo.DailyAverageVO; import java.util.List; /** * 均值回归策略中会使用 * 存放了股票号码 * 均线类型 * 均线的数据 * <p> * Created by keenan on 05/04/2017. */ public class StockMAValue { // 股票号码 private String stockCode; // 均线数据 private List<DailyAverageVO> ma_values; public StockMAValue(String stockCode, List<DailyAverageVO> ma_values) { this.stockCode = stockCode; this.ma_values = ma_values; } public String getStockCode() { return stockCode; } public List<DailyAverageVO> getMa_values() { return ma_values; } } <file_sep>package oquantour.po; import javax.persistence.*; import java.sql.Date; /** * Created by island on 2017/6/12. */ @Entity @IdClass(TopListPOPK.class) public class TopListPO { private String stockId; private String stockName; private Double pchange; private Double amount; private Double buy; private Double bratio; private Double sell; private Double sratio; private String reason; private Date dateValue; @Id @Column(name = "StockID") public String getStockId() { return stockId; } public void setStockId(String stockId) { this.stockId = stockId; } @Basic @Column(name = "StockName") public String getStockName() { return stockName; } public void setStockName(String stockName) { this.stockName = stockName; } @Basic @Column(name = "Pchange") public Double getPchange() { return pchange; } public void setPchange(Double pchange) { this.pchange = pchange; } @Basic @Column(name = "Amount") public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } @Basic @Column(name = "Buy") public Double getBuy() { return buy; } public void setBuy(Double buy) { this.buy = buy; } @Basic @Column(name = "Bratio") public Double getBratio() { return bratio; } public void setBratio(Double bratio) { this.bratio = bratio; } @Basic @Column(name = "Sell") public Double getSell() { return sell; } public void setSell(Double sell) { this.sell = sell; } @Basic @Column(name = "Sratio") public Double getSratio() { return sratio; } public void setSratio(Double sratio) { this.sratio = sratio; } @Id @Column(name = "Reason") public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } @Id @Column(name = "DateValue") public Date getDateValue() { return dateValue; } public void setDateValue(Date dateValue) { this.dateValue = dateValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TopListPO topListPO = (TopListPO) o; if (stockId != null ? !stockId.equals(topListPO.stockId) : topListPO.stockId != null) return false; if (stockName != null ? !stockName.equals(topListPO.stockName) : topListPO.stockName != null) return false; if (pchange != null ? !pchange.equals(topListPO.pchange) : topListPO.pchange != null) return false; if (amount != null ? !amount.equals(topListPO.amount) : topListPO.amount != null) return false; if (buy != null ? !buy.equals(topListPO.buy) : topListPO.buy != null) return false; if (bratio != null ? !bratio.equals(topListPO.bratio) : topListPO.bratio != null) return false; if (sell != null ? !sell.equals(topListPO.sell) : topListPO.sell != null) return false; if (sratio != null ? !sratio.equals(topListPO.sratio) : topListPO.sratio != null) return false; if (reason != null ? !reason.equals(topListPO.reason) : topListPO.reason != null) return false; if (dateValue != null ? !dateValue.equals(topListPO.dateValue) : topListPO.dateValue != null) return false; return true; } @Override public int hashCode() { int result = stockId != null ? stockId.hashCode() : 0; result = 31 * result + (stockName != null ? stockName.hashCode() : 0); result = 31 * result + (pchange != null ? pchange.hashCode() : 0); result = 31 * result + (amount != null ? amount.hashCode() : 0); result = 31 * result + (buy != null ? buy.hashCode() : 0); result = 31 * result + (bratio != null ? bratio.hashCode() : 0); result = 31 * result + (sell != null ? sell.hashCode() : 0); result = 31 * result + (sratio != null ? sratio.hashCode() : 0); result = 31 * result + (reason != null ? reason.hashCode() : 0); result = 31 * result + (dateValue != null ? dateValue.hashCode() : 0); return result; } } <file_sep>package oquantour.util.tools; import oquantour.po.PlateinfoPO; import oquantour.po.StockPO; import java.sql.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 分类器 * Created by keenan on 09/06/2017. */ public class Classifier { public static Map<Date, StockPO> classifyStockByDate(List<StockPO> stockPOS) { Map<Date, StockPO> res = new HashMap<>(); stockPOS.stream().forEach(stockPO -> res.put(stockPO.getDateValue(), stockPO)); return res; } public static Map<Date, PlateinfoPO> classifyPlateByDate(List<PlateinfoPO> plateinfoPOS) { Map<Date, PlateinfoPO> res = new HashMap<>(); plateinfoPOS.stream().forEach(plateinfoPO -> res.put(plateinfoPO.getDateValue(), plateinfoPO)); return res; } } <file_sep>package oquantour.service.serviceImpl; import oquantour.data.dao.IndustryDao; import oquantour.po.StockRealTimePO; import oquantour.po.util.ChartInfo; import oquantour.po.util.Edge; import oquantour.po.util.RelationGraph; import oquantour.service.IndustryService; import oquantour.service.servicehelper.analysis.industry.IndustryRelativity; import oquantour.util.tools.CalendarUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Date; import java.util.*; /** * Created by keenan on 02/06/2017. */ @Service @Transactional public class IndustryServiceImpl implements IndustryService { @Autowired private IndustryDao industryDao; /** * 得到所有行业名称 * * @return */ @Override public List<String> getAllIndustriesName() { return industryDao.getAllIndustries(); } /** * 根据行业名,日期区间获得行业内所有股票数据 * * @param industryName 行业名 * @return 行业内股票数据 key: 股票号,value: 股票数据 */ @Override public Map<String, StockRealTimePO> getIndustryStocks(String industryName) { return industryDao.getStocksInIndustry(industryName); } /** * 得到行业板块间的最小生成树 * * @return 最小生成树 */ @Override @SuppressWarnings("Duplicates") public RelationGraph getIndustryTree() { List<String> list = industryDao.getAllIndustries(); String[] industries = list.toArray(new String[1]); Date today = CalendarUtil.getToday(); Date oneYear = CalendarUtil.getDateOneYearBefore(today); List<List<Double>> rr = new ArrayList<>(); Map<String, List<ChartInfo>> chartInfos = new HashMap<>(); for (String s : industries) { List<ChartInfo> chartInfo = industryDao.getIndustryReturnRate(s, oneYear, today); chartInfos.put(s, chartInfo); List<Double> doubles = new ArrayList<>(); chartInfo.stream().forEachOrdered(chartInfo1 -> doubles.add(chartInfo1.getyAxis())); rr.add(doubles); } PriorityQueue<Edge> edges = new IndustryRelativity(list, rr).getRelativity(); return new RelationGraph(edges, list, chartInfos); } /** * 获得一段时间的行业收益率 * * @param industries 行业名 * @param startDate 开始日期 * @param endDate 结束日期 * @return 行业收益率 */ @Override public Map<String, List<ChartInfo>> getAllIndustryReturnRate(List<String> industries, Date startDate, Date endDate) { Map<String, List<ChartInfo>> info = new HashMap<>(); for (String name : industries) { List<ChartInfo> chartInfos = industryDao.getIndustryReturnRate(name, startDate, endDate); info.put(name, chartInfos); } return info; } } <file_sep>package oquantour.action; import com.opensymphony.xwork2.ActionSupport; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import oquantour.po.StockPO; import oquantour.po.StockRealTimePO; import oquantour.service.OptionalStockService; import oquantour.service.StockService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Pxr on 2017/5/23. */ @Controller public class OptionalStockAction extends ActionSupport { @Autowired private OptionalStockService optionalStockService; @Autowired private StockService stockService; private String account; private String stockCode; private String result; public String addOptionalStock() { String addOptionalStockResult; optionalStockService.addOptionalStock(account, stockCode); addOptionalStockResult = "addSuccess"; Map<String, Object> map = new HashMap<>(); map.put("addOptionalStockInfo", addOptionalStockResult); JSONObject jsonObject = JSONObject.fromObject(map); result = jsonObject.toString(); // addOptionalStockResult = "addSuccess"; // JSONObject jsonObject = new JSONObject(); // jsonObject.put("addOptionalStockResult", addOptionalStockResult); // result = jsonObject.toString(); return SUCCESS; } public String deleteOptionalStock() { String deleteOptionalStockResult; optionalStockService.deleteOptionalStock(account, stockCode); deleteOptionalStockResult = "deleteSuccess"; Map<String, Object> map = new HashMap<>(); map.put("deleteOptionalStockInfo", deleteOptionalStockResult); JSONObject jsonObject = JSONObject.fromObject(map); result = jsonObject.toString(); return SUCCESS; } public String getAllOptionalStock() { System.out.println("ST: "+account); List<String> stockList = optionalStockService.getAllOptionalStock(account); String[] s = stockList.toArray(new String[1]); System.out.println("stockID的size" + s.length); Map<String, StockRealTimePO> map = stockService.getRealTimeStockInfo(s); System.out.println("map的size"+map.size()); JSONArray jsonArray = new JSONArray(); for (Map.Entry<String, StockRealTimePO> entry : map.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("stockID", entry.getKey()); System.out.println("自选股:" + entry.getKey()); jsonObject.put("stockName", entry.getValue().getStockName()); jsonObject.put("stockTrade", entry.getValue().getTrade()); jsonObject.put("stockChange", entry.getValue().getChangepercent()); jsonArray.add(jsonObject); } result = jsonArray.toString(); return SUCCESS; } public void setOptionalStockService(OptionalStockService optionalStockService) { this.optionalStockService = optionalStockService; } public void setAccount(String account) { this.account = account; } public void setStockService(StockService stockService) { this.stockService = stockService; } public void setStockCode(String stockCode) { this.stockCode = stockCode; } public void setResult(String result) { this.result = result; } public String getResult() { return result; } } <file_sep>package ui.compare; import bl.stock.StockBL; import bl.stock.StockBLService; import exception.BothStockNotExistException; import exception.FirstStockNotExistException; import exception.SecondStockNotExistException; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import org.apache.avro.generic.GenericData; import ui.ControlledStage; import ui.StageController; import ui.util.AutoCloseStage; import ui.util.DatePickerSettings; import ui.charts.SingleLineChart; import ui.util.SearchNotificatePane; import vo.SearchVO; import vo.StockCompareVO; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by st on 2017/3/4. */ public class StockCompareViewController implements ControlledStage { private StageController stageController; public void setStageController(StageController stageController) { this.stageController = stageController; } private String resource = "StockCompareView.fxml"; private StockBLService stockBLService; final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @FXML DatePicker startDate; @FXML DatePicker endDate; @FXML TextField stock1; @FXML TextField stock2; @FXML Label stockLabel1; @FXML Label upLabel1; @FXML Label maxLabel1; @FXML Label minLabel1; @FXML Label varianceLabel1; @FXML Label stockLabel2; @FXML Label upLabel2; @FXML Label maxLabel2; @FXML Label minLabel2; @FXML Label varianceLabel2; @FXML Pane closeValuePane; @FXML Pane logReturnPane; @FXML Pane searchPane; @FXML Button confirmButton; @FXML private Pane searchNotificationPane1; @FXML private ScrollPane searchScrollPane1; @FXML private Label nullLabel1; @FXML private Pane searchNotificationPane2; @FXML private ScrollPane searchScrollPane2; @FXML private Label nullLabel2; /** * 初始化方法 * 初始化日期选择器,设定初始值及选择范围 */ public void initial(SearchVO searchVO) { ZoneId zone = ZoneId.systemDefault(); DatePickerSettings datePickerSettings = new DatePickerSettings(); startDate.setDayCellFactory(datePickerSettings.getStartSettings(startDate)); endDate.setDayCellFactory(datePickerSettings.getEndSettings(startDate, endDate)); startDate.setValue(searchVO.startDate.toInstant().atZone(zone).toLocalDate()); endDate.setValue(searchVO.endDate.toInstant().atZone(zone).toLocalDate()); stock1.setText(searchVO.stock1); stock2.setText(searchVO.stock2); // 键盘监听,回车键发起搜索 searchPane.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { searchInfo(); } }); updateInfo(searchVO); SearchNotificatePane searchNotificatePane1 = new SearchNotificatePane(stock1, searchNotificationPane1, nullLabel1, searchScrollPane1); searchNotificatePane1.setTextField(120, 25, 75); SearchNotificatePane searchNotificatePane2 = new SearchNotificatePane(stock2, searchNotificationPane2, nullLabel2, searchScrollPane2); searchNotificatePane2.setTextField(120, 25, 75); } /** * 搜索按钮响应方法,把开始日期、结束日期及两只股票打包成searchVO后进行搜索 */ @FXML private void searchInfo() { if (stock1.getText().equals(stock2.getText())) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入两只不同股票"); } else if (stock1.getText().equals("") || stock2.getText().equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入股票代码或名称"); } else { SearchVO searchVO = wrapSearchInfo(); updateInfo(searchVO); } searchScrollPane1.setVisible(false); searchScrollPane2.setVisible(false); } /** * 更新信息方法,根据搜索条件,显示股票数据和图表 * * @param searchVO */ private void updateInfo(SearchVO searchVO) { stockBLService = new StockBL(); // System.out.println("start: "+System.currentTimeMillis()); try { List<StockCompareVO> stockCompareVOS = stockBLService.compareStock(searchVO); // System.out.println("pxr: "+System.currentTimeMillis()); // System.out.println("line133: "+stockCompareVOS.size()); stockLabel1.setText(stockCompareVOS.get(0).stockName); stockLabel2.setText(stockCompareVOS.get(1).stockName); double upPercent1 = stockCompareVOS.get(0).chg; double upPercent2 = stockCompareVOS.get(1).chg; DecimalFormat decimalFormat1 = new DecimalFormat("#.##%"); DecimalFormat decimalFormat2 = new DecimalFormat("#.#####E0"); upLabel1.setText(decimalFormat1.format(upPercent1)); upLabel2.setText(decimalFormat1.format(upPercent2)); setLabelStyle(upLabel1, upPercent1); setLabelStyle(upLabel2, upPercent2); // 获得两只股票的最大值、最小值和对数收益率方差 maxLabel1.setText(String.valueOf(stockCompareVOS.get(0).high)); minLabel1.setText(String.valueOf(stockCompareVOS.get(0).low)); maxLabel2.setText(String.valueOf(stockCompareVOS.get(1).high)); minLabel2.setText(String.valueOf(stockCompareVOS.get(1).low)); varianceLabel1.setText(decimalFormat2.format(stockCompareVOS.get(0).logReturnVariance)); varianceLabel2.setText(decimalFormat2.format(stockCompareVOS.get(1).logReturnVariance)); // // 获得每天涨跌幅 // List<Double> chg1 = stockCompareVOS.get(0).chg; // List<Double> chg2 = stockCompareVOS.get(1).chg; // 获得每天收盘价 List<Double> closeValues1 = new ArrayList<>(); List<Double> closeValues2 = new ArrayList<>(); // 获得每天对数收益率 List<Double> logReturn1 = new ArrayList<>(); List<Double> logReturn2 = new ArrayList<>(); // 获得日期 List<Date> dateList1 = stockCompareVOS.get(0).dateList; List<Date> dateList2 = stockCompareVOS.get(1).dateList; List<Date> dateList = new ArrayList<>(); //处理数据,获得两只股票日期与数据的交集 int i = 0; int j = 0; while(i < dateList1.size() && j < dateList2.size() ){ if(dateList1.get(i).equals(dateList2.get(j))){ dateList.add(dateList1.get(i)); closeValues1.add(stockCompareVOS.get(0).closeList.get(i)); closeValues2.add(stockCompareVOS.get(1).closeList.get(j)); logReturn1.add(stockCompareVOS.get(0).logReturnList.get(i)); logReturn2.add(stockCompareVOS.get(1).logReturnList.get(j)); i++; j++; } else if(dateList1.get(i).after(dateList2.get(j))){ j++; } else if(dateList2.get(j).after(dateList1.get(i))){ i++; } } System.out.print(dateList.size()); // System.out.println("line163: valueSize "+closeValues1.size()); // System.out.println("line164: dateSize "+dateList.size()); String stockName1 = stockCompareVOS.get(0).stockName; String stockName2 = stockCompareVOS.get(1).stockName; // List<Double> closeList1 = new ArrayList<>(); // List<Double> logReturnList1 = new ArrayList<>(); // List<Date> dateList1 = new ArrayList<>(); // for (CompareDataVO compareDataVO : stockCompareVOS.get(0).compareDataVOS) { // closeList1.add(compareDataVO.close); // logReturnList1.add(compareDataVO.logReturn); // dateList1.add(compareDataVO.date); // } // // List<Double> closeList2 = new ArrayList<>(); // List<Double> logReturnList2 = new ArrayList<>(); // List<Date> dateList2 = new ArrayList<>(); // for (CompareDataVO compareDataVO : stockCompareVOS.get(1).compareDataVOS) { // closeList2.add(compareDataVO.close); // logReturnList2.add(compareDataVO.logReturn); // dateList2.add(compareDataVO.date); // } Platform.runLater(new Runnable() { @Override public void run() { closeValuePane.getChildren().clear(); closeValuePane.getChildren().add(new SingleLineChart(closeValues1, closeValues2, dateList, dateList, stockName1, stockName2, "每日收盘价")); logReturnPane.getChildren().clear(); logReturnPane.getChildren().add(new SingleLineChart(logReturn1, logReturn2, dateList, dateList, stockName1, stockName2, "对数收益率")); } }); // System.out.println("st: "+System.currentTimeMillis()); } catch (BothStockNotExistException b) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("找不到数据"); } catch (FirstStockNotExistException f) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("找不到\n第一只股票的数据"); } catch (SecondStockNotExistException s) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("找不到\n第二只股票的数据"); } } /** * 获得用户输入的搜索信息,并打包成SearchVO * * @return */ private SearchVO wrapSearchInfo() { DatePickerSettings datePickerSettings = new DatePickerSettings(); SearchVO searchVO = new SearchVO(stock1.getText(), stock2.getText(), datePickerSettings.getDate(startDate), datePickerSettings.getDate(endDate)); return searchVO; } /** * 根据涨跌幅设置数字颜色,红色表示涨,绿色表示跌 * * @param label * @param value */ private void setLabelStyle(Label label, double value) { String text = label.getText(); // System.out.println(text); if (value > 0) { label.setStyle("-fx-text-fill: #d97555"); // label.setText(text + " ∧"); } else if (value < 0) { label.setStyle("-fx-text-fill: #4c9b8e"); // label.setText(text + " ∨"); // label.setText(text + " ∧"); } else { label.setStyle("-fx-text-fill: white"); } } /** * 开始时间选择器监听,选择开始时间后,结束时间默认为开始时间的后两个月 */ @FXML private void changeEndDate() { ZoneId zone = ZoneId.systemDefault(); try { if (startDate.getValue().plusMonths(2). isAfter(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate())) { // 若开始时间的两个月后在2014/12/31之后,则设置结束时间为2014/12/31 endDate.setValue(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate()); } else { endDate.setValue(startDate.getValue().plusMonths(2)); } } catch (ParseException e) { e.printStackTrace(); } } /** * 按钮响应设置 */ @FXML private void turnRed() { confirmButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1"); } @FXML private void turnWhite() { confirmButton.setStyle("-fx-text-fill: #689cc4; -fx-background-color: transparent; -fx-border-color: #689cc4; -fx-border-width: 1"); } } <file_sep>package oquantour; import junit.framework.TestCase; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * 所有的测试类都要继承该类 * <p> * 测试类写法 * * @Autowired private MemberDao memberDao; * @Test public void testAdd() { * Member member = new Member(); * member.setId(1234567); * member.setUsername("123"); * member.setPassword("123"); * memberDao.addMember(member); * } * <p> * Created by keenan on 11/05/2017. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:applicationContext.xml"}) public class BaseTest extends TestCase { } <file_sep>package oquantour.po; /** * Created by island on 5/21/17. */ public class PersonalStrategyPO { } <file_sep>package bl.strategy; import exception.FormativePeriodNotExistException; import exception.ParameterErrorException; import exception.SelectStocksException; import exception.WinnerSelectErrorException; import vo.*; import java.util.List; /** * 供界面调用的接口类 * Created by st on 2017/3/27. */ public interface BackTestingBLService { /** * 得到回测结果 * * @return 回测结果 */ List<BackTestingSingleChartVO> getBackTestResult() throws ParameterErrorException, WinnerSelectErrorException; /** * 得到回测统计数据 * * @return 回测统计数据 */ StrategyStatisticsVO getBackTestStatistics(); /** * 判断能否回测 * * @return 能否回测的结果 */ BackTestingJudgeVO canBackTest() throws SelectStocksException, FormativePeriodNotExistException; /** * 设置回测信息 * * @param backTestingInfoVO */ void setBackTestingInfo(BackTestingInfoVO backTestingInfoVO); /** * 获得收益率分布直方图的数据(由界面按需自己处理) * * @return 收益率分布数据 */ List<Double> getReturnRateDistribution(); /** * 获得每个调仓日赢家组合的信息 * * @return 赢家组合的信息 */ List<WinnerInfoVO> getWinnersInfo(); } <file_sep>package vo; import po.Stock; import java.util.Date; import java.util.List; /** * 市场温度计 * <p> * 内容包括但不限于: * 当日总交易量 * 涨停股票数 * 跌停股票数 * 涨幅超过5%的股票数 * 跌幅超过5%的股票数 * 开盘-收盘大于5%*上一个交易日收盘价的股票个数 * 开盘-收盘小于-5%*上一个交易日收盘价的股票个数 * <p> * Created by Pxr on 2017/3/3. */ public class MarketTemperatureVO { //总交易量 public long totalVolume; //涨停股票数 public List<StockVO> limitUpStock; //跌停股票数 public List<StockVO> limitDownStock; //涨幅超过5%的股票数 public List<StockVO> up5perStock; //跌幅超过5%的股票数 public List<StockVO> down5perStock; //当日大涨股 public List<StockVO> openUp5perStock; //当日大跌股 public List<StockVO> openDown5perStock; //当日总股票数 public int totalNum; //涨幅榜 public List<StockVO> upList; //跌幅榜 public List<StockVO> downList; public Date date; public MarketTemperatureVO(long totalVolume, List<StockVO> limitUpStock, List<StockVO> limitDownStock, List<StockVO> up5perStock, List<StockVO> down5perStock, List<StockVO> openUp5perStock, List<StockVO> openDown5perStock, int totalNum, List<StockVO> upList, List<StockVO> downList) { this.totalVolume = totalVolume; this.limitUpStock = limitUpStock; this.limitDownStock = limitDownStock; this.up5perStock = up5perStock; this.down5perStock = down5perStock; this.openUp5perStock = openUp5perStock; this.openDown5perStock = openDown5perStock; this.totalNum = totalNum; this.upList = upList; this.downList = downList; } } <file_sep>$(document).ready(function () { $.ajax({ url: "getTopListInfo.action", dataType: 'json', type: 'GET', success: function (data) { var jsonObj = eval('(' + data + ')'); $("#date").html(jsonObj[0]["date"]); initialTopList(jsonObj); } }) }); function goToStockInfo(stockID) { console.log(stockID) window.open("../jsp/stockInfo.jsp?stockName=" + stockID); } function initialTopList(data) { for (var i = 0; i < 12; i++) { var table = document.getElementById("topRankTable"); var insertTr = table.insertRow(i + 1); insertTr.id = "stockInfo"; var insertTd = insertTr.insertCell(0); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = "<span style='cursor: pointer' onclick='goToStockInfo(this.innerHTML)'>" + data[i]["stockID"] + "</span>"; var insertTd = insertTr.insertCell(1); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = data[i]["stockName"]; var chg = data[i]["pchange"]; var insertTd = insertTr.insertCell(2); insertTd.className = "mdl-data-table__cell--non-numeric"; if (chg > 0) { insertTd.innerHTML = "+" + data[i]["pchange"].toFixed(2) + "%"; insertTd.style.color = "#cd8585" } else { insertTd.innerHTML = data[i]["pchange"].toFixed(2) + "%"; insertTd.style.color = "#74a57e" } // var insertTd = insertTr.insertCell(3); // insertTd.className = "mdl-data-table__cell--non-numeric"; // insertTd.innerHTML = data[i]["amount"]; // var insertTd = insertTr.insertCell(4); // insertTd.className = "mdl-data-table__cell--non-numeric"; // insertTd.innerHTML = data[i]["buy"]; var insertTd = insertTr.insertCell(3); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = (data[i]["bratio"] * 100).toFixed(1) + "%"; // var insertTd = insertTr.insertCell(6); // insertTd.className = "mdl-data-table__cell--non-numeric"; // insertTd.innerHTML = data[i]["sell"]; var insertTd = insertTr.insertCell(4); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = (data[i]["sratio"] * 100).toFixed(1) + "%"; var insertTd = insertTr.insertCell(5); insertTd.className = "mdl-data-table__cell--non-numeric"; insertTd.innerHTML = data[i]["reason"]; } }<file_sep>package oquantour.service; import oquantour.po.StockPO; import java.util.List; /** * 自选股相关 * Created by keenan on 16/05/2017. */ public interface OptionalStockService { /** * 增加自选股 * * @param account 用户账户 * @param stockID 股票代码 */ void addOptionalStock(String account, String stockID); /** * 删除自选股 * * @param account 用户账户 * @param stockID 股票代码 */ void deleteOptionalStock(String account, String stockID); /** * 判断股票是否已在自选股中 * * @param account 用户账户 * @param stockID 股票代码 * @return 是否已在自选股中 */ boolean isInOptionalStock(String account, String stockID); /** * 获得某用户所有自选股 * * @param account 用户账户 * @return 用户所有自选股 */ List<String> getAllOptionalStock(String account); } <file_sep>package bl.strategy; import bl.strategy.backtest.MeanReversion; import bl.strategy.backtest.Momentum; import bl.strategy.backtest.Strategy; import exception.FormativePeriodNotExistException; import exception.ParameterErrorException; import exception.SelectStocksException; import exception.WinnerSelectErrorException; import vo.*; import java.util.List; /** * Created by st on 2017/3/27. * <p> * Modified by keenan on 2017/4/4 */ public class BackTestingBLServiceImpl implements BackTestingBLService { private Strategy strategy; private BackTestingInfoVO backTestingInfoVO; private static BackTestingBLService backTestingBLService; private BackTestingBLServiceImpl() { } public static BackTestingBLService getInstance() { if (backTestingBLService == null) { backTestingBLService = new BackTestingBLServiceImpl(); } return backTestingBLService; } /** * 根据界面选择的策略类型,返回回测结果 * * @return */ @Override public List<BackTestingSingleChartVO> getBackTestResult() throws ParameterErrorException, WinnerSelectErrorException { return strategy.getBackTestResult(); } /** * 根据界面传入的策略类型,返回回测统计数据 * * @return */ @Override public StrategyStatisticsVO getBackTestStatistics() { return strategy.getBackTestStatistics(); } /** * 判断能否回测 * * @return 能否回测的结果 */ @Override public BackTestingJudgeVO canBackTest() throws SelectStocksException, FormativePeriodNotExistException { return strategy.canBackTest(); } /** * 设置回测信息 * * @param backTestingInfoVO */ @Override public void setBackTestingInfo(BackTestingInfoVO backTestingInfoVO) { this.backTestingInfoVO = backTestingInfoVO; switch (backTestingInfoVO.strategyType) { case MOMENTUM: strategy = new Momentum(backTestingInfoVO); break; case MEANREVERSION: strategy = new MeanReversion(backTestingInfoVO); break; } } /** * 获得收益率分布直方图的数据(由界面按需自己处理) * * @return 收益率分布数据 */ @Override public List<Double> getReturnRateDistribution() { return strategy.getReturnRateDistribution(); } /** * 获得每个调仓日赢家组合的信息 * * @return 赢家组合的信息 */ @Override public List<WinnerInfoVO> getWinnersInfo() { return strategy.getWinnerInfo(); } } <file_sep>package oquantour.po.util; import java.util.List; /** * Created by keenan on 08/05/2017. */ public class BackTestResult { // 基准收益率和策略收益率对比 private List<BackTestingSingleChartInfo> backTestingSingleChartInfos; // 回测统计数据 private BackTestStatistics backTestStatistics; // 每个调仓日的持仓股票详情 private List<BackTestWinner> dailyWinners; // 收益率分布 private List<Double> returnRateDistribution; // 策略评分 private double score; // 风险指标 private double[] indices; // 最佳持有期结果 private List<BackTestBestInfo> bestHolding; // 最佳持仓数结果 private List<BackTestBestInfo> bestHoldingNum; public BackTestResult() { } public BackTestResult(List<BackTestingSingleChartInfo> backTestingSingleChartInfos, BackTestStatistics backTestStatistics, List<BackTestWinner> dailyWinners, List<Double> returnRateDistribution, double score, double[] indices) { this.backTestingSingleChartInfos = backTestingSingleChartInfos; this.backTestStatistics = backTestStatistics; this.dailyWinners = dailyWinners; this.returnRateDistribution = returnRateDistribution; this.score = score; this.indices = indices; } public List<BackTestingSingleChartInfo> getBackTestingSingleChartInfos() { return backTestingSingleChartInfos; } public void setBackTestingSingleChartInfos(List<BackTestingSingleChartInfo> backTestingSingleChartInfos) { this.backTestingSingleChartInfos = backTestingSingleChartInfos; } public BackTestStatistics getBackTestStatistics() { return backTestStatistics; } public void setBackTestStatistics(BackTestStatistics backTestStatistics) { this.backTestStatistics = backTestStatistics; } public List<BackTestWinner> getDailyWinners() { return dailyWinners; } public void setDailyWinners(List<BackTestWinner> dailyWinners) { this.dailyWinners = dailyWinners; } public List<Double> getReturnRateDistribution() { return returnRateDistribution; } public void setReturnRateDistribution(List<Double> returnRateDistribution) { this.returnRateDistribution = returnRateDistribution; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public double[] getIndices() { return indices; } public void setIndices(double[] indices) { this.indices = indices; } // private List<Double> calReturnRateDistribution(List<BackTestingSingleChartInfo> backTestingSingleChartInfos, int holding) { // List<Double> returnRateDistribution = new ArrayList<>(); // //循环计算每个持有期的收益率 // int offset = 0; // for (; offset + holding <= backTestingSingleChartInfos.size(); offset += holding) { // double startValue = backTestingSingleChartInfos.get(offset).getBackTestValue(); // double endValue = backTestingSingleChartInfos.get(offset + holding - 1).getBackTestValue(); // returnRateDistribution.add((endValue - startValue) / (1 + startValue)); // } // // if (offset != backTestingSingleChartInfos.size() && offset + holding > backTestingSingleChartInfos.size()) { // double startValue = backTestingSingleChartInfos.get(offset).getBackTestValue(); // double endValue = backTestingSingleChartInfos.get(backTestingSingleChartInfos.size() - 1).getBackTestValue(); // // returnRateDistribution.add((endValue - startValue) / (1 + startValue)); // } // return returnRateDistribution; // } public List<BackTestBestInfo> getBestHolding() { return bestHolding; } public void setBestHolding(List<BackTestBestInfo> bestHolding) { this.bestHolding = bestHolding; } public List<BackTestBestInfo> getBestHoldingNum() { return bestHoldingNum; } public void setBestHoldingNum(List<BackTestBestInfo> bestHoldingNum) { this.bestHoldingNum = bestHoldingNum; } } <file_sep>package exception; /** * Created by Pxr on 2017/3/15. */ public class BothStockNotExistException extends Exception { public BothStockNotExistException() { super(); } public BothStockNotExistException(String msg) { super(msg); } } <file_sep>package oquantour.service.servicehelper.analysis.stock.indices; import oquantour.po.StockPO; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by keenan on 07/06/2017. */ public class BOLLAnalysis { private static final String shortBuy = "短线买入", longBuy = "中长线买入", shortSell = "短线卖出", longSell = "中线卖出"; public static List<Map<Date, String>> getSignal(List<StockPO> data) { Map<Date, String> map_buy = new HashMap<>(); Map<Date, String> map_sell = new HashMap<>(); for (int i = 1; i < data.size(); i++) { StockPO pre = data.get(i - 1); StockPO cur = data.get(i); if (pre.getMb() == -1 || pre.getUp() == -1 || pre.getDn() == -1) { continue; } //当美国线从布林线的中轨线以下、向上突破布林线中轨线时,预示着股价的强势特征开始出现,股价将上涨,投资者应以中长线买入股票为主。 if (pre.getHighPrice() < pre.getMb() && cur.getHighPrice() >= cur.getMb()) { map_buy.put(cur.getDateValue(), longBuy); } else if (pre.getLowPrice() > pre.getMb() && pre.getHighPrice() < pre.getUp() && cur.getHighPrice() >= cur.getUp()) {//当美国线从布林线的中轨线以上、向上突破布林线上轨时,预示着股价的强势特征已经确立,股价将可能短线大涨,投资者应以持股待涨或短线买入为主。 map_buy.put(cur.getDateValue(), shortBuy); } else if (pre.getHighPrice() < pre.getDn() && cur.getHighPrice() >= cur.getDn()) {//当美国线从布林线下轨下方、向上突破布林线下轨时,预示着股价的短期行情可能回暖,投资者可以及时适量买进股票,作短线反弹行情。 map_buy.put(cur.getDateValue(), shortBuy); } else if (pre.getHighPrice() > pre.getUp() && cur.getHighPrice() <= cur.getUp()) {//当美国线在布林线上方向上运动了一段时间后,如果美国线的运动方向开始掉头向下,投资者应格外小心,一旦美国线掉头向下并突破布林线上轨时,预示着股价短期的强势行情可能结束,股价短期内将大跌,投资者应及时短线卖出股票、离场观望。 map_sell.put(cur.getDateValue(), shortSell); } else if (pre.getLowPrice() > pre.getMb() && cur.getLowPrice() <= cur.getMb()) { //当美国线从布林线中轨上方、向下突破布林线的中轨时,预示着股价前期的强势行情已经结束,股价的中期下跌趋势已经形成,投资者应中线及时卖出股票。 map_sell.put(cur.getDateValue(), longSell); } } List<Map<Date, String>> maps = new ArrayList<>(); maps.add(map_buy); maps.add(map_sell); return maps; } } <file_sep>package oquantour.po; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; /** * Created by island on 2017/6/6. */ @Entity public class PlateRealTimePO { //指数代码 private String plateId; //指数名称 private String plateName; //涨跌幅 private double change; //开盘点位 private double openPrice; //昨日收盘点位 private double preclosePrice; //收盘点位 private double closePrice; //最高点位 private double highPrice; //最低点位 private double lowPrice; //成交量手(手) private double volume; //成交金额(亿元) private double amount; @Id @Column(name = "PlateName") public String getPlateName() { return plateName; } public void setPlateName(String plateName) { this.plateName = plateName; } @Basic @Column(name = "ChangeRate") public double getChange() { return change; } public void setChange(double change) { this.change = change; } @Basic @Column(name = "OpenPrice") public double getOpenPrice() { return openPrice; } public void setOpenPrice(double openPrice) { this.openPrice = openPrice; } @Basic @Column(name = "PreclosePrice") public double getPreclosePrice() { return preclosePrice; } public void setPreclosePrice(double preclosePrice) { this.preclosePrice = preclosePrice; } @Basic @Column(name = "ClosePrice") public double getClosePrice() { return closePrice; } public void setClosePrice(double closePrice) { this.closePrice = closePrice; } @Basic @Column(name = "HighPrice") public double getHighPrice() { return highPrice; } public void setHighPrice(double highPrice) { this.highPrice = highPrice; } @Basic @Column(name = "LowPrice") public double getLowPrice() { return lowPrice; } public void setLowPrice(double lowPrice) { this.lowPrice = lowPrice; } @Basic @Column(name = "Volume") public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } @Basic @Column(name = "Amount") public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } @Basic @Column(name = "PlateID") public String getPlateId() { return plateId; } public void setPlateId(String plateId) { this.plateId = plateId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PlateRealTimePO that = (PlateRealTimePO) o; if (Double.compare(that.openPrice, openPrice) != 0) return false; if (Double.compare(that.preclosePrice, preclosePrice) != 0) return false; if (Double.compare(that.closePrice, closePrice) != 0) return false; if (Double.compare(that.highPrice, highPrice) != 0) return false; if (Double.compare(that.lowPrice, lowPrice) != 0) return false; if (Double.compare(that.volume, volume) != 0) return false; if (Double.compare(that.amount, amount) != 0) return false; if (plateName != null ? !plateName.equals(that.plateName) : that.plateName != null) return false; if (plateId != null ? !plateId.equals(that.plateId) : that.plateId != null) return false; return true; } @Override public int hashCode() { int result; long temp; result = plateName != null ? plateName.hashCode() : 0; result = 31 * result + (plateId != null ? plateId.hashCode() : 0); temp = Double.doubleToLongBits(openPrice); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(preclosePrice); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(closePrice); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(highPrice); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(lowPrice); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(volume); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(amount); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } } <file_sep>package ui.util; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Modality; import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.IOException; /** * 自动关闭的窗口 * <p> * Created by keenan on 10/03/2017. */ public class AutoCloseStage { /** * 静态方法 * <p> * 显示自动关闭的窗口 * * @param text 错误原因 */ public void showErrorBox(String text) { Stage popup = new Stage(); popup.setAlwaysOnTop(true); //stage背景透明 popup.initModality(Modality.APPLICATION_MODAL); popup.initStyle(StageStyle.TRANSPARENT); //去除stage外框 popup.initStyle(StageStyle.UNDECORATED); //无法改变stage窗口 popup.setResizable(false); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("ErrorBoxView.fxml")); Pane pane = (Pane) loader.load(); Scene scene = new Scene(pane); popup.setScene(scene); Screen screen = Screen.getPrimary(); Rectangle2D bounds = screen.getVisualBounds(); double width = pane.getPrefWidth(); double height = pane.getPrefHeight(); popup.setX((bounds.getWidth() - width) / 2); popup.setY((bounds.getHeight() - height) / 2); popup.show(); ErrorBoxController errorBoxController = (ErrorBoxController) loader.getController(); errorBoxController.setLabel(text); }catch (IOException e){ e.printStackTrace(); } Thread thread = new Thread(() -> { try { Thread.sleep(2000); if (popup.isShowing()) { Platform.runLater(() -> popup.close()); } } catch (Exception exp) { exp.printStackTrace(); } }); thread.setDaemon(true); thread.start(); } } <file_sep>package oquantour.action; import com.opensymphony.xwork2.ActionSupport; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import oquantour.exception.BackTestErrorException; import oquantour.po.StockPO; import oquantour.po.util.*; import oquantour.service.BackTestService; import oquantour.service.StockService; import oquantour.util.tools.BasicIndices; import oquantour.util.tools.PriceIndices; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import static oquantour.po.util.StrategyType.*; /** * Created by Pxr on 2017/5/16. */ @Controller public class BackTestAction extends ActionSupport { // 回测开始日期 private String startDate; // 回测结束日期 private String endDate; // 要回测的多只股票代码 private String stocks; // 形成期 private int formativePeriod; // 持有期 private int holdingPeriod; // 几日均线 private int ma_length; // 策略类型 private String strategyType; // 最大持仓股票数目 private int maxholdingStocks; // 过滤ST股票 private boolean filter_ST; // 过滤无数据股票 private boolean filter_NoData; // 过滤停牌股票 private boolean filter_Suspension; @Autowired private StockService stockService; //回测种类flag,flag=0表示为经典策略,flag=1表示为DIY策略 private int flag; //表示是否是区间选股,若是区间选股则值为1,若是权重选股值为0 private int isRangeActive; // 是否忽略100只约束 private boolean ignore_100; @Autowired private BackTestService backTestService; private String info; private String result; private String indexName; private String indexVal; public void setStockService(StockService stockService) { this.stockService = stockService; } public void setFlag(int flag) { this.flag = flag; } public String getResult() { return result; } public void setStartDate(String startDate) { this.startDate = startDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public void setStocks(String stocks) { this.stocks = stocks; } public void setFormativePeriod(int formativePeriod) { this.formativePeriod = formativePeriod; } public void setHoldingPeriod(int holdingPeriod) { this.holdingPeriod = holdingPeriod; } public void setMa_length(int ma_length) { this.ma_length = ma_length; } public void setStrategyType(String strategyType) { this.strategyType = strategyType; } public void setMaxholdingStocks(int maxholdingStocks) { this.maxholdingStocks = maxholdingStocks; } public void setFilter_ST(boolean filter_ST) { this.filter_ST = filter_ST; } public void setFilter_NoData(boolean filter_NoData) { this.filter_NoData = filter_NoData; } public void setFilter_Suspension(boolean filter_Suspension) { this.filter_Suspension = filter_Suspension; } public void setIgnore_100(boolean ignore_100) { this.ignore_100 = ignore_100; } public void setBackTestService(BackTestService backTestService) { this.backTestService = backTestService; } public void setIndexVal(String indexVal) { this.indexVal = indexVal; } public void setIndexName(String indexName) { this.indexName = indexName; } public void setIsRangeActive(int isRangeActive) { this.isRangeActive = isRangeActive; } public void setInfo(String info) { this.info = info; } public void setResult(String result) { this.result = result; } public String backTest() { JSONArray jsonArray = new JSONArray(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { BackTestInfo backTestInfo = generateBackTestInfo(); BackTestResult backTestResult = backTestService.getBackTestResult(backTestInfo); info = "回测成功"; JSONObject resultJson = new JSONObject(); resultJson.put("info", info); jsonArray.add(resultJson); for (BackTestingSingleChartInfo backTestingSingleChartInfo : backTestResult.getBackTestingSingleChartInfos()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("date", simpleDateFormat.format(backTestingSingleChartInfo.getDate())); jsonObject.put("backTestValue", String.format("%.3f", backTestingSingleChartInfo.getBackTestValue() * 100)); jsonObject.put("stdValue", String.format("%.3f", backTestingSingleChartInfo.getStdValue() * 100)); jsonArray.add(jsonObject); } JSONObject statisticJson = new JSONObject(); statisticJson.put("backTestStatistics", backTestResult.getBackTestStatistics()); jsonArray.add(statisticJson); JSONObject returnRateJson = new JSONObject(); returnRateJson.put("returnRateDistribution", backTestResult.getReturnRateDistribution()); jsonArray.add(returnRateJson); List<BackTestWinner> dailyWinner = backTestResult.getDailyWinners(); for (BackTestWinner backTestWinner : dailyWinner) { Map<StockPO, Integer> shares = backTestWinner.getShares(); for (Map.Entry<StockPO, Integer> entry : shares.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("winnerDate", simpleDateFormat.format(backTestWinner.getDate())); // jsonObject.put("stockName", stockService.getStockName(entry.getKey().getStockId())); jsonObject.put("stockCode", entry.getKey().getStockId()); jsonObject.put("stockClose", String.format("%.2f", entry.getKey().getClosePrice())); jsonObject.put("stockOpen", String.format("%.2f", entry.getKey().getOpenPrice())); jsonObject.put("stockHigh", String.format("%.2f", entry.getKey().getHighPrice())); jsonObject.put("stockLow", String.format("%.2f", entry.getKey().getLowPrice())); jsonObject.put("stockAdjClose", String.format("%.2f", entry.getKey().getAdjClose())); // jsonObject.put("stockChg", String.format("%.2f", entry.getKey().getChg()*100)); jsonObject.put("share", entry.getValue()); jsonArray.add(jsonObject); } // jsonObject.put("shares", backTestWinner.getShares()); } List<BackTestBestInfo> backTestBestInfos = backTestResult.getBestHolding(); double[] doubles = backTestResult.getIndices(); JSONObject jsonObject = new JSONObject(); jsonObject.put("抗风险能力", doubles[0]); jsonObject.put("稳定性", doubles[1]); jsonObject.put("盈利能力", doubles[2]); jsonObject.put("持股分散度", doubles[3]); jsonObject.put("评分", backTestResult.getScore()); jsonObject.put("最佳持有期", backTestBestInfos); List<BackTestBestInfo> list = backTestResult.getBestHoldingNum(); if (!list.isEmpty()) { jsonObject.put("最佳持仓数", list); } jsonArray.add(jsonObject); result = jsonArray.toString(); } catch (BackTestErrorException e) { info = e.getMessage(); JSONObject jsonObject = new JSONObject(); jsonObject.put("info", info); jsonArray.add(jsonObject); result = jsonArray.toString(); } return SUCCESS; } private BackTestInfo generateBackTestInfo() { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); java.sql.Date startDate_sql = new java.sql.Date(simpleDateFormat.parse(startDate).getTime()); java.sql.Date endDate_sql = new java.sql.Date(simpleDateFormat.parse(endDate).getTime()); String[] s = stocks.split(";"); List<String> stocksList = new ArrayList<>(); for (int i = 0; i < s.length; i++) { stocksList.add(s[i]); } if (flag == 0) { StrategyType strategy = null; switch (strategyType) { case "动量策略": strategy = Momentum; break; case "均值回归": strategy = MeanReversion; break; case "小市值轮动策略": strategy = SmallMarketValueWheeled; break; default: break; } return new BackTestInfo(startDate_sql, endDate_sql, stocksList, formativePeriod, holdingPeriod, ma_length, strategy, maxholdingStocks, filter_ST, filter_NoData, filter_Suspension, ignore_100); } else if (flag == 1) { StrategyType strategyType = DIY; if (isRangeActive == 1) { //是区间选股 Map<PriceIndices, double[]> map = new HashMap<>(); String[] indexName_array = indexName.split(";"); double[] indexVal_array = Arrays.stream(indexVal.split(";")).mapToDouble(Double::parseDouble).toArray(); for (int i = 0; i < indexName_array.length; i++) { double[] value = new double[2]; value[0] = indexVal_array[i]; value[1] = indexVal_array[i + 1]; map.put(PriceIndices.getIndex(indexName_array[i]), value); } return new BackTestInfo(startDate_sql, endDate_sql, stocksList, holdingPeriod, strategyType, maxholdingStocks, filter_ST, filter_NoData, filter_Suspension, false, map, Collections.EMPTY_MAP); } else { Map<PriceIndices, Double> map = new HashMap<>(); String[] indexName_array = indexName.split(";"); double[] indexVal_array = Arrays.stream(indexVal.split(";")).mapToDouble(Double::parseDouble).toArray(); for (int i = 0; i < indexName_array.length; i++) { map.put(PriceIndices.getIndex(indexName_array[i]), indexVal_array[i]); } return new BackTestInfo(startDate_sql, endDate_sql, stocksList, holdingPeriod, strategyType, maxholdingStocks, filter_ST, filter_NoData, filter_Suspension, false, Collections.EMPTY_MAP, map); } } } catch (ParseException e1) { e1.printStackTrace(); } return null; } } <file_sep>package ui.util; import javafx.scene.control.DateCell; import javafx.scene.control.DatePicker; import javafx.util.Callback; import sun.plugin2.jvm.RemoteJVMLauncher; import javax.xml.stream.events.EndDocument; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; /** * Created by st on 2017/3/8. */ public class DatePickerSettings { final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); /** * 设置开始时间选择器格式,最早不早于2005-3-1,最晚不晚于2014-3-25 * @param startDate * @return */ public Callback<DatePicker, DateCell> getStartSettings(DatePicker startDate) { Date minDate = null; Date maxDate = null; try { minDate = sdf.parse("2005-2-1"); maxDate = sdf.parse("2014-4-29"); } catch (ParseException e) { e.printStackTrace(); } Instant minInstant = minDate.toInstant(); Instant maxInstant = maxDate.toInstant(); ZoneId zone = ZoneId.systemDefault(); LocalDate minLocal = LocalDateTime.ofInstant(minInstant, zone).toLocalDate(); LocalDate maxLocal = LocalDateTime.ofInstant(maxInstant, zone).toLocalDate(); startDate.setValue(minLocal); // endDate.setValue(maxLocal); final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() { @Override public DateCell call(final DatePicker datePicker) { return new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); if (item.isBefore(minLocal) || item.isAfter(maxLocal) ) { setDisable(true); setStyle("-fx-background-color: #d8e7ef;"); } } }; } }; startDate.setDayCellFactory(dayCellFactory); // endDate.setDayCellFactory(dayCellFactory); return dayCellFactory; } /** * 设置结束时间选择器格式,最早不早于开始时间的后两个月,最晚不晚于开始时间的后两年,也不晚于2014-3-25 * @param startDate * @param endDate * @return */ public Callback<DatePicker, DateCell> getEndSettings(DatePicker startDate, DatePicker endDate) { Date maxDate = null; try { maxDate = sdf.parse("2014-4-29"); } catch (ParseException e) { e.printStackTrace(); } Instant maxInstant = maxDate.toInstant(); ZoneId zone = ZoneId.systemDefault(); LocalDate maxLocal = LocalDateTime.ofInstant(maxInstant, zone).toLocalDate(); endDate.setValue(startDate.getValue().plusYears(1)); final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() { @Override public DateCell call(final DatePicker datePicker) { return new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); if (item.isBefore(startDate.getValue().plusMonths(2)) || item.isAfter(startDate.getValue().plusYears(1)) || item.isAfter(maxLocal) ) { setDisable(true); setStyle("-fx-background-color: #d8e7ef;"); } } }; } }; endDate.setDayCellFactory(dayCellFactory); // endDate.setDayCellFactory(dayCellFactory); return dayCellFactory; } /** * 设置结束时间选择器格式,最早不早于开始时间的后两个月,最晚不晚于2014-3-25 * 该方法供回测时使用 * @param startDate * @param endDate * @return */ public Callback<DatePicker, DateCell> getBackTestEndSettings(DatePicker startDate, DatePicker endDate) { Date maxDate = null; try { maxDate = sdf.parse("2014-4-29"); } catch (ParseException e) { e.printStackTrace(); } Instant maxInstant = maxDate.toInstant(); ZoneId zone = ZoneId.systemDefault(); LocalDate maxLocal = LocalDateTime.ofInstant(maxInstant, zone).toLocalDate(); endDate.setValue(startDate.getValue().plusMonths(2)); final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() { @Override public DateCell call(final DatePicker datePicker) { return new DateCell() { @Override public void updateItem(LocalDate item, boolean empty) { super.updateItem(item, empty); if (item.isBefore(startDate.getValue().plusMonths(2)) || item.isAfter(maxLocal) ) { setDisable(true); setStyle("-fx-background-color: #d8e7ef;"); } } }; } }; endDate.setDayCellFactory(dayCellFactory); // endDate.setDayCellFactory(dayCellFactory); return dayCellFactory; } public Date getDate(DatePicker datePicker) { LocalDate localDate = datePicker.getValue(); ZoneId zone = ZoneId.systemDefault(); Instant instant = localDate.atStartOfDay().atZone(zone).toInstant(); Date date = Date.from(instant); return date; } } <file_sep>package vo; import java.util.Date; /** * 计算日均线 * Created by Pxr on 2017/3/3. */ public class DailyAverageVO { //均值 public double average; //日期 public Date date; public DailyAverageVO(double average, Date date) { this.average = average; this.date = date; } } <file_sep>import sys import tushare as ts year = int(sys.argv[1]) quarter = int(sys.argv[2]) df = ts.get_report_data(year, quarter) path = sys.argv[3] df.to_csv(path, encoding="utf8") df = ts.get_profit_data(year, quarter) path = sys.argv[4] df.to_csv(path, encoding="utf8") df = ts.get_operation_data(year, quarter) path = sys.argv[5] df.to_csv(path, encoding="utf8") df = ts.get_growth_data(year, quarter) path = sys.argv[6] df.to_csv(path, encoding="utf8") df = ts.get_debtpaying_data(year, quarter) path = sys.argv[7] df.to_csv(path, encoding="utf8") df = ts.get_cashflow_data(year, quarter) path = sys.argv[8] df.to_csv(path, encoding="utf8") <file_sep>package oquantour.po.util; /** * Created by keenan on 31/05/2017. */ public class BackTestBestInfo { // x轴 private double x_axis; // 回测统计数据 private BackTestStatistics backTestStatistics; // 超额收益率 private double extraReturnRate; // 策略胜率 private double winningRate; public BackTestBestInfo(double x_axis, BackTestStatistics backTestStatistics, double extraReturnRate, double winningRate) { this.x_axis = x_axis; this.backTestStatistics = backTestStatistics; this.extraReturnRate = extraReturnRate; this.winningRate = winningRate; } public double getX_axis() { return x_axis; } public void setX_axis(double x_axis) { this.x_axis = x_axis; } public BackTestStatistics getBackTestStatistics() { return backTestStatistics; } public void setBackTestStatistics(BackTestStatistics backTestStatistics) { this.backTestStatistics = backTestStatistics; } public double getExtraReturnRate() { return extraReturnRate; } public void setExtraReturnRate(double extraReturnRate) { this.extraReturnRate = extraReturnRate; } public double getWinningRate() { return winningRate; } public void setWinningRate(double winningRate) { this.winningRate = winningRate; } } <file_sep>package data.dataHelper; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import po.Stock; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by keenan on 06/03/2017. */ public class StockInfoReader { private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy"); /** * 获取股票信息 * * @param flag 若flag为0,则代表是按股票号查找 * 若flag为1,则代表是按年份查找 * @param mark 不同的查找关键词,可能是股票代码,也可能是日期(格式为MM/dd/yy) * @return 搜索结果:对应股票号的所有股票信息,或该年份的所有股票信息 * 若按股票号搜索,若股票号对应的股票不存在,则返回的队列中没有元素 * 若按年份搜索,若该年份没有股票信息,则队列中也没有元素 */ public List<Stock> readStockInfo(int flag, String mark) { if (flag != 1 && flag != 0) { return new ArrayList<>(); } List<Stock> stocksFound = new ArrayList(); String path = ""; // 如果是按股票号码查找,则flag为0 if (flag == 0) { path = System.getProperty("user.dir") + "/datasource/stocks/" + mark.substring(0, 1) + "/" + mark + ".txt"; } else // 如果是按日期查找,则flag为1 { path = System.getProperty("user.dir") + "/datasource/yearInfo/" + mark.substring(mark.length() - 2) + ".txt"; } try { stocksFound = txtReader(path); } catch (IOException e) { e.printStackTrace(); } return stocksFound; } /** * 根据年份获得股票信息 * * @param startYear 开始年份 * @param endYear 结束年份 * @return 那些年份的股票信息 */ public List<String> getStockByYear(int startYear, int endYear) { List<String> strings = new ArrayList<>(); try { for (int i = startYear; i <= endYear; i++) { if (i - 100 < 10) { strings.addAll(FileUtils.readLines(new File(System.getProperty("user.dir") + "/datasource/yearInfo/0" + (i - 100) + ".txt"))); } else { strings.addAll(FileUtils.readLines(new File(System.getProperty("user.dir") + "/datasource/yearInfo/" + (i - 100) + ".txt"))); } } } catch (IOException e) { e.printStackTrace(); } return strings; } // public Map<String, List<Stock>> getMeanValue(List<String> stockList, Date startDate, Date endDate, int meanValueDays) { // try { // Date date = null; // for (String s : stockList) { // List<String> strings = FileUtils.readLines(new File("datasource/stocks/" + s.substring(0, 1) + "/" + s + ".txt")); // for (int i = 0, size = strings.size(); i < size; i++) { // date = str2Date(strings.get(i).split(";")[1]); // // } // } // } catch (IOException e) { // e.printStackTrace(); // } // // } /** * 读取大量股票时的方法 * * @param stockList 股票号码列表 * @param startDate 开始日期 * @param endDate 结束日期 * @return 股票名对应其数据的map */ public Map<String, List<Stock>> readManyStocks(List<String> stockList, Date startDate, Date endDate) { Map<String, List<Stock>> map = new HashMap<>();//一个股票名对应一个list List<String> strings = getStockByYear(startDate.getYear(), endDate.getYear()); for (String s : stockList) { map.put(s, new ArrayList<>()); } int i = 0, size = strings.size(); Stock stock = null; for (; i < size; i++) { String s[] = StringUtils.split(strings.get(i), ";"); Date date = str2Date(s[1]); if (null != map.get(s[8])) { if (!date.before(startDate) && !date.after(endDate)) { stock = new Stock(strings.get(i), date); map.get(s[8]).add(stock); } } } return map; } /** * 根据给定的地址,从txt文件中获取股票信息 * * @param path 文件地址 * @return 该文件中的所有股票 */ private List<Stock> txtReader(String path) throws IOException { File file = new File(path); if (!file.exists()) { return new ArrayList<>(); } BufferedReader bufferedReader = null; List<Stock> stocks = new ArrayList<>(); try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String str = null; while ((str = bufferedReader.readLine()) != null) stocks.add(encapsulateStock(str)); } catch (IOException e) { e.printStackTrace(); } return stocks; } /** * 将txt中读到的每一行的股票信息封装成Stock对象 * 属性的顺序为: * Serial:0 * Date:1 * Open:2 * High:3 * Low:4 * Close:5 * Volume:6 * AdjClose:7 * code:8 * name:9 * market:10 * * @param stockInfo * @return 封装完成的股票信息,可能为null */ private Stock encapsulateStock(String stockInfo) { String[] attributes = stockInfo.split(";"); if (attributes.length != 11) { return null; } try { int serial = Integer.parseInt(attributes[0]); // System.out.println(attributes[1]); Date date = str2Date(attributes[1]); double open = Double.parseDouble(attributes[2]); double high = Double.parseDouble(attributes[3]); double low = Double.parseDouble(attributes[4]); double close = Double.parseDouble(attributes[5]); int volume = Integer.parseInt(attributes[6]); double adjClose = Double.parseDouble(attributes[7]); String code = attributes[8]; String name = attributes[9]; String market = attributes[10]; return new Stock(serial, date, open, high, low, close, volume, adjClose, code, name, market); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 将日期格式字符串转为Date对象 * * @param str 日期格式的字符串 * @return 对应的Date对象 */ private Date str2Date(String str) { Date date; // System.out.println(str+" pxr"); try { synchronized (simpleDateFormat){ date = simpleDateFormat.parse(str);} return date; } catch (ParseException e) { return null; } } /** * 读取所有交易日 * * @return 所有交易日组成的list */ public List<Date> readTransactionDays() { File f = new File(System.getProperty("user.dir") + "/datasource/transactionDays.txt"); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String[] transactionStringList = bufferedReader.readLine().split(";"); List<Date> transactionDateList = new ArrayList<>(); for (String s : transactionStringList) { transactionDateList.add(str2Date(s)); } return transactionDateList; } catch (IOException e) { e.printStackTrace(); } return new ArrayList<>(); } } <file_sep>import sys import tushare as ts df = ts.get_h_data(sys.argv[2], start='2005-01-01', end='2018-01-01', autype=None) path = sys.argv[1] df.to_csv(path, encoding="utf8") <file_sep>package vo; import javafx.beans.property.SimpleStringProperty; /** * Created by island on 2017/4/9. */ public class StockNameVO { //股票ID public String stockID; //股票名字 public String stockName; public SimpleStringProperty specCode; public SimpleStringProperty specName; public StockNameVO(String specCode, String specName) { this.specCode = new SimpleStringProperty(specCode); this.specName = new SimpleStringProperty(specName); } public String getSpecCode() { return specCode.get(); } public String getSpecName() { return specName.get(); } } <file_sep>package ui.bestperiod; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.DatePicker; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import ui.ControlledStage; import ui.MainViewController; import ui.StageController; import ui.util.AutoCloseStage; import ui.util.DatePickerSettings; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.Date; /** * Created by island on 2017/4/13. */ public class SearchBestPeriodController implements ControlledStage { private StageController stageController = new StageController(); final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private boolean momentumIsSelected = false; private boolean meanIsSelected = false; @FXML private Pane searchPane; @FXML private DatePicker startDate; @FXML private DatePicker endDate; @FXML private Button confirmButton; @FXML private Button momentumButton; @FXML private Button meanButton; @FXML private ChoiceBox periodChoiceBox; public void setStageController(StageController stageController) { this.stageController = stageController; } /** * 初始化方法 */ public void initial(){ DatePickerSettings datePickerSettings = new DatePickerSettings(); startDate.setDayCellFactory(datePickerSettings.getStartSettings(startDate)); endDate.setDayCellFactory(datePickerSettings.getBackTestEndSettings(startDate, endDate)); Date date = new Date(110,5,15); startDate.setValue(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); date = new Date(110,7,15); endDate.setValue(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); // 键盘监听,回车键发起搜索 searchPane.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { turnOrange(); } }); } public void backFromStockSelect(Date sDate, Date eDate, String type, String period) { initial(); endDate.setValue(eDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); startDate.setValue(sDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()); if(type.equals("动量策略")) selectMomentum(); if(type.equals("均值回归")) selectMean(); periodChoiceBox.setValue(period); } /** * 按钮响应 */ @FXML private void turnOrange() { confirmButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1"); } @FXML private void turnWhite() { confirmButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1"); } @FXML private void moTurnOrange() { if(!momentumButton.getStyle().equals("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) momentumButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void moTurnWhite() { if(!momentumButton.getStyle().equals("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) momentumButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void meTurnOrange() { if(!meanButton.getStyle().equals("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) meanButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void meTurnWhite() { if(!meanButton.getStyle().equals("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) meanButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); } /** * 选择动量策略 */ @FXML private void selectMomentum(){ momentumButton.setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); meanButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); momentumIsSelected = true; meanIsSelected = false; ObservableList<String> means = FXCollections.observableArrayList(); means.addAll("形成期", "持有期"); periodChoiceBox.setItems(means); } /** * 选择均值回归 */ @FXML private void selectMean(){ meanButton.setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); momentumButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); momentumIsSelected = false; meanIsSelected = true; ObservableList<String> means = FXCollections.observableArrayList(); means.addAll("形成期"); periodChoiceBox.setItems(means); } /** * 确认按钮 */ @FXML private void confirm(){ MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); DatePickerSettings datePickerSettings = new DatePickerSettings(); Date sDate = datePickerSettings.getDate(startDate); Date eDate = datePickerSettings.getDate(endDate); String period = (String) periodChoiceBox.getSelectionModel().getSelectedItem(); if(period == null){ AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请选择一种固定周期"); }else { if (meanIsSelected == false && momentumIsSelected == false) { Platform.runLater(new Runnable() { @Override public void run() { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请选择一种回测策略"); } }); } else if (meanIsSelected == true && momentumIsSelected == false) { mainViewController.setBackTestStockSelectPane(sDate, eDate, "均值回归", period); } else if (meanIsSelected == false && momentumIsSelected == true) { mainViewController.setBackTestStockSelectPane(sDate, eDate, "动量策略", period); } } } /** * 开始时间选择器监听,选择开始时间后,结束时间默认为开始时间的后两个月 */ @FXML private void changeEndDate() { ZoneId zone = ZoneId.systemDefault(); try { if (startDate.getValue().plusMonths(2). isAfter(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate())) { // 若开始时间的两个月后在2014/12/31之后,则设置结束时间为2014/12/31 endDate.setValue(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate()); } else { if(endDate.getValue().isBefore(startDate.getValue().plusMonths(2))) endDate.setValue(startDate.getValue().plusMonths(2)); } } catch (ParseException e) { e.printStackTrace(); } } } <file_sep>package ui.singleStock; import bl.stock.StockBL; import bl.stock.StockBLService; import exception.FirstStockNotExistException; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import ui.*; import ui.util.AutoCloseStage; import ui.util.DatePickerSettings; import ui.util.SearchNotificatePane; import vo.DailyAverageVO; import vo.KLineVO; import vo.SearchVO; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.Date; import java.util.List; import static java.lang.Thread.sleep; /** * Created by island on 2017/3/5. */ public class SearchSingleStockController implements ControlledStage { private StageController stageController = new StageController(); private String resource = "SearchSingleStockView.fxml"; private StockBLService stockBLService; final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); public void setStageController(StageController stageController) { this.stageController = stageController; } @FXML private DatePicker startDate; @FXML private DatePicker endDate; @FXML private TextField stockID; @FXML private Button confirmButton; @FXML private Pane searchPane; @FXML private Pane searchNotificationPane; @FXML private ScrollPane searchScrollPane; @FXML private Label nullLabel; /** * 确认按钮方法 */ @FXML private void confirm() { MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); mainViewController.showLoading(); Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { if (stockID.getText().equals("")) { Platform.runLater(new Runnable() { @Override public void run() { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入股票代码或名称"); } }); } else { MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); SearchVO searchVO = getSearchVO(); stockBLService = new StockBL(); try { List<KLineVO> kLineVOS = stockBLService.getKLineInfo(searchVO); List<List<DailyAverageVO>> ave = stockBLService.getDailyAverageInfo(searchVO); mainViewController.setInfoPane(getSearchVO(), kLineVOS, ave); } catch (FirstStockNotExistException e) { Platform.runLater(new Runnable() { @Override public void run() { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("找不到数据"); } }); } } return null; } }; Thread thread = new Thread(task); thread.start(); task.setOnSucceeded(new EventHandler<WorkerStateEvent>() { public void handle(WorkerStateEvent event) { MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); mainViewController.closeLoading(); } }); } /** * 按钮响应设置 */ @FXML private void turnRed() { confirmButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1"); } @FXML private void turnWhite() { confirmButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1"); } /** * 搜索单个股票界面初始化方法 */ public void init() { DatePickerSettings datePickerSettings = new DatePickerSettings(); datePickerSettings.getStartSettings(startDate); datePickerSettings.getEndSettings(startDate, endDate); // 键盘监听,回车键发起搜索 searchPane.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { turnRed(); confirm(); } }); SearchNotificatePane searchNotificatePane = new SearchNotificatePane(stockID, searchNotificationPane, nullLabel, searchScrollPane); searchNotificatePane.setTextField(269, 18, 55); } /** * 获得SearchVO * * @return */ private SearchVO getSearchVO() { DatePickerSettings datePickerSettings = new DatePickerSettings(); Date sDate = datePickerSettings.getDate(startDate); Date eDate = datePickerSettings.getDate(endDate); return new SearchVO(stockID.getText(), "", sDate, eDate); } /** * 开始时间选择器监听,选择开始时间后,结束时间默认为开始时间的后两个月 */ @FXML private void changeEndDate() { ZoneId zone = ZoneId.systemDefault(); try { if (startDate.getValue().plusMonths(2). isAfter(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate())) { // 若开始时间的两个月后在2014/12/31之后,则设置结束时间为2014/12/31 endDate.setValue(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate()); } else { endDate.setValue(startDate.getValue().plusMonths(2)); } } catch (ParseException e) { e.printStackTrace(); } } } <file_sep>package oquantour.util.tools; /** * Created by keenan on 10/06/2017. */ public enum PriceIndices { OpenPrice,// 开盘价 ClosePrice,// 收盘价 AdjClose,// 复权收盘价 HighPrice,// 最高价 LowPrice, // 最低价 Volume, // 成交量(一般都是六位数~八位数) Chg, // 涨跌幅 Amount,// 成交额(一般都是七~八位数) kValue,// 随机指标KDJ线k值 dValue,// 随机指标KDJ线d值 jValue,// 随机指标KDJ线j值 Ema12,// 12日EMA(指数平均数指标) Ema26,// 26日EMA(指数平均数指标) Up,// 布林上线 Down,// 布林下线 Dif,// 指数平滑移动平均线MACD线离差值 Dea,// 指数平滑移动平均线MACD线讯号线 Rsi; // 相对强弱指数RSI public static PriceIndices getIndex(String name) { switch (name) { case "调仓日开盘价": return OpenPrice; case "调仓日收盘价": return ClosePrice; case "调仓日复权收盘价": return AdjClose; case "调仓日最高价": return HighPrice; case "调仓日最低价": return LowPrice; case "调仓日成交量": return Volume; case "调仓日涨跌幅": return Chg; case "调仓日成交额": return Amount; case "KDJ线K值": return kValue; case "KDJ线D值": return dValue; case "KDJ线J值": return jValue; case "12日EMA": return Ema12; case "26日EMA": return Ema26; case "布林上线": return Up; case "布林下线": return Down; case "MACD离差值": return Dif; case "MACD线讯号": return Dea; case "RSI": return Rsi; default: return null; } } } <file_sep>import bl.strategy.BackTestingBLService; import bl.strategy.BackTestingBLServiceImpl; import bl.tools.StrategyType; import junit.framework.Test; import junit.framework.TestSuite; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Before; import vo.BackTestingInfoVO; import vo.BackTestingJudgeVO; import vo.BackTestingSingleChartVO; import vo.StrategyStatisticsVO; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * BackTestingBLServiceImpl Tester. * * @author <keenan> * @version 1.0 * @since <pre>04/17/2017</pre> */ public class BackTestingBLServiceImplTest { private BackTestingBLService backTestingBLService; @Before public void setUpBeforeClass() throws Exception { backTestingBLService = BackTestingBLServiceImpl.getInstance(); } @org.junit.Test public void testGetBackTestResult() throws Exception { BackTestingInfoVO backTestingInfoVO = new BackTestingInfoVO(new Date(2010 - 1900, 10 - 1, 15), new Date(2010 - 1900, 12 - 1, 15), false, "创业板", new ArrayList<>(), 5, 5, StrategyType.MOMENTUM); backTestingBLService.setBackTestingInfo(backTestingInfoVO); backTestingBLService.canBackTest(); List<BackTestingSingleChartVO> backTestingSingleChartVOS = backTestingBLService.getBackTestResult(); Assert.assertNotEquals(new ArrayList<>(), backTestingSingleChartVOS); } @org.junit.Test public void testGetBackTestStatistics() throws Exception { BackTestingInfoVO backTestingInfoVO = new BackTestingInfoVO(new Date(2010 - 1900, 10 - 1, 15), new Date(2010 - 1900, 12 - 1, 15), false, "创业板", new ArrayList<>(), 5, 5, StrategyType.MOMENTUM); backTestingBLService.setBackTestingInfo(backTestingInfoVO); backTestingBLService.canBackTest(); backTestingBLService.getBackTestResult(); StrategyStatisticsVO strategyStatisticsVO = backTestingBLService.getBackTestStatistics(); Assert.assertNotEquals(null, strategyStatisticsVO); } @org.junit.Test public void testSetBackTestingInfo() throws Exception { BackTestingInfoVO backTestingInfoVO = new BackTestingInfoVO(new Date(2010 - 1900, 10 - 1, 15), new Date(2010 - 1900, 12 - 1, 15), false, "创业板", new ArrayList<>(), 5, 5, StrategyType.MOMENTUM); backTestingBLService.setBackTestingInfo(backTestingInfoVO); BackTestingJudgeVO backTestingJudgeVO = backTestingBLService.canBackTest(); Assert.assertEquals(true, backTestingJudgeVO.getCanBackTest()); } @org.junit.Test public void testGetReturnRateDistribution() throws Exception { BackTestingInfoVO backTestingInfoVO = new BackTestingInfoVO(new Date(2010 - 1900, 10 - 1, 15), new Date(2010 - 1900, 12 - 1, 15), false, "创业板", new ArrayList<>(), 5, 5, StrategyType.MOMENTUM); backTestingBLService.setBackTestingInfo(backTestingInfoVO); BackTestingJudgeVO backTestingJudgeVO = backTestingBLService.canBackTest(); backTestingBLService.getBackTestResult(); List<Double> doubles = backTestingBLService.getReturnRateDistribution(); Assert.assertNotEquals(new ArrayList<>(), doubles); } } <file_sep>package ui.charts; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.EventHandler; import javafx.geometry.Bounds; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.chart.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.shape.Line; import javafx.scene.text.Text; import javafx.util.StringConverter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; /** * Created by island on 2017/3/22. */ public class SingleBarChart extends Pane { final BarChart<String, Number> bc; private double width; public SingleBarChart(List<Double> value) { //stage.setScene(new Scene(new SingleBarChart(value),1060, 600)); List<Integer> intvalue = new ArrayList<>(); int intnum = 0; for (int i = 0; i < value.size(); i++) { intnum = (int) (value.get(i).doubleValue() * 100); intvalue.add(intnum); } int maxLimit = Collections.max(intvalue); int minLimit = (-1) * Collections.min(intvalue); if(maxLimit + minLimit < 40){ minLimit += (40 - maxLimit - minLimit) / 2; maxLimit += (40 - maxLimit - minLimit) / 2; } int[] positive = new int[maxLimit + 1]; int[] negative = new int[minLimit + 1]; for (int i = 0; i <= maxLimit; i++) { positive[i] = 0; } for (int i = 0; i <= minLimit; i++) { negative[i] = 0; } int num; for (int i = 0; i < value.size(); i++) { num = Math.abs(intvalue.get(i)); if (value.get(i) >= 0) { positive[num]++; } else { negative[num]++; } } XYChart.Series series1 = new XYChart.Series(); XYChart.Series series2 = new XYChart.Series(); series1.setName("正收益周期"); series2.setName("负收益周期"); for (int i = negative.length - 1; i > 0; i--) { final XYChart.Data<String, Number> data = new XYChart.Data((-1 * i) + "%", negative[i]); data.nodeProperty().addListener(new ChangeListener<Node>() { @Override public void changed(ObservableValue<? extends Node> ov, Node oldNode, final Node node) { if (node != null) { displayLabelForData(data); node.setStyle("-fx-bar-fill: #7dbbfb;"); } } }); series1.getData().add(data); } for (int i = 0; i < positive.length; i++) { final XYChart.Data<String, Number> data = new XYChart.Data(i + "%", positive[i]); data.nodeProperty().addListener(new ChangeListener<Node>() { @Override public void changed(ObservableValue<? extends Node> ov, Node oldNode, final Node node) { if (node != null) { displayLabelForData(data); node.setStyle("-fx-bar-fill: #fba71b;"); } } }); series1.getData().add(data); } final CategoryAxis xAxis = new CategoryAxis(); final NumberAxis yAxis = new NumberAxis(); yAxis.setTickLabelFormatter(new StringConverter<Number>() { @Override public String toString(Number object) { if (object.intValue() != object.doubleValue()) return ""; return "" + (object.intValue()); } @Override public Number fromString(String string) { return 0; } }); bc = new BarChart<String, Number>(xAxis, yAxis); bc.setTitle("收益率分布直方图"); bc.setPrefSize(1060, 590); width = -1; bc.setBarGap(0); bc.setCategoryGap(width); bc.getData().addAll(series1); bc.getStylesheets().add("ui/MyChart.css"); this.getChildren().addAll(bc); //bc.getData().addAll(series2); } private void displayLabelForData(XYChart.Data<String, Number> data) { Node node = data.getNode(); if (data.getYValue().intValue() != 0) { Text dataText = new Text(data.getYValue() + ""); dataText.setStyle("-fx-text-fill: #838383; -fx-stroke: #838383;"); node.parentProperty().addListener(new ChangeListener<Parent>() { @Override public void changed(ObservableValue<? extends Parent> ov, Parent oldParent, Parent parent) { Group parentGroup = (Group) parent; parentGroup.getChildren().add(dataText); } }); node.boundsInParentProperty().addListener(new ChangeListener<Bounds>() { @Override public void changed(ObservableValue<? extends Bounds> ov, Bounds oldBounds, Bounds bounds) { dataText.setLayoutX( Math.round( bounds.getMinX() + bounds.getWidth() / 2 - dataText.prefWidth(-1) / 2 ) ); dataText.setLayoutY( Math.round( bounds.getMinY() - dataText.prefHeight(-1) * 0.5 ) ); width = bounds.getWidth(); } }); } } }<file_sep>package bl.tools; /** * Created by st on 2017/3/27. */ public enum StrategyType { MOMENTUM, MEANREVERSION } <file_sep>package oquantour.po.util; import oquantour.po.util.Edge; import java.util.List; import java.util.Map; import java.util.PriorityQueue; /** * Created by keenan on 06/06/2017. */ public class RelationGraph { /** * 边 */ private PriorityQueue<Edge> edges; /** * industries.get(industry_id)=industryName; */ private List<String> industries; /** * 行业收益率 */ private Map<String, List<ChartInfo>> industryReturnRate; public RelationGraph(PriorityQueue<Edge> edges, List<String> industries, Map<String, List<ChartInfo>> industryReturnRate) { this.edges = edges; this.industries = industries; this.industryReturnRate = industryReturnRate; } public PriorityQueue<Edge> getEdges() { return edges; } public void setEdges(PriorityQueue<Edge> edges) { this.edges = edges; } public List<String> getIndustries() { return industries; } public void setIndustries(List<String> industries) { this.industries = industries; } public Map<String, List<ChartInfo>> getIndustryReturnRate() { return industryReturnRate; } public void setIndustryReturnRate(Map<String, List<ChartInfo>> industryReturnRate) { this.industryReturnRate = industryReturnRate; } } <file_sep>package oquantour.po.util; import java.sql.Date; /** * 画图时要用的 * <p> * x轴和y轴对应的值 * <p> * Created by keenan on 07/05/2017. */ public class ChartInfo { // X轴 private double xAxis; // Date X轴 private Date dateXAxis; // String x轴 private String strXAxis; // Y轴 private double yAxis; public ChartInfo() { } public ChartInfo(Date dateXAxis, double yAxis) { this.dateXAxis = dateXAxis; this.yAxis = yAxis; } public ChartInfo(double xAxis, double yAxis) { this.xAxis = xAxis; this.yAxis = yAxis; } public ChartInfo(String strXAxis, double yAxis) { this.strXAxis = strXAxis; this.yAxis = yAxis; } public String getStrXAxis() { return strXAxis; } public void setStrXAxis(String strXAxis) { this.strXAxis = strXAxis; } public void setxAxis(double xAxis) { this.xAxis = xAxis; } public void setDateXAxis(Date dateXAxis) { this.dateXAxis = dateXAxis; } public void setyAxis(double yAxis) { this.yAxis = yAxis; } public double getxAxis() { return xAxis; } public Date getDateXAxis() { return dateXAxis; } public double getyAxis() { return yAxis; } } <file_sep>package ui.charts; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import java.text.DecimalFormat; /** * Created by island on 2017/3/22. */ public class TooltipContent extends GridPane { private String type; private Label yValue = new Label(); private Label dateValue = new Label(); private Label stock1Value = new Label(); private Label stock2Value = new Label(); private Label y = new Label("y:"); private Label date = new Label("Date:"); private Label stock1 = new Label("Stock1:"); private Label stock2 = new Label("Stock2:"); public TooltipContent(String yname, String datename, String name1, String name2, String type) { y.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #ffffff; -fx-padding: 2 5 2 0;"); yValue.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #ffffff; -fx-padding: 2 5 2 0;"); date.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #ffffff; -fx-padding: 2 5 2 0;"); dateValue.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #ffffff; -fx-padding: 2 5 2 0;"); stock1.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #69a9fd; -fx-padding: 2 5 2 0;"); stock1Value.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #69a9fd; -fx-padding: 2 5 2 0;"); stock2.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #fa9800; -fx-padding: 2 5 2 0;"); stock2Value.setStyle("-fx-font-size: 15px; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-text-fill: #f98600; -fx-padding: 2 5 2 0;"); setConstraints(date, 0, 0); setConstraints(dateValue, 1, 0); setConstraints(stock1, 0, 1); setConstraints(stock1Value, 1, 1); setConstraints(stock2, 0, 2); setConstraints(stock2Value, 1, 2); y.setText(yname); date.setText(datename); stock1.setText(name1); stock2.setText(name2); this.type = type; } public void update(String dateVa, double stock1Va, double stock2Va) { DecimalFormat decimalFormat = new DecimalFormat("#.##"); getChildren().clear(); dateValue.setText(dateVa); if(type.equals("backtest")){ stock1Value.setText(decimalFormat.format(stock1Va * 100) + "%"); stock2Value.setText(decimalFormat.format(stock2Va * 100) + "%"); } else { stock1Value.setText(decimalFormat.format(stock1Va) + ""); stock2Value.setText(decimalFormat.format(stock2Va) + ""); } getChildren().addAll(date, dateValue, stock1, stock1Value, stock2, stock2Value); } public void upadteArea(int dateVa, double value){ DecimalFormat decimalFormat = new DecimalFormat("#.##"); getChildren().clear(); dateValue.setText(dateVa + ""); stock1Value.setText(decimalFormat.format(value * 100) + "%"); getChildren().addAll(date, dateValue, stock1, stock1Value); } public void showXAxis(String dateVa){ getChildren().clear(); setConstraints(date, 0, 0); setConstraints(dateValue, 1, 0); getChildren().addAll(date, dateValue); dateValue.setText(dateVa); } public void showYAxis(double yVa){ DecimalFormat decimalFormat = new DecimalFormat("#.###"); getChildren().clear(); setConstraints(y, 0, 0); setConstraints(yValue, 1, 0); getChildren().addAll(y, yValue); if(type.equals("backtest")) { yValue.setText(decimalFormat.format(yVa * 100) + "%" ); } else { yValue.setText(yVa + ""); } } } <file_sep>package bl.tools; import po.Stock; import java.util.*; /** * 从map中提出Date的列表(排过序的) * <p> * Created by keenan on 31/03/2017. */ public class SplitMapElements { /** * 从map中提出Date的列表(排过序的) * * @param listMap map * @return 排过序的日期列表 */ public static List<Date> splitKeys(Map<Date, List<Stock>> listMap) { List<Date> dateList = new ArrayList<>(listMap.keySet()); Collections.sort(dateList); return dateList; } } <file_sep>package oquantour.po; import javax.persistence.*; import java.sql.Timestamp; /** * Created by island on 2017/6/1. */ @Entity @IdClass(StockCombinationPOPK.class) public class StockCombinationPO { private String userName; private String position; private String combinationName; private String stocks; private String prices; private Timestamp saveTime; @Id @Column(name = "UserName") public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Basic @Column(name = "Position") public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } @Id @Column(name = "CombinationName") public String getCombinationName() { return combinationName; } public void setCombinationName(String combinationName) { this.combinationName = combinationName; } @Basic @Column(name = "Stocks") public String getStocks() { return stocks; } public void setStocks(String stocks) { this.stocks = stocks; } @Basic @Column(name = "Prices") public String getPrices() { return prices; } public void setPrices(String prices) { this.prices = prices; } @Id @Column(name = "SaveTime") public Timestamp getSaveTime() { return saveTime; } public void setSaveTime(Timestamp saveTime) { this.saveTime = saveTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StockCombinationPO that = (StockCombinationPO) o; if (userName != null ? !userName.equals(that.userName) : that.userName != null) return false; if (position != null ? !position.equals(that.position) : that.position != null) return false; if (combinationName != null ? !combinationName.equals(that.combinationName) : that.combinationName != null) return false; if (stocks != null ? !stocks.equals(that.stocks) : that.stocks != null) return false; if (saveTime != null ? !saveTime.equals(that.saveTime) : that.saveTime != null) return false; return true; } @Override public int hashCode() { int result = userName != null ? userName.hashCode() : 0; result = 31 * result + (position != null ? position.hashCode() : 0); result = 31 * result + (combinationName != null ? combinationName.hashCode() : 0); result = 31 * result + (stocks != null ? stocks.hashCode() : 0); result = 31 * result + (saveTime != null ? saveTime.hashCode() : 0); return result; } } <file_sep>package oquantour.po; /** * Created by island on 2017/6/9. */ public class HotStockPO { private String StockID; private StockRealTimePO stockRealTimePO; private int changeRank; private int volumeRank; private int amountRank; private int comprehensiveRank; private double volumeRate; private double amountRate; private double changeRate; private double comprehensiveRate; public String getStockID() { return StockID; } public void setStockID(String stockID) { StockID = stockID; } public StockRealTimePO getStockRealTimePO() { return stockRealTimePO; } public void setStockRealTimePO(StockRealTimePO stockRealTimePO) { this.stockRealTimePO = stockRealTimePO; } public int getChangeRank() { return changeRank; } public void setChangeRank(int changeRank) { this.changeRank = changeRank; } public int getVolumeRank() { return volumeRank; } public void setVolumeRank(int volumeRank) { this.volumeRank = volumeRank; } public int getAmountRank() { return amountRank; } public void setAmountRank(int amountRank) { this.amountRank = amountRank; } public int getComprehensiveRank() { return comprehensiveRank; } public void setComprehensiveRank(int comprehensiveRank) { this.comprehensiveRank = comprehensiveRank; } public void setVolumeRate(double volumeRate) { this.volumeRate = volumeRate; } public void setAmountRate(double amountRate) { this.amountRate = amountRate; } public void setChangeRate(double changeRate) { this.changeRate = changeRate; } public double getComprehensiveRate() { return comprehensiveRate; } public void calComprehensiveRate(){ this.comprehensiveRate = volumeRate + amountRate + changeRate; } } <file_sep>package ui.backtest; import bl.stock.StockBL; import bl.stock.StockBLService; import bl.strategy.BackTestingBLService; import bl.strategy.BackTestingBLServiceImpl; import bl.strategy.WinningRateBLService; import bl.strategy.WinningRateBLServiceImpl; import bl.tools.StrategyType; import exception.FormativePeriodNotExistException; import exception.ParameterErrorException; import exception.SelectStocksException; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import org.apache.commons.lang.StringUtils; import ui.ControlledStage; import ui.MainViewController; import ui.StageController; import ui.util.AutoCloseStage; import ui.util.SearchNotificatePane; import vo.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; /** * Created by island on 2017/3/28. */ public class BackTestSelectStocksController implements ControlledStage { private StageController stageController; final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //选择了动量策略 private boolean momentumIsSelected = false; //选择了均值回归 private boolean meanIsSelected = false; //开始日期 private Date startDate; //结束日期 private Date endDate; //策略种类 private String type; //所有的股票按钮 private List<Button> buttons = new ArrayList<>(); //选中的股票按钮 private List<Button> selectedStocks = new ArrayList<>(); //SHOWALL private boolean showAll = false; //选择的板块名 private String plateName = ""; //固定的period种类 private String period = ""; //backtestingjudgevo BackTestingJudgeVO backTestingJudgeVO; //随机选择的股票票数 private int randomSelectNum = 200; //checkbox是否被选择 private boolean[] checkBoxs = {false, false, false}; //策略胜率 private List<WinningRateVO> winningRateVOS; @FXML private Button backButton; @FXML private Button confirmButton; @FXML private Button mainBoardButton; @FXML private Button startUpBoardButton; @FXML private Button smeBoardButton; @FXML private Label strategyLabel; @FXML private Label sDateLabel; @FXML private Label eDateLabel; @FXML private Pane momentumPane; @FXML private Pane meanPane; @FXML private TextField meanHoldingPeriod; @FXML private TextField meanMostNumOfStock; @FXML private ChoiceBox meanTypeChoiceBox; @FXML private TextField momentumHoldingPeriod; @FXML private TextField momentumFormativePeriod; @FXML private Pane stockPane; @FXML private Label numOfStocksLabel; @FXML private TextField stockTextField; @FXML private ScrollPane scrollPane; @FXML private Pane arrorImage; @FXML private Pane searchNotificationPane; @FXML private ScrollPane searchScrollPane; @FXML private Label nullLabel; @FXML private Tab stockPlateTab; @FXML private CheckBox mainCheckBox; @FXML private CheckBox stCheckBox; @FXML private CheckBox smeCheckBox; @FXML private TabPane stockTabPane; @FXML private Pane momentumPeriodPane; @FXML private TextField periodTextField; @FXML private Label periodLabel; @FXML private Label typeLabel; @FXML private Pane meanPeriodPane; @FXML private ChoiceBox meanTypeChoiceBox1; @FXML private TextField meanMostNumOfStock1; public void setStageController(StageController stageController) { this.stageController = stageController; } /** * 回测股票选择界面初始化方法 * * @param sDate * @param eDate * @param type */ public void initial(Date sDate, Date eDate, String type, String period) { this.type = type; ObservableList<String> means = FXCollections.observableArrayList(); means.addAll("5日均线", "10日均线", "20日均线"); startDate = sDate; endDate = eDate; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); sDateLabel.setText(sdf.format(startDate)); eDateLabel.setText(sdf.format(endDate)); this.period = period; if (type.equals("动量策略")) { if (period.equals("")) { momentumIsSelected = true; strategyLabel.setText("动 量 策 略"); momentumPane.setVisible(true); } if (period.equals("形成期")) { momentumIsSelected = true; typeLabel.setText("B E S T P E R I O D"); strategyLabel.setText("动 量 策 略"); momentumPeriodPane.setVisible(true); periodLabel.setText("形 成 期"); periodTextField.setPromptText("形成期:"); } if (period.equals("持有期")) { momentumIsSelected = true; strategyLabel.setText("动 量 策 略"); momentumPeriodPane.setVisible(true); periodLabel.setText("持 有 期"); periodTextField.setPromptText("持有期:"); typeLabel.setText("B E S T P E R I O D"); } } else { if (period.equals("")) { meanIsSelected = true; strategyLabel.setText("均 值 回 归"); meanPane.setVisible(true); meanTypeChoiceBox1.setItems(means); } else { meanIsSelected = true; strategyLabel.setText("均 值 回 归"); meanPeriodPane.setVisible(true); meanTypeChoiceBox.setItems(means); } } setAllStock(); SearchNotificatePane searchNotificatePane = new SearchNotificatePane(stockTextField, searchNotificationPane, nullLabel, searchScrollPane); searchNotificatePane.setTextField(125, 30, 110); //preset(); } /** * 选择一种板块的所有股票 * * @param plateName */ private void selectOneBoard(String plateName, CheckBox checkBox) { StockBLService stockBLService = new StockBL(); List<String> stocks = stockBLService.getAllStockCodeAndNameInPlate(plateName); String s; if (checkBox.isSelected()) { if (plateName.equals("深市主板")) checkBoxs[0] = true; if (plateName.equals("创业板")) checkBoxs[1] = true; if (plateName.equals("中小板")) checkBoxs[2] = true; for (int i = 0; i < stocks.size(); i++) { s = stocks.get(i).split(";")[0] + " " + stocks.get(i).split(";")[1]; for (int j = 0; j < buttons.size(); j++) { if (s.equals(buttons.get(j).getText())) { if (!selectedStocks.contains(buttons.get(j))) { buttons.get(j).setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.add(buttons.get(j)); break; } } } } } else { if (plateName.equals("深市主板")) checkBoxs[0] = false; if (plateName.equals("创业板")) checkBoxs[1] = false; if (plateName.equals("中小板")) checkBoxs[2] = false; for (int i = 0; i < stocks.size(); i++) { s = stocks.get(i).split(";")[0] + " " + stocks.get(i).split(";")[1]; for (int j = 0; j < buttons.size(); j++) { if (s.equals(buttons.get(j).getText())) { if (selectedStocks.contains(buttons.get(j))) { buttons.get(j).setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.remove(buttons.get(j)); break; } } } } } updateLabel(); } /** * 选择所有主板股票 */ @FXML private void selectMain() { selectOneBoard("深市主板", mainCheckBox); } /** * 选择所有创业板股票 */ @FXML private void selectSt() { selectOneBoard("创业板", stCheckBox); } /** * 选择所有中小板股票 */ @FXML private void selectSme() { selectOneBoard("中小板", smeCheckBox); } /** * 初始化所有股票 */ private void setAllStock() { StockBLService stockBLService = new StockBL(); List<String> allStocks = stockBLService.getAllStockCodeAndName(); String[][] stocks = new String[allStocks.size()][2]; stockPane.setPrefHeight(((allStocks.size() / 4) + 1) * 50 + 10); for (int i = 0; i < allStocks.size(); i++) { stocks[i][0] = allStocks.get(i).split(";")[0]; stocks[i][1] = allStocks.get(i).split(";")[1]; } for (int i = 0; i < stocks.length; i++) { Button b = new Button(stocks[i][1] + " " + stocks[i][0]); stockPane.getChildren().add(b); int row = i % 4; if (row == 0) b.setLayoutX(10); else if (row == 1) b.setLayoutX(170); else if (row == 2) b.setLayoutX(330); else if (row == 3) b.setLayoutX(490); int line = i / 4; b.setLayoutY(10 + line * 50); b.setPrefWidth(140); b.setPrefHeight(35); b.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); b.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { if (b.getStyle().equals("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand")) b.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); }); b.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { if (b.getStyle().equals("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand")) b.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); }); b.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> { arrorImage.setOpacity(0); if (b.getStyle().equals("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand")) { b.setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.add(b); } else { b.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.remove(b); } updateLabel(); }); buttons.add(b); } } /** * 更新已选择股票数信息label */ private void updateLabel() { numOfStocksLabel.setText("已选" + selectedStocks.size() + "支股票"); } /** * 取消所有已选中股票 */ @FXML private void cancelAll() { if (!selectedStocks.isEmpty()) { for (int i = selectedStocks.size() - 1; i >= 0; i--) { selectedStocks.get(i).setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.remove(selectedStocks.get(i)); } updateLabel(); } } /** * 随机选择200支股票方法 */ @FXML private void randomSelect() { int maxNum = buttons.size() - 1; if (selectedStocks.size() + 200 > buttons.size()) { if(selectedStocks.size() != buttons.size()) { for (int i = 0; i < buttons.size(); i++) { if (!selectedStocks.contains(buttons.get(i))) { buttons.get(i).setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.add(buttons.get(i)); } } updateLabel(); }else{ AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("超出股票总数"); } } else { Random rand = new Random(); int num = 0; for (int i = 0; i < 200; i++) { while (selectedStocks.contains(buttons.get(num))) { num = rand.nextInt(maxNum); } selectedStocks.add(buttons.get(num)); buttons.get(num).setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); } updateLabel(); } } /** * 搜索按钮响应 */ @FXML private void search() { searchScrollPane.setVisible(false); String stock = stockTextField.getText(); String stockID = ""; String stockName = ""; if (stock.equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入股票ID或股票名称"); return; } for (int i = 0; i < buttons.size(); i++) { String[] s = buttons.get(i).getText().split(" "); stockID = s[0]; stockName = s[1]; if (stock.equals(stockID) || stock.equals(stockName)) { scrollPane.setVvalue((buttons.get(i).getLayoutY()) / (stockPane.getPrefHeight() - 60)); int row = i % 4; if (row == 0) arrorImage.setLayoutX(-5); else if (row == 1) arrorImage.setLayoutX(155); else if (row == 2) arrorImage.setLayoutX(315); else if (row == 3) arrorImage.setLayoutX(475); int line = i / 4; arrorImage.setLayoutY(20 + line * 50); arrorImage.setOpacity(1); break; } if (i == buttons.size() - 1) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("没有该支股票"); } } } /** * 确认按钮响应 */ @FXML private void confirm() { stageController = new StageController(); MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); int holding = 0; int formative = 0; int ma = 0; int mostNumOfStock = 0; BackTestingBLService backTestingBLService = BackTestingBLServiceImpl.getInstance(); //选择动量策略 if (momentumIsSelected) { if (period.equals("")) { String holdingPeriod = momentumHoldingPeriod.getText(); String formativePeriod = momentumFormativePeriod.getText(); if (holdingPeriod.equals("") || formativePeriod.equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入形成期/持有期"); } else { if (StringUtils.isNumeric(holdingPeriod) && StringUtils.isNumeric(formativePeriod)) { holding = Integer.parseInt(holdingPeriod); formative = Integer.parseInt(formativePeriod); getMomemtumStockInfo(formative, holding); } else { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("形成期/持有期请输入整数"); } } } else { String periodNum = periodTextField.getText(); if (periodNum.equals("") || !StringUtils.isNumeric(periodNum)) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入正确的周期"); } else { int num = Integer.parseInt(periodNum); if (period.equals("持有期")) { formative = num; holding = num; } if (period.equals("形成期")) { formative = num; holding = num; } getMomemtumStockInfo(formative, holding); } } } //选择均值回归 else { String maType = ""; String mostNum = ""; ChoiceBox choiceBox; TextField textField; if (period.equals("")) { choiceBox = meanTypeChoiceBox1; textField = meanMostNumOfStock1; } else { choiceBox = meanTypeChoiceBox; textField = meanMostNumOfStock; } if (choiceBox.getSelectionModel().getSelectedItem() != null) maType = (String) choiceBox.getSelectionModel().getSelectedItem().toString(); mostNum = textField.getText(); if (maType.equals("") || mostNum.equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请正确填写均线种类/最多持仓股票数目"); } else { if (StringUtils.isNumeric(mostNum)) { mostNumOfStock = Integer.parseInt(mostNum); if (maType.equals("5日均线")) ma = 5; if (maType.equals("10日均线")) ma = 10; if (maType.equals("20日均线")) ma = 20; if (period.equals("")) { String holdingPeriod = meanHoldingPeriod.getText(); if (StringUtils.isNumeric(holdingPeriod)) { holding = Integer.parseInt(holdingPeriod); getMeanStockInfo(ma, holding, mostNumOfStock); } else { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("持有期请输入整数"); } } else { holding = ma; getMeanStockInfo(ma, holding, mostNumOfStock); } } else { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("最多持仓股票数目请输入整数"); } } } } private void getMomemtumStockInfo(int formative, int holding) { BackTestingBLService backTestingBLService = BackTestingBLServiceImpl.getInstance(); MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); boolean plate = stockPlateTab.isSelected(); BackTestingInfoVO backTestingInfoVO; List<String> stocks = new ArrayList<>(); //选择板块 if (plate) { if (plateName.equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请选择一个板块"); } else { showAll = false; backTestingInfoVO = new BackTestingInfoVO(startDate, endDate, showAll, plateName, new ArrayList<>(), formative, holding, StrategyType.MOMENTUM); defineBackTest(backTestingInfoVO); } } //选择股票 else { for (int i = 0; i < selectedStocks.size(); i++) { stocks.add(selectedStocks.get(i).getText().split(" ")[0]); } if (showAll) stocks.clear(); backTestingInfoVO = new BackTestingInfoVO(startDate, endDate, showAll, "", stocks, formative, holding, StrategyType.MOMENTUM); if (stocks.size() < 100 && !showAll) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请至少选择100支股票"); } else { defineBackTest(backTestingInfoVO); } } } public void getMeanStockInfo(int ma, int holding, int mostNumOfStock) { BackTestingBLService backTestingBLService = BackTestingBLServiceImpl.getInstance(); MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); boolean plate = stockPlateTab.isSelected(); BackTestingInfoVO backTestingInfoVO; List<String> stocks = new ArrayList<>(); //选择板块 if (plate) { if (plateName.equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请选择一个板块"); } else { showAll = false; backTestingInfoVO = new BackTestingInfoVO(startDate, endDate, showAll, plateName, ma, stocks, holding, StrategyType.MEANREVERSION, mostNumOfStock); defineBackTest(backTestingInfoVO); //mainViewController.setBackTestPane(backTestingInfoVO); } } //选择股票 else { for (int i = 0; i < selectedStocks.size(); i++) { stocks.add(selectedStocks.get(i).getText().split(" ")[0]); } if (showAll) stocks.clear(); backTestingInfoVO = new BackTestingInfoVO(startDate, endDate, showAll, "", ma, stocks, holding, StrategyType.MEANREVERSION, mostNumOfStock); if (stocks.size() < 100 && !showAll) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请至少选择100支股票"); } else { defineBackTest(backTestingInfoVO); } } } /** * 判断能否回测 */ private void defineBackTest(BackTestingInfoVO backTestingInfoVO) { BackTestingBLService backTestingBLService = BackTestingBLServiceImpl.getInstance(); MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); if(backTestingInfoVO.holdingPeriod <= 1 && !period.equals("形成期")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("持有期必须大于1"); }else { mainViewController.showLoading(); mainViewController.closeWaiting1(); Task<Void> task = new Task<Void>() { @Override protected Void call() throws Exception { backTestingBLService.setBackTestingInfo(backTestingInfoVO); try { backTestingJudgeVO = backTestingBLService.canBackTest(); } catch (SelectStocksException e) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("股票选择有问题"); } return null; } }; Thread thread = new Thread(task); thread.start(); task.setOnSucceeded(new EventHandler<WorkerStateEvent>() { public void handle(WorkerStateEvent event) { MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); mainViewController.closeLoading(); if (backTestingJudgeVO.getCanBackTest()) { stageController = new StageController(); stageController.loadStage("backtest/BackTestErrorView.fxml"); BackTestErrorController backTestErrorController = (BackTestErrorController) stageController.getController("backtest/BackTestErrorView.fxml"); backTestErrorController.init(backTestingJudgeVO, backTestingInfoVO, 0, checkBoxs, period); } else { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("可回测股票总数少于100支"); } } }); } } /** * 返回按钮响应 */ @FXML private void back() { stageController = new StageController(); MainViewController mainViewController = (MainViewController) stageController.getController("MainView.fxml"); if (period.equals("")) { mainViewController.backToBackTest(startDate, endDate, type); } else { mainViewController.backToBestPeriod(startDate, endDate, type, period); } } /** * 选择主板 */ @FXML private void selectMainBoard() { initAllButton(); mainBoardButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); plateName = "深市主板"; } /** * 选择创业板 */ @FXML private void selectStartUpBoard() { initAllButton(); startUpBoardButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); plateName = "创业板"; } /** * 选择中小板 */ @FXML private void selectSMEBoard() { initAllButton(); smeBoardButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); plateName = "中小板"; } /** * 按钮响应 */ @FXML private void cTurnOrange() { confirmButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1"); } @FXML private void cTurnWhite() { confirmButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1"); } @FXML private void bTurnOrange() { backButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1"); } @FXML private void bTurnWhite() { backButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1"); } @FXML private void mTurnOrange() { if (!mainBoardButton.getStyle().equals("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) mainBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void mTurnWhite() { if (!mainBoardButton.getStyle().equals("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) mainBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void stTurnOrange() { if (!startUpBoardButton.getStyle().equals("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) startUpBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void stTurnWhite() { if (!startUpBoardButton.getStyle().equals("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) startUpBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void smTurnOrange() { if (!smeBoardButton.getStyle().equals("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) smeBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void smTurnWhite() { if (!smeBoardButton.getStyle().equals("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1; -fx-border-radius: 50")) smeBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); } private void initAllButton() { smeBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); startUpBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); mainBoardButton.setStyle("-fx-text-fill: white; -fx-background-color: transparent; -fx-border-color: white; -fx-border-width: 1; -fx-border-radius: 50"); } @FXML private void allSelect() { for (int i = 0; i < buttons.size(); i++) { if (!selectedStocks.contains(buttons.get(i))) { buttons.get(i).setStyle("-fx-text-fill: #ffb199; -fx-background-color: transparent; -fx-border-color: #a29f9f; -fx-border-width: 1; -fx-border-radius: 50; -fx-cursor: hand"); selectedStocks.add(buttons.get(i)); } } updateLabel(); } } <file_sep>package oquantour.service.servicehelper.analysis.stock.arima; import Jama.Matrix; /** * Created by keenan on 16/05/2017. */ public class ARMAMath { /** * 均值 * * @param dataArray * @return */ protected double avgData(double[] dataArray) { return this.sumData(dataArray) / dataArray.length; } /** * 和 * @param dataArray * @return */ protected double sumData(double[] dataArray) { double sumData = 0; for (int i = 0; i < dataArray.length; i++) { sumData += dataArray[i]; } return sumData; } /** * 标准化后的方差 * @param dataArray * @return */ protected double varerrData(double[] dataArray) { double variance = 0; double avgsumData = this.avgData(dataArray); for (int i = 0; i < dataArray.length; i++) { dataArray[i] -= avgsumData; variance += dataArray[i] * dataArray[i]; } return variance / dataArray.length;//variance error; } /** * 计算自相关的函数 Tho(k)=Grma(k)/Grma(0) * * @param dataArray 数列 * @param order 阶数 * @return */ protected double[] autoCorData(double[] dataArray, int order) { double[] autoCor = new double[order + 1]; double varData = this.varerrData(dataArray);//标准化过后的方差 for (int i = 0; i <= order; i++) { autoCor[i] = 0; for (int j = 0; j < dataArray.length - i; j++) { autoCor[i] += dataArray[j + i] * dataArray[j]; } autoCor[i] /= dataArray.length; autoCor[i] /= varData; } return autoCor; } /** * Grma * * @param dataArray * @param order * @return 序列的自相关系数 */ protected double[] autoCorGrma(double[] dataArray, int order) { double[] autoCor = new double[order + 1]; for (int i = 0; i <= order; i++) { autoCor[i] = 0; for (int j = 0; j < dataArray.length - i; j++) { autoCor[i] += dataArray[j + i] * dataArray[j]; } autoCor[i] /= (dataArray.length - i); } return autoCor; } /** * 解MA模型的参数 * * @param autoCorData * @param q * @return */ protected double[] getMApara(double[] autoCorData, int q) { double[] maPara = new double[q + 1];//第一个存放噪声参数,后面q个存放ma参数sigma2,ma1,ma2... double[] tempmaPara = maPara; double temp = 0; boolean iterationFlag = true; //解方程组 //迭代法解方程组 maPara[0] = 1; while (iterationFlag) { for (int i = 1; i < maPara.length; i++) { temp += maPara[i] * maPara[i]; } tempmaPara[0] = autoCorData[0] / (1 + temp); for (int i = 1; i < maPara.length; i++) { temp = 0; for (int j = 1; j < maPara.length - i; j++) { temp += maPara[j] * maPara[j + i]; } tempmaPara[i] = -(autoCorData[i] / maPara[0] - temp); } iterationFlag = false; for (int i = 0; i < maPara.length; i++) { if (maPara[i] != tempmaPara[i]) { iterationFlag = true; break; } } maPara = tempmaPara; } return maPara; } /** * 计算自回归系数 * * @param dataArray * @param p * @param q * @return */ protected double[] parcorrCompute(double[] dataArray, int p, int q) { double[][] toplizeArray = new double[p][p];//p阶toplize矩阵; double[] atuocorr = this.autoCorData(dataArray, p + q);//返回p+q阶的自相关函数 double[] autocorrF = this.autoCorGrma(dataArray, p + q);//返回p+q阶的自相关系数数 for (int i = 1; i <= p; i++) { int k = 1; for (int j = i - 1; j > 0; j--) { toplizeArray[i - 1][j - 1] = atuocorr[q + k++]; } toplizeArray[i - 1][i - 1] = atuocorr[q]; int kk = 1; for (int j = i; j < p; j++) { toplizeArray[i - 1][j] = atuocorr[q + kk++]; } } Matrix toplizeMatrix = new Matrix(toplizeArray);//由二位数组转换成二维矩阵 Matrix toplizeMatrixInverse = toplizeMatrix.inverse();//矩阵求逆运算 double[] temp = new double[p]; for (int i = 1; i <= p; i++) { temp[i - 1] = atuocorr[q + i]; } Matrix autocorrMatrix = new Matrix(temp, p); Matrix parautocorDataMatrix = toplizeMatrixInverse.times(autocorrMatrix); // [Fi]=[toplize]x[autocorr]'; //矩阵计算结果应该是按照[a b c] 列向量存储的 double[] result = new double[parautocorDataMatrix.getRowDimension() + 1]; for (int i = 0; i < parautocorDataMatrix.getRowDimension(); i++) { result[i] = parautocorDataMatrix.get(i, 0); } // 估算sigma2 double sum2 = 0; for (int i = 0; i < p; i++) for (int j = 0; j < p; j++) { sum2 += result[i] * result[j] * autocorrF[Math.abs(i - j)]; } result[result.length - 1] = autocorrF[0] - sum2; // result数组最后一个存储干扰估计值 return result; } } <file_sep>package oquantour.service.servicehelper.strategy; import oquantour.exception.BackTestErrorException; import oquantour.exception.UnsupportedOperationException; import oquantour.exception.WinnerSelectionErrorException; import oquantour.po.StockPO; import oquantour.po.util.BackTestWinner; import oquantour.po.util.ChartInfo; import oquantour.util.tools.Calculator; import java.math.BigDecimal; import java.sql.Date; import java.util.*; /** * 在serviceImpl中处理股票池,策略类只负责根据股票池和回测条件进行计算,返回回测结果 * <p> * 策略类需要的参数为:股票池数据(以Map形式,包括了形成期的数据),形成期长度,持有期长度,最大持仓股票数 * <p> * Created by keenan on 10/05/2017. */ public abstract class Strategy { // 股票池 protected Map<Date, List<StockPO>> securities; // 形成期 protected int formative; // 持有期 protected int holding; // 回测开始日期 protected Date startDate; // 参与回测的股票数量 protected int numOfStocks; // 每个调仓日的赢家组合 protected List<BackTestWinner> dailyWinners; // 收益率分布 protected List<Double> returnRateDistribution; // 策略收益率 protected List<ChartInfo> backTestReturnRate; // 基准收益率 protected List<ChartInfo> benchmarkReturnRate; // 初始成本资金为一千万 private final BigDecimal initialFund = new BigDecimal(10000000); // 模拟当前资金,开始时和成本资金相同 private BigDecimal currentMoney = initialFund; // 调仓完成后的余额,起始为0 public Strategy(Map<Date, List<StockPO>> securities, int formative, int holding, Date startDate, int numOfStocks) { this.securities = securities; this.formative = formative; this.holding = holding; this.startDate = startDate; this.numOfStocks = numOfStocks; dailyWinners = new ArrayList<>(); returnRateDistribution = new ArrayList<>(); backTestReturnRate = new ArrayList<>(); benchmarkReturnRate = new ArrayList<>(); } public void setSecurities(Map<Date, List<StockPO>> securities) { this.securities = securities; } public void setFormative(int formative) { this.formative = formative; } public void setHolding(int holding) { this.holding = holding; } public int getHolding() { return holding; } public void setStartDate(Date startDate) { this.startDate = startDate; } public void setNumOfStocks(int numOfStocks) { this.numOfStocks = numOfStocks; } /** * 得到策略收益率 * <p> * 调仓日开盘前调仓 * * @return 策略收益率 */ public List<ChartInfo> getBackTestReturnRate() throws BackTestErrorException { if (!backTestReturnRate.isEmpty()) { backTestReturnRate = new ArrayList<>(); } List<Date> dateList = new ArrayList<>(securities.keySet()); Date lastDate = dateList.get(dateList.size() - 1); // 回测开始日期(形成期后的第一天) Date actualStartDate = dateList.get(formative); Date currentDate = actualStartDate; int cur_index = formative; try { while (!dateList.get(cur_index + holding - 1).after(lastDate)) { // 如果不是第一天,如果是调仓日,先把持仓股票卖出,计算收益率 // 如果不是调仓日,只要计算收益率 // 得到赢家组合 // 买入,得到份额 // 下一个调仓日 List<StockPO> winners = selectWinner(currentDate, dateList); BackTestWinner afterBuyingInfo = buyIntoShare(winners, currentDate); calBackTestReturnRate(afterBuyingInfo, dateList, currentDate); dailyWinners.add(afterBuyingInfo); if (dateList.get(cur_index + holding - 1).equals(lastDate)) { break; } cur_index += holding; currentDate = dateList.get(cur_index); } } catch (IndexOutOfBoundsException e) { List<StockPO> winners = selectWinner(currentDate, dateList); BackTestWinner afterBuyingInfo = buyIntoShare(winners, currentDate); calBackTestReturnRate(afterBuyingInfo, dateList, currentDate); dailyWinners.add(afterBuyingInfo); } catch (BackTestErrorException e) { throw e; } finally { return backTestReturnRate; } } /** * 计算策略收益率 * 并加入策略收益率结果中 * * @param winner 当前调仓日的赢家组合 * @param dateList 日期列表 * 包含形成期 * @param currentDate 当前日期 */ private void calBackTestReturnRate(BackTestWinner winner, List<Date> dateList, Date currentDate) { Date actualStartDate = dateList.get(formative); int i = 0; if (actualStartDate == currentDate) { backTestReturnRate.add(new ChartInfo(currentDate, 0)); i = 1; } int index = dateList.indexOf(currentDate); Date lastDate = dateList.get(dateList.size() - 1); BigDecimal totalFund; String lastRemainingStr; for (; i < holding; i++) { // 调仓日的初始余额为上一个调仓日调仓完后的余额 lastRemainingStr = (i == 0) ? String.valueOf(dailyWinners.get(dailyWinners.size() - 1).getDailyRemainings()) : String.valueOf(winner.getDailyRemainings()); if (index + i >= dateList.size()) { break; } // 如果日期超过了用户所选日期的最后一天,则跳出循环 else if (dateList.get(index + i).after(lastDate)) { break; } totalFund = new BigDecimal(lastRemainingStr); List<StockPO> currentDayStock = securities.get(dateList.get(index + i)); for (Map.Entry<StockPO, Integer> stock : winner.getShares().entrySet()) { StockPO correspondingStock = currentDayStock .stream() .filter(stockPO -> stockPO.getStockId().equals(stock.getKey().getStockId())) .findFirst() .get(); if (null == correspondingStock) { continue; } else { // 得到赢家组合中的股票的当日复权收盘价,乘以持股数即为当前资金数 BigDecimal closeOfCurrentDate = new BigDecimal(String.valueOf(correspondingStock.getAdjClose())); BigDecimal stockNum = new BigDecimal(String.valueOf(stock.getValue())); closeOfCurrentDate = closeOfCurrentDate.multiply(stockNum); totalFund = totalFund.add(closeOfCurrentDate); } } // 计算累计收益率(始终和最初的成本比较) currentMoney = totalFund; BigDecimal bigDecimal = currentMoney.subtract(initialFund); double rate = bigDecimal.divide(initialFund).doubleValue(); backTestReturnRate.add(new ChartInfo(dateList.get(index + i), rate)); } } /** * 得到基准收益率 * * @return 基准收益率 */ public List<ChartInfo> getBenchmarkReturnRate() { if (!benchmarkReturnRate.isEmpty()) { return benchmarkReturnRate; } // 在原股票池中删除形成期的数据 Map<Date, List<StockPO>> stockDataWithoutPeriod = getSecuritiesWithoutPeriodInfo(securities, startDate, formative); // 找到每个股票的第一天的数据 Map<String, StockPO> firstDayStocks = getFirstTransactionData(stockDataWithoutPeriod, numOfStocks); List<Double> total = new ArrayList<>(); for (Map.Entry<Date, List<StockPO>> entry : stockDataWithoutPeriod.entrySet()) { entry.getValue() .stream() .forEach(stock -> total.add((stock.getAdjClose() / firstDayStocks.get(stock.getStockId()).getAdjClose()) - 1)); benchmarkReturnRate.add(new ChartInfo(entry.getKey(), Calculator.avg(total))); total.clear(); } return benchmarkReturnRate; } /** * 得到调仓日赢家组合 * * @return 调仓日赢家组合 * @throws UnsupportedOperationException 非法操作 */ public List<BackTestWinner> getDailyWinners() throws UnsupportedOperationException { if (backTestReturnRate.isEmpty()) { throw new UnsupportedOperationException(); } return dailyWinners; } /** * 选择赢家组合 * * @param currentDate 当前调仓日的日期 * @param dateList 日期列表(包括形成期) * @return 调仓日赢家组合 */ protected abstract List<StockPO> selectWinner(Date currentDate, List<Date> dateList) throws BackTestErrorException, WinnerSelectionErrorException; /** * 调仓日买入股票 * <p> * 每日买入股票以整数股买入,记录余额和每个股票的买入股数 * * @param winners 当日赢家组合 * @param currentDate 当前调仓日期 * @return 当前调仓日完成调仓后的信息 */ private BackTestWinner buyIntoShare(List<StockPO> winners, Date currentDate) { Map<StockPO, Integer> shares = new HashMap<>(); double eachMoney = currentMoney.doubleValue() / winners.size(); BigDecimal remainings = new BigDecimal("0"); for (StockPO stock : winners) { int share = (int) Math.floor(eachMoney / stock.getAdjClose()); shares.put(stock, share); BigDecimal eachMoneyBigDecimal = new BigDecimal(String.valueOf(eachMoney)); BigDecimal priceBigDecimal = new BigDecimal(String.valueOf(stock.getAdjClose())); BigDecimal shareBigDecimal = new BigDecimal(String.valueOf(share)); BigDecimal investment = shareBigDecimal.multiply(priceBigDecimal); BigDecimal remain = eachMoneyBigDecimal.subtract(investment); remainings = remainings.add(remain); } BackTestWinner backTestWinner = new BackTestWinner(currentDate, shares, remainings.doubleValue()); return backTestWinner; } /** * 剔除股票池中形成期的数据 * * @param securities 原来的股票池 * @param startDate 回测开始日期 * @param formative 形成期长度 * @return 剔除形成期数据后的股票池 */ private Map<Date, List<StockPO>> getSecuritiesWithoutPeriodInfo(Map<Date, List<StockPO>> securities, Date startDate, int formative) { Map<Date, List<StockPO>> result = new TreeMap<>(securities); Set<Date> dateSet = new HashSet<>(result.keySet()); int cnt = 0; for (Date date : dateSet) { if (cnt == formative) { break; } if (date.before(startDate)) { result.remove(date); cnt++; } } return result; } /** * 得到每个股票的第一天的数据 * * @param securitiesWithoutPeriod 剔除了形成期的股票池 * @param numOfStocks 参与回测的股票数量 * @return 每个股票第一天的数据 */ private Map<String, StockPO> getFirstTransactionData(Map<Date, List<StockPO>> securitiesWithoutPeriod, int numOfStocks) { Map<Date, List<StockPO>> all = new TreeMap<>(securitiesWithoutPeriod); Map<String, StockPO> firstDay = new HashMap<>(); // 记录已经找到第一天数据的股票数量 int cnt = 0; for (Map.Entry<Date, List<StockPO>> entry : all.entrySet()) { // 全都找到了 if (cnt == numOfStocks) { break; } for (StockPO stock : entry.getValue()) { // 已经找到过这一只的了 if (firstDay.containsKey(stock.getStockId())) { continue; } else { firstDay.put(stock.getStockId(), stock); cnt++; } } } return firstDay; } /** * 得到持有期内都有数据的股票 * * @param date 当前日期 * @param dateList 日期列表(包含形成期) * @return 持有期内都有数据的股票 */ protected List<StockPO> holdingPeriodFilter(Date date, List<Date> dateList) throws UnsupportedOperationException { int index = dateList.indexOf(date); List<StockPO> currentDayInfo = securities.get(date); List<List<StockPO>> lists = new ArrayList<>(); for (int offset = 0; offset < holding; offset++) { if (offset + index >= dateList.size()) { break; } lists.add(securities.get(dateList.get(offset + index))); } Map<StockPO, Integer> map = new HashMap<>(); currentDayInfo.forEach(stock -> map.put(stock, 0)); for (List<StockPO> list : lists) { for (StockPO stockPO : list) { if (map.get(stockPO) == null) { map.put(stockPO, 0); } else { map.put(stockPO, map.get(stockPO).intValue() + 1); } } } List<StockPO> result = new ArrayList<>(); int size = dateList.size() - index; if (size >= holding) { size = holding; } for (Map.Entry<StockPO, Integer> entry : map.entrySet()) { if (entry.getValue() == size) { result.add(entry.getKey()); } } if (result.size() == 0) { throw new UnsupportedOperationException(); } return result; } /** * 得到某一股票某一日的股票信息 * * @param stockCode 股票代码 * @param date 日期 * @return 股票 */ protected StockPO getStockByCodeAndDay(String stockCode, Date date) { List<StockPO> stocks = securities.get(date); if (stocks == null) { return null; } StockPO stock = stocks.stream().filter(s -> s.getStockId().equals(stockCode)).findFirst().orElse(null); return stock; } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactId>Oquantour</artifactId> <groupId>Octopus</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>Oquantour_web</artifactId> <packaging>war</packaging> <name>Oquantour_web Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!--struts2--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.1.8</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts-default</artifactId> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.1.8.1</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier><!--指定jdk版本--> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.1.8</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> </exclusions> </dependency> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.4.RELEASE</version> </dependency> <!--<dependency>--> <!--<groupId>org.springframework</groupId>--> <!--<artifactId>spring-test</artifactId>--> <!--<version>4.1.7.RELEASE</version>--> <!--<scope>test</scope>--> <!--</dependency>--> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <!--hibernate--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.5.Final</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>org.apache.struts.xwork</groupId> <artifactId>xwork-core</artifactId> <version>2.3.8</version> </dependency> <dependency> <groupId>com.opensymphony</groupId> <artifactId>xwork-core</artifactId> <version>2.1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/gov.nist.math/jama --> <!-- java matrix helper --> <dependency> <groupId>gov.nist.math</groupId> <artifactId>jama</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math3</artifactId> <version>3.5</version> </dependency> <!-- log4j --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>com.opensymphony</groupId> <artifactId>xwork-core</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <finalName>Oquantour_web</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>package data.dataService; import po.Stock; import java.util.Date; import java.util.List; /** * Created by keenan on 07/03/2017. */ public interface TransactionDateDataService { /** * 得到某一日的前n个交易日的股票数据 * * @param daysBefore n的值 * @param date 某一日 * @return 前n个交易日的数据(若没有,则为空) */ List<Stock> getDaysBeforeByCode(int daysBefore, Date date, String code); /** * 根据日期得到这个交易日和前一个交易日的数据 * 如果这个交易日之前没有交易日,则返回的Stock[]长度为1 * 如果这个交易日之前有交易日,则返回的Stock[]长度为2 * 如果这一日不是交易日,或某个股票这一日没有交易数据,则返回的Stock[]长度为0 * * @param date 要查询的日期 * @return 791个股票的当前交易日和前一交易日的信息 */ List<Stock[]> getStockOfTodayAndYesterday(Date date); /** * 根据股票代码获得某只股票的全部交易日 * @param stock 股票代码/ * @return 所有交易日 */ List<Date> getAllTransactionDays(String stock); } <file_sep>function drawBackTestResultChart(jsonObj, strategyType) { var json = splitBackTestData(jsonObj); setIndex(json.index); drawBackTestLineChart('line_chart', json.dates, json.stdValue, json.backTestValue, "基准收益率", "策略收益率"); drawBackTestBarChart(json); drawWinner(json); getStraScore(json); drawAreaChart("extra_chart", json.bestX, json.extra, "超额收益率", '#F5C07D') drawAreaChart("winning_chart", json.bestX, json.winning, "策略胜率", '#CAF3A4') if (strategyType != "动量策略") { $("#bestHoldingNumLi").show(); var x = []; var extra = []; var winning = []; var bestHoldingNum = json.bestHoldingNum; for (var i = 0; i < bestHoldingNum.length; i++) { x.push(bestHoldingNum[i]["x_axis"]) extra.push(bestHoldingNum[i]["extraReturnRate"].toFixed(3)) winning.push(bestHoldingNum[i]["winningRate"].toFixed(3)) } drawAreaChart("extraNum_chart", x, extra, "超额收益率", '#F5C07D') drawAreaChart("winningNum_chart", x, winning, "策略胜率", '#CAF3A4') } else { $("#bestHoldingNumLi").hide(); } $("#strategyScoreDiv").show(); $("#backTestResult").fadeIn(); $("#backTestResult")[0].scrollIntoView({ behavior: "smooth" }); } function splitBackTestData(rawData) { var dates = []; var backTestValue = []; var stdValue = []; var returnRateDistribution = []; var index = []; var winner = []; var m = 0; var score = []; var bestHolding = []; var bestHoldingNum = []; for (var i = 1; i < rawData.length; i++) { if (rawData[i]["date"] != null) { dates[i - 1] = rawData[i]["date"]; backTestValue[i - 1] = rawData[i]["backTestValue"]; stdValue[i - 1] = rawData[i]["stdValue"]; } else if (rawData[i]["returnRateDistribution"] != null) { returnRateDistribution = rawData[i]["returnRateDistribution"]; } else if (rawData[i]["backTestStatistics"] != null) { index = rawData[i]["backTestStatistics"]; } else if (rawData[i]["winnerDate"] != null) { winner[m] = rawData[i]; m++; } else { score[0] = rawData[i]["抗风险能力"].toFixed(2); score[1] = rawData[i]["稳定性"].toFixed(2); score[2] = rawData[i]["盈利能力"].toFixed(2); score[3] = rawData[i]["持股分散度"].toFixed(2); score[4] = rawData[i]["评分"]; bestHolding = rawData[i]["最佳持有期"]; bestHoldingNum = rawData[i]["最佳持仓数"]; } } var bestX = []; var extra = []; var winning = []; for (var i = 0; i < bestHolding.length; i++) { bestX.push(bestHolding[i]["x_axis"]) extra.push(bestHolding[i]["extraReturnRate"].toFixed(3)) winning.push((bestHolding[i]["winningRate"] * 100).toFixed(3)) } var toFixedReturnRateDistribution = []; for (var j = 0; j < returnRateDistribution.length; j++) { toFixedReturnRateDistribution[j] = returnRateDistribution[j].toFixed(3); } return { dates: dates, backTestValue: backTestValue, stdValue: stdValue, returnRateDistribution: returnRateDistribution, index: index, toFixedReturnRateDistribution: toFixedReturnRateDistribution, winner: winner, score: score, bestX: bestX, extra: extra, winning: winning, bestHoldingNum: bestHoldingNum } } function setIndex(data) { $("#alpha").html(data["alpha"].toFixed(3)); $("#beta").html(data["beta"].toFixed(3)); $("#sharpe").html((data["sharpe"] * 100).toFixed(3) + "%"); $("#informationRatio").html((data["informationRatio"] * 100).toFixed(3) + "%"); $("#algorithmVolatility").html((data["algorithmVolatility"] * 100).toFixed(3) + "%"); $("#benchmarkVolatility").html((data["benchmarkVolatility"] * 100).toFixed(3) + "%"); $("#maxDrawdown").html(data["maxDrawdown"].toFixed(3)); $("#totalAnnualizedReturns").html((data["annualizedReturnRate"] * 100).toFixed(3) + "%"); $("#benchmarkAnnualizedReturns").html((data["stdAnnualizedReturnRate"] * 100).toFixed(3) + "%"); } function drawBackTestLineChart(chartID, x, series1, series2, s1Name, s2Name) { var myChart = echarts.init(document.getElementById(chartID)); var colors = ['#DAB3F5', '#F39C98', '#CAF3A4']; myChart.setOption(option = { color: colors, tooltip: { trigger: 'axis', axisPointer: { animation: true } }, legend: { data: [s1Name, s2Name] }, // grid: { // top: 70, // bottom: 50 // }, xAxis: [ { type: 'category', axisTick: { alignWithLabel: true }, axisLine: { onZero: false, lineStyle: { color: '#F5C07D' } }, data: x }, { show: false, type: 'category', axisTick: { alignWithLabel: true }, axisLine: { onZero: false, lineStyle: { color: '#A9CCF5' } }, data: x } ], yAxis: [ { type: 'value', name: '(%)', nameGap: 10 } ], dataZoom: [ { show: true, realtime: true, start: 0, end: 100, xAxisIndex: [0, 1] }, { type: 'inside', realtime: true, start: 0, end: 100, xAxisIndex: [0, 1] } ], series: [ { symbol: 'circle', name: s1Name, type: 'line', xAxisIndex: 1, smooth: true, data: series1, itemStyle: { normal: { color: '#F5C07D', lineStyle: { color: '#F5C07D', width: 2.5 } } } }, { symbol: 'circle', name: s2Name, type: 'line', smooth: true, data: series2, itemStyle: { normal: { color: '#A9CCF5', lineStyle: { color: '#A9CCF5', width: 2.5 } } } } ] }); } function drawBackTestBarChart(data) { var myChart = echarts.init(document.getElementById('bar_chart')); var bins = ecStat.histogram(data.toFixedReturnRateDistribution); myChart.setOption(option = { color: '#A9CCF5', grid: { left: '3%', right: '3%', bottom: '3%', top: 80, containLabel: true }, xAxis: [{ type: 'value', scale: true //这个一定要设,不然barWidth和bins对应不上 }], yAxis: [{ type: 'value' }], tooltip: { trigger: 'axis', axisPointer: { animation: true } }, series: [{ name: 'height', symbol: 'circle', type: 'bar', barWidth: '99.3%', itemStyle: { normal: { color: '#A9CCF5' } }, label: { normal: { show: true, position: 'insideTop', formatter: function (params) { return params.value[1]; } } }, data: bins.data } ] }); } function getStockName(code) { var allStock = window.localStorage.getItem("allStock").split(";"); for (var i = 0; i < allStock.length; i++) { if (allStock[i].split(",")[0] == code) return allStock[i].split(",")[1]; } } function drawWinner(data) { var winner = data.winner; var winnerSize = winner.length; //把调仓日赢家组合放入表格 var currentRows = 0; var insertTr = 0; $("#winnerTable").empty(); for (var offset = 0; offset < winnerSize; offset++) { currentRows = document.getElementById("winnerTable").rows.length; insertTr = document.getElementById("winnerTable").insertRow(currentRows); insertTr.style.textAlign = "center"; var insertTd = insertTr.insertCell(0); insertTd.innerHTML = winner[offset]["winnerDate"]; /// alert(winner[offset]["winnerDate"]); insertTd.colSpan = 8; insertTd.style.textAlign = "center"; insertTd.style.backgroundColor = "#c5ced5"; insertTd.style.color = "#fff"; insertTd.style.fontSize = "16px"; insertTd.colSpan = 8; insertTr = document.getElementById("winnerTable").insertRow(currentRows + 1); insertTr.className = "winnerTableSpecInfoHead"; var insertTd = insertTr.insertCell(0); insertTd.innerHTML = "代码"; insertTd.style.color = "#7a7a7a"; var insertTd = insertTr.insertCell(1); insertTd.innerHTML = "名称"; insertTd.style.color = "#7a7a7a"; var insertTd = insertTr.insertCell(2); insertTd.innerHTML = "开盘价"; insertTd.style.color = "#7a7a7a"; var insertTd = insertTr.insertCell(3); insertTd.innerHTML = "收盘价"; insertTd.style.color = "#7a7a7a"; var insertTd = insertTr.insertCell(4); insertTd.innerHTML = "最高价"; insertTd.style.color = "#7a7a7a"; var insertTd = insertTr.insertCell(5); insertTd.innerHTML = "最低价"; insertTd.style.color = "#7a7a7a"; var insertTd = insertTr.insertCell(6); insertTd.innerHTML = "份额"; insertTd.style.color = "#7a7a7a"; for (var j = offset; j < winnerSize; j++) { if (winner[offset]["winnerDate"] == winner[j]["winnerDate"]) { currentRows = document.getElementById("winnerTable").rows.length; insertTr = document.getElementById("winnerTable").insertRow(currentRows); var insertTd = insertTr.insertCell(0); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = "<span onclick='goToStockInfo(this.innerHTML)' style='cursor: pointer'>" + data.winner[j]["stockCode"] + "</span>"; var insertTd = insertTr.insertCell(1); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = getStockName(data.winner[j]["stockCode"]); // var insertTd = insertTr.insertCell(2); // insertTd.innerHTML = data.winner[j]["stockChg"]; var insertTd = insertTr.insertCell(2); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = data.winner[j]["stockOpen"]; var insertTd = insertTr.insertCell(3); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = data.winner[j]["stockClose"]; var insertTd = insertTr.insertCell(4); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = data.winner[j]["stockHigh"]; var insertTd = insertTr.insertCell(5); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = data.winner[j]["stockLow"]; var insertTd = insertTr.insertCell(6); insertTd.style.color = "#7a7a7a"; insertTd.innerHTML = data.winner[j]["share"]; } else { offset = j; break; } } } } function getStraScore(data) { // alert(data.score[0]); var myChart = echarts.init(document.getElementById('radarChart')); myChart.setOption(option = { // title: { // text: '基础雷达图' // }, tooltip: {}, legend: { show: false }, radar: { // shape: 'circle', indicator: [ {name: '抗风险能力', max: 1}, {name: '稳定性', max: 1}, {name: '盈利能力', max: 1}, {name: '持股分散度', max: 1} ] }, series: [{ type: 'radar', lineStyle: { normal: { color: '#F5C07D', } }, itemStyle: { normal: { color: '#F5C07D', } }, // areaStyle: {normal: {}}, data: [ { value: [data.score[0], data.score[1], data.score[2], data.score[3]], name: '策略评分' } ] }] }); $("#strategyScore").html(data.score[4]); } function drawAreaChart(id, date, y, name, color) { var myChart = echarts.init(document.getElementById(id)); var colors = ['#F5C07D', '#F39C98', '#CAF3A4']; myChart.setOption(option = { color: colors, tooltip: { trigger: 'axis', axisPointer: { animation: true } }, legend: { data: [name] }, // grid: { // top: 70, // bottom: 50 // }, xAxis: [ { type: 'category', axisTick: { alignWithLabel: true }, axisLine: { onZero: false, lineStyle: { color: '#F5C07D' } }, data: date }, { show: false, type: 'category', axisTick: { alignWithLabel: true }, axisLine: { onZero: false, lineStyle: { color: '#A9CCF5' } }, data: date } ], yAxis: [ { type: 'value', name: '(%)', nameGap: 10 } ], dataZoom: [ { show: true, realtime: true, start: 0, end: 100, xAxisIndex: [0, 1] }, { type: 'inside', realtime: true, start: 0, end: 100, xAxisIndex: [0, 1] } ], series: [ { symbol: 'none', name: name, type: 'line', xAxisIndex: 1, smooth: true, data: y, itemStyle: { normal: { color: color, lineStyle: { color: color, width: 2.5 } } }, areaStyle: { normal: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: color }, { offset: 1, color: color }]) } }, } ] }) } function showWinner() { if ($("#ifShowWinner").prop("checked")) { $("#displayWinnerDiv").fadeIn(); $("#displayWinnerDiv")[0].scrollIntoView({ behavior: "smooth" }) } else { $("#displayWinnerDiv").css("display", "none"); } } function goToStockInfo(stockID) { console.log(stockID) window.open("../jsp/stockInfo.jsp?stockName=" + stockID); } <file_sep>package vo; /** * Created by keenan on 07/04/2017. */ public class WinningRateVO { // 形成期 或 持有期 private int days; // 超额收益率 private double extraReturnRate; // 策略胜率 private double winningRate; public int getDays() { return days; } public double getExtraReturnRate() { return extraReturnRate; } public double getWinningRate() { return winningRate; } public WinningRateVO(int days, double extraReturnRate, double winningRate) { this.days = days; this.extraReturnRate = extraReturnRate; this.winningRate = winningRate; } } <file_sep>package bl.strategy; import exception.FormativePeriodNotExistException; import exception.ParameterErrorException; import exception.SelectStocksException; import exception.WinnerSelectErrorException; import vo.BackTestingInfoVO; import vo.BackTestingJudgeVO; import vo.WinningRateVO; import java.util.List; /** * 超额收益率和策略胜率 * <p> * 参数说明: * 与回测所用的数据基本相同 * 两种策略都需要的数据为: * 回测区间; 策略类型; 回测股票; * <p> * 如果是动量策略,还需要形成期或者持有期(只需调用相应的方法,数据的提取由逻辑层处理)、 * 如果是均值回归,还需要选择均线(5日、10日、20日) * a首先,用户要选择一个回测区间。 * <p> * Created by keenan on 07/04/2017. */ public interface WinningRateBLService { /** * 得到超额收益率和策略胜率(固定形成期) * * @param backTestingInfoVO * @return 超额收益率和策略胜率 */ List<WinningRateVO> getWinningRate_FixedFormative(BackTestingInfoVO backTestingInfoVO) throws SelectStocksException, FormativePeriodNotExistException, ParameterErrorException, WinnerSelectErrorException; /** * 得到超额收益率和策略胜率(固定持有期) * <p> * 若策略为均值回归,该方法返回空的List * * @param backTestingInfoVO * @return */ List<WinningRateVO> getWinningRate_FixedHolding(BackTestingInfoVO backTestingInfoVO) throws SelectStocksException, FormativePeriodNotExistException, ParameterErrorException, WinnerSelectErrorException; } <file_sep>package oquantour.data.dao; import oquantour.po.StockRealTimePO; import oquantour.po.util.ChartInfo; import java.sql.Date; import java.util.List; import java.util.Map; /** * Created by island on 2017/6/6. */ public interface IndustryDao { /** * 获得行业信息 * @param plateName * @param startDate * @param endDate * @return */ List<ChartInfo> getIndustryReturnRate(String plateName, Date startDate, Date endDate); /** * 获得所有行业名 * @return */ List<String> getAllIndustries(); /** * 获得股票所在的板块名 * @param stockIDs * @return Map<股票名, 行业名></> */ Map<String, String> getIndustryOfStock(String... stockIDs); /** * 获得行业中所有股票及其实时数据 * @param industryName * @return */ Map<String, StockRealTimePO> getStocksInIndustry(String industryName); /** * 获得行业中所有股票的ID * @param industryName * @return */ List<String> getStockIDsInIndustry(String industryName); /** * 添加行业信息 * @param industry */ void addIndustryInfo(String industry); } <file_sep>package oquantour.service.servicehelper.strategy; import oquantour.exception.BackTestErrorException; import oquantour.exception.UnsupportedOperationException; import oquantour.exception.WinnerSelectionErrorException; import oquantour.po.StockPO; import oquantour.po.util.SortInfo; import oquantour.util.tools.PriceIndices; import oquantour.util.tools.SortUtil; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Date; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by keenan on 16/05/2017. */ public class DIY_Strategy extends Strategy { private Map<PriceIndices, double[]> priceIndicesRange; private Map<PriceIndices, Double> priceIndicesWeight; private int maxHoldingNum; public DIY_Strategy(Map<Date, List<StockPO>> securities, int holding, Date startDate, int numOfStocks, Map<PriceIndices, double[]> priceIndicesRange, Map<PriceIndices, Double> priceIndicesWeight, int maxHoldingNum) { super(securities, 0, holding, startDate, numOfStocks); this.priceIndicesRange = priceIndicesRange; this.priceIndicesWeight = priceIndicesWeight; this.maxHoldingNum = maxHoldingNum; } /** * 选择赢家组合 * * @param currentDate 当前调仓日的日期 * @param dateList 日期列表(包括形成期) * @return 调仓日赢家组合 */ @Override protected List<StockPO> selectWinner(Date currentDate, List<Date> dateList) throws BackTestErrorException, WinnerSelectionErrorException { // 得到这个持有期内数据没有缺失的股票 List<StockPO> stockPOS = new ArrayList<>(); try { stockPOS = holdingPeriodFilter(currentDate, dateList); } catch (UnsupportedOperationException e) { throw new BackTestErrorException(); } if (priceIndicesRange == null || priceIndicesRange.isEmpty()) { return weightFilter(stockPOS); } else if (priceIndicesWeight == null || priceIndicesWeight.isEmpty()) { return rangeFilter(stockPOS); } return null; } /** * 按照区间方式进行调仓 * * @return 赢家组合 */ private List<StockPO> rangeFilter(List<StockPO> stockPOS) { List<SortInfo> sortInfos = new ArrayList<>(); for (StockPO stockPO : stockPOS) { int inCnt = 0; for (Map.Entry<PriceIndices, double[]> entry : priceIndicesRange.entrySet()) { double down = entry.getValue()[0]; double up = entry.getValue()[1]; double value = getValue(stockPO, entry.getKey()); if (value >= down && value <= up) { inCnt++; } } sortInfos.add(new SortInfo(stockPO, inCnt)); } SortUtil.sortDescending(sortInfos, sortInfo -> sortInfo.getValue()); int maxSize = (sortInfos.size() < maxHoldingNum) ? sortInfos.size() : maxHoldingNum; List<StockPO> winner = new ArrayList<>(); for (int i = 0; i < maxSize; i++) { winner.add(sortInfos.get(i).getStock()); } return winner; } /** * 按照权重方式进行调仓 * * @return 赢家组合 */ private List<StockPO> weightFilter(List<StockPO> stockPOS) { List<SortInfo> sortInfos = new ArrayList<>(); for (StockPO stockPO : stockPOS) { Double score = 0.0; for (Map.Entry<PriceIndices, Double> entry : priceIndicesWeight.entrySet()) { score += getValue(stockPO, entry.getKey()) * entry.getValue(); } sortInfos.add(new SortInfo(stockPO, score)); } SortUtil.sortDescending(sortInfos, sortInfo -> sortInfo.getValue()); int maxSize = (sortInfos.size() < maxHoldingNum) ? sortInfos.size() : maxHoldingNum; List<StockPO> winner = new ArrayList<>(); for (int i = 0; i < maxSize; i++) { winner.add(sortInfos.get(i).getStock()); } return winner; } /** * 获得对应指标的值 * * @param stockPO 股票 * @param priceIndex 技术指标枚举类型 * @return 对应指标值 */ private Double getValue(StockPO stockPO, PriceIndices priceIndex) { try { Class clazz = stockPO.getClass(); String methodName = "get" + priceIndex.toString(); Method method = clazz.getMethod(methodName); Double value = (Double) method.invoke(stockPO); return value; } catch (NoSuchMethodException e1) { e1.printStackTrace(); return 0.0; } catch (IllegalAccessException e2) { e2.printStackTrace(); return 0.0; } catch (InvocationTargetException e3) { return 0.0; } } } <file_sep>package oquantour.action; import com.opensymphony.xwork2.ActionSupport; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import oquantour.exception.InnerValueException; import oquantour.exception.StockDataNotExistException; import oquantour.po.StockPO; import oquantour.po.StockRealTimePO; import oquantour.po.util.ChartInfo; import oquantour.service.PlateService; import oquantour.service.StockService; import oquantour.util.tools.BasicIndices; import oquantour.util.tools.IndicesAnalysis; import oquantour.po.util.StockInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.*; /** * Created by Pxr on 2017/5/12. */ @Controller public class StockAction extends ActionSupport { @Autowired private StockService stockService; @Autowired private PlateService plateService; public void setPlateService(PlateService plateService) { this.plateService = plateService; } private String stockInfo; private String searchResult; private String result; private String plateName; private Map<String, double[]> indexs; private String indexVal; private String indexName; public String getKLine() { JSONArray jsonArray = new JSONArray(); StockInfo stock = null; List<ChartInfo> chartInfos = new ArrayList<>(); JSONObject json = new JSONObject(); try { stock = stockService.getStockInfo(stockInfo); chartInfos = stockService.getInnerValue(stockInfo); searchResult = "搜索成功"; json.put("searchResult", searchResult); } catch (StockDataNotExistException e2) { searchResult = "搜索的股票不存在"; JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("searchResult", searchResult); jsonArray.add(jsonObject1); result = jsonArray.toString(); return SUCCESS; } catch (InnerValueException e2) { searchResult = e2.getMessage(); json.put("searchResult", searchResult); } Map<String, StockRealTimePO> stringStockRealTimePOMap = stockService.getRealTimeStockInfo(stockInfo); List<StockPO> stockPOList = stock.getStockInfo(); List<StockPO> weeklyInfo = stock.getWeeklyInfo(); List<StockPO> monthlyInfo = stock.getMonthlyInfo(); json.put("stockID", stockPOList.get(0).getStockId()); json.put("advice", stock.getAdvice()); json.put("estimatedOpen", stock.getEstimatedOpen()); json.put("estimatedClose", stock.getEstimatedClose()); json.put("estimatedHigh", stock.getEstimatedHigh()); json.put("estimatedLow", stock.getEstimatedLow()); json.put("estimatedAdjClose", stock.getEstimatedAdjClose()); json.put("basicInfo", stock.getBasicInfo()); json.put("score", stockService.getScore(stockInfo)); json.put("实时", stringStockRealTimePOMap.get(stockInfo)); // System.out.println(stringStockRealTimePOMap.get(stockInfo).getTrade()); jsonArray.add(json); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); for (StockPO stockPO : stockPOList) { JSONObject jsonObject = new JSONObject(); jsonObject.put("日期", simpleDateFormat.format(stockPO.getDateValue())); jsonObject.put("开盘价", stockPO.getOpenPrice()); jsonObject.put("复权收盘价", stockPO.getClosePrice());//这里暂时先用收盘价 jsonObject.put("最高价", stockPO.getHighPrice()); jsonObject.put("最低价", stockPO.getLowPrice()); jsonObject.put("交易量", stockPO.getVolume()); jsonObject.put("涨跌幅", String.format("%.4f", stockPO.getChg() * 100)); jsonObject.put("对数收益率", String.format("%.3f", stockPO.getReturnRate())); // jsonObject.put("板块名", stockPO.getPlate()); jsonObject.put("5日均线", String.format("%.2f", stockPO.getMa5())); jsonObject.put("10日均线", String.format("%.2f", stockPO.getMa10())); jsonObject.put("20日均线", String.format("%.2f", stockPO.getMa20())); jsonObject.put("30日均线", String.format("%.2f", stockPO.getMa30())); jsonObject.put("60日均线", String.format("%.2f", stockPO.getMa60())); jsonObject.put("120日均线", String.format("%.2f", stockPO.getMa120())); jsonObject.put("240日均线", String.format("%.2f", stockPO.getMa240())); jsonObject.put("mb", stockPO.getMb()); jsonObject.put("up", stockPO.getUp()); jsonObject.put("dn", stockPO.getDn()); jsonObject.put("j", stockPO.getjValue()); jsonObject.put("d", stockPO.getdValue()); jsonObject.put("k", stockPO.getkValue()); jsonObject.put("dif", stockPO.getDif()); jsonObject.put("dea", stockPO.getDea()); jsonObject.put("macd", stockPO.getDif() - stockPO.getDea()); jsonObject.put("adx", stockPO.getAdx()); jsonObject.put("adxr", stockPO.getAdxr()); jsonObject.put("+di", stockPO.getDiPlus()); jsonObject.put("-di", stockPO.getDiMinus()); jsonArray.add(jsonObject); } JSONObject temp1 = new JSONObject(); temp1.put("日期", -1); jsonArray.add(temp1); for (StockPO stockPO : weeklyInfo) { JSONObject jsonObject = new JSONObject(); jsonObject.put("日期(周)", simpleDateFormat.format(stockPO.getDateValue())); jsonObject.put("开盘价(周)", stockPO.getOpenPrice()); jsonObject.put("复权收盘价(周)", stockPO.getClosePrice());//这里暂时先用收盘价 jsonObject.put("最高价(周)", stockPO.getHighPrice()); jsonObject.put("最低价(周)", stockPO.getLowPrice()); jsonObject.put("交易量(周)", stockPO.getVolume()); jsonObject.put("5日均线", String.format("%.2f", stockPO.getMa5())); jsonObject.put("10日均线", String.format("%.2f", stockPO.getMa10())); jsonObject.put("20日均线", String.format("%.2f", stockPO.getMa20())); jsonObject.put("30日均线", String.format("%.2f", stockPO.getMa30())); jsonObject.put("60日均线", String.format("%.2f", stockPO.getMa60())); jsonObject.put("120日均线", String.format("%.2f", stockPO.getMa120())); jsonObject.put("240日均线", String.format("%.2f", stockPO.getMa240())); jsonArray.add(jsonObject); } JSONObject temp2 = new JSONObject(); temp2.put("日期(周)", -1); jsonArray.add(temp2); for (StockPO stockPO : monthlyInfo) { JSONObject jsonObject = new JSONObject(); jsonObject.put("日期(月)", simpleDateFormat.format(stockPO.getDateValue())); jsonObject.put("开盘价(月)", stockPO.getOpenPrice()); jsonObject.put("复权收盘价(月)", stockPO.getClosePrice());//这里暂时先用收盘价 jsonObject.put("最高价(月)", stockPO.getHighPrice()); jsonObject.put("最低价(月)", stockPO.getLowPrice()); jsonObject.put("交易量(月)", stockPO.getVolume()); jsonObject.put("5日均线", String.format("%.2f", stockPO.getMa5())); jsonObject.put("10日均线", String.format("%.2f", stockPO.getMa10())); jsonObject.put("20日均线", String.format("%.2f", stockPO.getMa20())); jsonObject.put("30日均线", String.format("%.2f", stockPO.getMa30())); jsonObject.put("60日均线", String.format("%.2f", stockPO.getMa60())); jsonObject.put("120日均线", String.format("%.2f", stockPO.getMa120())); jsonObject.put("240日均线", String.format("%.2f", stockPO.getMa240())); jsonArray.add(jsonObject); } Map<Date, String> kdjAnaBuy = stock.getBuyPoints().get(IndicesAnalysis.KDJ); Map<Date, String> kdjAnaSell = stock.getSellPoints().get(IndicesAnalysis.KDJ); Map<Date, String> bollAnaBuy = stock.getBuyPoints().get(IndicesAnalysis.BOLL); Map<Date, String> bollAnaSell = stock.getSellPoints().get(IndicesAnalysis.BOLL); Map<Date, String> macdAnaBuy = stock.getBuyPoints().get(IndicesAnalysis.MACD); Map<Date, String> macdAnaSell = stock.getSellPoints().get(IndicesAnalysis.MACD); Map<Date, String> dmiAnaBuy = stock.getBuyPoints().get(IndicesAnalysis.DMI); Map<Date, String> dmiAnaSell = stock.getSellPoints().get(IndicesAnalysis.DMI); for (Map.Entry<Date, String> entry : kdjAnaBuy.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("kdjDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("kdjAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : kdjAnaSell.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("kdjDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("kdjAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : bollAnaBuy.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("bollDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("bollAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : bollAnaSell.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("bollDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("bollAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : macdAnaBuy.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("macdDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("macdAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : macdAnaSell.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("macdDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("macdAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : dmiAnaBuy.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("dmiDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("dmiAna", entry.getValue()); jsonArray.add(jsonObject); } for (Map.Entry<Date, String> entry : dmiAnaSell.entrySet()) { JSONObject jsonObject = new JSONObject(); jsonObject.put("dmiDate", simpleDateFormat.format(entry.getKey())); jsonObject.put("dmiAna", entry.getValue()); jsonArray.add(jsonObject); } if (!chartInfos.isEmpty()) { for (ChartInfo chartInfo : chartInfos) { JSONObject jsonObject = new JSONObject(); jsonObject.put("xAxis", simpleDateFormat.format(chartInfo.getDateXAxis())); jsonObject.put("value", chartInfo.getyAxis()); jsonArray.add(jsonObject); } } Set<Date> dates = new TreeSet<>(); dates.addAll(macdAnaBuy.keySet()); dates.addAll(macdAnaSell.keySet()); dates.addAll(kdjAnaBuy.keySet()); dates.addAll(kdjAnaSell.keySet()); dates.addAll(bollAnaBuy.keySet()); dates.addAll(bollAnaSell.keySet()); dates.addAll(dmiAnaBuy.keySet()); dates.addAll(dmiAnaSell.keySet()); List<Date> datesList = new ArrayList<>(dates); List<Integer> kdjList = new ArrayList<>(); List<Integer> bollList = new ArrayList<>(); List<Integer> macdList = new ArrayList<>(); List<Integer> dmiList = new ArrayList<>(); for (Date date : datesList) { JSONObject jsonObject = new JSONObject(); jsonObject.put("allDate", simpleDateFormat.format(date)); jsonArray.add(jsonObject); addToList(kdjList, kdjAnaBuy, kdjAnaSell, date); addToList(bollList, bollAnaBuy, bollAnaSell, date); addToList(macdList, macdAnaBuy, macdAnaSell, date); addToList(dmiList, dmiAnaBuy, dmiAnaSell, date); } JSONObject jsonObject = new JSONObject(); jsonObject.put("kdjList", kdjList); jsonObject.put("bollList", bollList); jsonObject.put("macdList", macdList); jsonObject.put("dmiList", dmiList); jsonArray.add(jsonObject); result = jsonArray.toString(); return SUCCESS; } public String getAllStockNameAndCode() { List<String> stringList = stockService.getAllStockCodeAndName(); Map<String, Object> map = new HashMap<>(); map.put("stockNameAndCode", stringList); JSONObject jsonObject = JSONObject.fromObject(map); result = jsonObject.toString(); return SUCCESS; } public String getRecommendedStock() { List<StockRealTimePO> stringList = stockService.getRecommendedStock(stockInfo); JSONObject jsonObject = new JSONObject(); jsonObject.put("recommend", stringList); result = jsonObject.toString(); return SUCCESS; } public String getStockByPlate() { List<String> strings = plateService.getStockByPlate(plateName); Map<String, Object> map = new HashMap<>(); map.put("stockInPlate", strings); JSONObject jsonObject = JSONObject.fromObject(map); result = jsonObject.toString(); return SUCCESS; } private void addToList(List<Integer> list, Map<Date, String> map1, Map<Date, String> map2, Date date) { if (map1.get(date) != null) { list.add(1); } else if (map2.get(date) != null) { list.add(-1); } else { list.add(0); } } public String selectStock() { Map<BasicIndices, double[]> map = new HashMap<>(); String[] indexName_array = new String[0]; double[] indexVal_array = new double[0]; if (indexName.length() > 0 && indexVal.length() > 0) { indexName_array = indexName.split(";"); indexVal_array = Arrays.stream(indexVal.split(";")).mapToDouble(Double::parseDouble).toArray(); } int j = 0; for (int i = 0; i < indexName_array.length; i++) { double[] value = new double[2]; value[0] = indexVal_array[j]; j++; value[1] = indexVal_array[j]; j++; System.out.println("st " + value[0] + ";" + value[1]); map.put(BasicIndices.getIndex(indexName_array[i]), value); } System.out.println("map的size" + map.size()); Map<String, String> stock = stockService.selectStock(map); System.out.println("stock的size" + stock.size()); List<String> stockID = new ArrayList<>(stock.keySet()); List<String> stockName = new ArrayList<>(); for (String s : stockID) { stockName.add(stock.get(s)); } JSONObject jsonObject = new JSONObject(); jsonObject.put("stockID", stockID); jsonObject.put("stockName", stockName); result = jsonObject.toString(); return SUCCESS; } public void setStockService(StockService stockService) { this.stockService = stockService; } public void setStockInfo(String stockInfo) { this.stockInfo = stockInfo; } public void setSearchResult(String searchResult) { this.searchResult = searchResult; } public void setResult(String result) { this.result = result; } public String getResult() { return result; } public void setPlateName(String plateName) { this.plateName = plateName; } public void setIndexs(Map<String, double[]> index) { this.indexs = index; } public void setIndexVal(String indexVal) { this.indexVal = indexVal; } public void setIndexName(String indexName) { this.indexName = indexName; } } <file_sep>package oquantour.po; import javax.persistence.*; /** * Created by island on 2017/6/4. */ @Entity @Table(name = "stockbasicinfo", schema = "oquantour", catalog = "") @IdClass(StockBasicInfoPOPK.class) public class StockBasicInfoPO { /** * 股票号 */ private String stockId; /** * 季度 */ private String quarterOfYear; /************************************************* * 业绩报告(主表) * *************************************************/ /** * 每股收益 */ private Double esp; /** * 每股净资产 */ private Double bvps; /** * 净资产收益率(%) */ private Double roe; /** * 净利润(万元) */ private Double netProfits; /** * 净利润同比(%) */ private Double profitsYoy; /************************************************* * 盈利能力 * *************************************************/ /** * 净利率(%) */ private Double netProfitRatio; /** * 毛利率(%) */ private Double grossProfitRate; /** * 每股收益 */ private Double eps; /** * 营业收入(百万元) */ private Double businessIncome; /** * 每股主营业务收入(元) */ private Double bips; /************************************************* * 营运能力 * *************************************************/ /** * 应收账款周转率(次) */ private Double arturnover; /** * 存货周转率(次) */ private Double inventoryTurnover; /** * 存货周转天数(天) */ private Double inventoryDays; /** * 流动资产周转率(次) */ private Double currentassetTurnover; /** * 流动资产周转天数(天) */ private Double currentassetDays; /** * 应收账款周转天数(天) */ private Double arturndays; /************************************************* * 成长能力 * *************************************************/ /** * 主营业务收入增长率(%) */ private Double mbrg; /** * 净利润增长率(%) */ private Double nprg; /** * 净资产增长率 */ private Double nav; /** * 总资产增长率 */ private Double targ; /** * 每股收益增长率 */ private Double epsg; /** * 股东权益增长率 */ private Double seg; /************************************************* * 偿债能力 * *************************************************/ /** * 流动比率 */ private Double currentRatio; /** * 速动比率 */ private Double quickRatio; /** * 利息支付倍数 */ private Double icRatio; /** * 股东权益比率 */ private Double sheqRatio; /** * 股东权益增长率 */ private Double adRatio; /** * 现金比率 */ private Double cashRatio; /************************************************* * 现金流量 * *************************************************/ /** * 经营现金净流量对销售收入比率 */ private Double cfSales; /** * 资产的经营现金流量回报率 */ private Double rateOfReturn; /** * 经营现金净流量与净利润的比率 */ private Double cfNm; /** * 经营现金净流量对负债比率 */ private Double cfLiabilities; /** * 现金流量比率 */ private Double cashflowRatio; @Id @Column(name = "StockID") public String getStockId() { return stockId; } public void setStockId(String stockId) { this.stockId = stockId; } @Id @Column(name = "QuarterOfYear") public String getQuarterOfYear() { return quarterOfYear; } public void setQuarterOfYear(String quarterOfYear) { this.quarterOfYear = quarterOfYear; } @Basic @Column(name = "Esp") public Double getEsp() { return esp; } public void setEsp(Double esp) { this.esp = esp; } @Basic @Column(name = "Bvps") public Double getBvps() { return bvps; } public void setBvps(Double bvps) { this.bvps = bvps; } @Basic @Column(name = "Roe") public Double getRoe() { return roe; } public void setRoe(Double roe) { this.roe = roe; } @Basic @Column(name = "Net_profits") public Double getNetProfits() { return netProfits; } public void setNetProfits(Double netProfits) { this.netProfits = netProfits; } @Basic @Column(name = "Profits_yoy") public Double getProfitsYoy() { return profitsYoy; } public void setProfitsYoy(Double profitsYoy) { this.profitsYoy = profitsYoy; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StockBasicInfoPO that = (StockBasicInfoPO) o; if (stockId != null ? !stockId.equals(that.stockId) : that.stockId != null) return false; if (quarterOfYear != null ? !quarterOfYear.equals(that.quarterOfYear) : that.quarterOfYear != null) return false; if (esp != null ? !esp.equals(that.esp) : that.esp != null) return false; if (bvps != null ? !bvps.equals(that.bvps) : that.bvps != null) return false; if (roe != null ? !roe.equals(that.roe) : that.roe != null) return false; if (netProfits != null ? !netProfits.equals(that.netProfits) : that.netProfits != null) return false; if (profitsYoy != null ? !profitsYoy.equals(that.profitsYoy) : that.profitsYoy != null) return false; return true; } @Override public int hashCode() { int result = stockId != null ? stockId.hashCode() : 0; result = 31 * result + (quarterOfYear != null ? quarterOfYear.hashCode() : 0); result = 31 * result + (esp != null ? esp.hashCode() : 0); result = 31 * result + (bvps != null ? bvps.hashCode() : 0); result = 31 * result + (roe != null ? roe.hashCode() : 0); result = 31 * result + (netProfits != null ? netProfits.hashCode() : 0); result = 31 * result + (profitsYoy != null ? profitsYoy.hashCode() : 0); return result; } @Basic @Column(name = "Net_profit_ratio") public Double getNetProfitRatio() { return netProfitRatio; } public void setNetProfitRatio(Double netProfitRatio) { this.netProfitRatio = netProfitRatio; } @Basic @Column(name = "Gross_profit_rate") public Double getGrossProfitRate() { return grossProfitRate; } public void setGrossProfitRate(Double grossProfitRate) { this.grossProfitRate = grossProfitRate; } @Basic @Column(name = "Eps") public Double getEps() { return eps; } public void setEps(Double eps) { this.eps = eps; } @Basic @Column(name = "Business_income") public Double getBusinessIncome() { return businessIncome; } public void setBusinessIncome(Double businessIncome) { this.businessIncome = businessIncome; } @Basic @Column(name = "Bips") public Double getBips() { return bips; } public void setBips(Double bips) { this.bips = bips; } @Basic @Column(name = "Arturnover") public Double getArturnover() { return arturnover; } public void setArturnover(Double arturnover) { this.arturnover = arturnover; } @Basic @Column(name = "Inventory_turnover") public Double getInventoryTurnover() { return inventoryTurnover; } public void setInventoryTurnover(Double inventoryTurnover) { this.inventoryTurnover = inventoryTurnover; } @Basic @Column(name = "Inventory_days") public Double getInventoryDays() { return inventoryDays; } public void setInventoryDays(Double inventoryDays) { this.inventoryDays = inventoryDays; } @Basic @Column(name = "Currentasset_turnover") public Double getCurrentassetTurnover() { return currentassetTurnover; } public void setCurrentassetTurnover(Double currentassetTurnover) { this.currentassetTurnover = currentassetTurnover; } @Basic @Column(name = "Currentasset_days") public Double getCurrentassetDays() { return currentassetDays; } public void setCurrentassetDays(Double currentassetDays) { this.currentassetDays = currentassetDays; } @Basic @Column(name = "Arturndays") public Double getArturndays() { return arturndays; } public void setArturndays(Double arturndays) { this.arturndays = arturndays; } @Basic @Column(name = "Mbrg") public Double getMbrg() { return mbrg; } public void setMbrg(Double mbrg) { this.mbrg = mbrg; } @Basic @Column(name = "Nprg") public Double getNprg() { return nprg; } public void setNprg(Double nprg) { this.nprg = nprg; } @Basic @Column(name = "Nav") public Double getNav() { return nav; } public void setNav(Double nav) { this.nav = nav; } @Basic @Column(name = "Targ") public Double getTarg() { return targ; } public void setTarg(Double targ) { this.targ = targ; } @Basic @Column(name = "Epsg") public Double getEpsg() { return epsg; } public void setEpsg(Double epsg) { this.epsg = epsg; } @Basic @Column(name = "Seg") public Double getSeg() { return seg; } public void setSeg(Double seg) { this.seg = seg; } @Basic @Column(name = "CurrentRatio") public Double getCurrentRatio() { return currentRatio; } public void setCurrentRatio(Double currentRatio) { this.currentRatio = currentRatio; } @Basic @Column(name = "QuickRatio") public Double getQuickRatio() { return quickRatio; } public void setQuickRatio(Double quickRatio) { this.quickRatio = quickRatio; } @Basic @Column(name = "IcRatio") public Double getIcRatio() { return icRatio; } public void setIcRatio(Double icRatio) { this.icRatio = icRatio; } @Basic @Column(name = "SheqRatio") public Double getSheqRatio() { return sheqRatio; } public void setSheqRatio(Double sheqRatio) { this.sheqRatio = sheqRatio; } @Basic @Column(name = "AdRatio") public Double getAdRatio() { return adRatio; } public void setAdRatio(Double adRatio) { this.adRatio = adRatio; } @Basic @Column(name = "CashRatio") public Double getCashRatio() { return cashRatio; } public void setCashRatio(Double cashRatio) { this.cashRatio = cashRatio; } @Basic @Column(name = "Cf_sales") public Double getCfSales() { return cfSales; } public void setCfSales(Double cfSales) { this.cfSales = cfSales; } @Basic @Column(name = "RateOfReturn") public Double getRateOfReturn() { return rateOfReturn; } public void setRateOfReturn(Double rateOfReturn) { this.rateOfReturn = rateOfReturn; } @Basic @Column(name = "Cf_nm") public Double getCfNm() { return cfNm; } public void setCfNm(Double cfNm) { this.cfNm = cfNm; } @Basic @Column(name = "Cf_liabilities") public Double getCfLiabilities() { return cfLiabilities; } public void setCfLiabilities(Double cfLiabilities) { this.cfLiabilities = cfLiabilities; } @Basic @Column(name = "CashflowRatio") public Double getCashflowRatio() { return cashflowRatio; } public void setCashflowRatio(Double cashflowRatio) { this.cashflowRatio = cashflowRatio; } } <file_sep>import sys import tushare as ts df = ts.get_latest_news(top=80, show_content=True) path = sys.argv[1] df.to_csv(path, encoding="utf8") <file_sep>import sys import tushare as ts df = ts.get_today_all() print df path = sys.argv[1] df.to_csv(path, encoding="utf8") <file_sep>package ui.singleStock; import bl.stock.StockBL; import bl.stock.StockBLService; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import ui.*; import ui.charts.AdvCandleStickChart; import ui.util.AutoCloseStage; import ui.util.DatePickerSettings; import ui.util.SearchNotificatePane; import vo.DailyAverageVO; import vo.KLineVO; import vo.SearchVO; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.ZoneId; import java.util.Date; import java.util.List; /** * Created by st on 2017/3/4. */ public class StockInfoViewController implements ControlledStage { private StageController stageController = new StageController(); final private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private List<KLineVO> kLineVOS; private List<List<DailyAverageVO>> average; @FXML private Button confirmButton; @FXML private DatePicker startDate; @FXML private DatePicker endDate; @FXML private TextField stockID; @FXML private Label stockIDLabel; @FXML private Label stockNameLabel; @FXML private Pane kLinePane; @FXML private Pane searchPane; @FXML private Pane loadingPane; @FXML private Pane searchNotificationPane; @FXML private ScrollPane searchScrollPane; @FXML private Label nullLabel; public void setStageController(StageController stageController) { this.stageController = stageController; } /** * 确认按钮方法 * 点击后进行 搜索 */ @FXML private void confirm() { if (stockID.getText().equals("")) { AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("请输入股票代码或名称"); } else { StockBLService stockBL = new StockBL(); try { kLineVOS = stockBL.getKLineInfo(getSearchVO()); average = stockBL.getDailyAverageInfo(getSearchVO()); setStockInfo(); } catch (Exception e) { //无股票信息 AutoCloseStage autoCloseStage = new AutoCloseStage(); autoCloseStage.showErrorBox("找不到数据"); } } searchScrollPane.setVisible(false); } /** * 股票信息界面初始化方法 * 设置搜索界面传来的参数 * * @param searchVO */ public void init(SearchVO searchVO, List<KLineVO> kLines, List<List<DailyAverageVO>> ave) { ZoneId zone = ZoneId.systemDefault(); DatePickerSettings datePickerSettings = new DatePickerSettings(); startDate.setDayCellFactory(datePickerSettings.getStartSettings(startDate)); endDate.setDayCellFactory(datePickerSettings.getEndSettings(startDate, endDate)); //设置上一界面所选日期信息及股票信息 startDate.setValue(searchVO.startDate.toInstant().atZone(zone).toLocalDate()); endDate.setValue(searchVO.endDate.toInstant().atZone(zone).toLocalDate()); stockID.setText(searchVO.stock1); //设置股票信息 kLineVOS = kLines; average = ave; if (!kLineVOS.isEmpty()) { stockNameLabel.setText(kLineVOS.get(0).stockName); stockIDLabel.setText(kLineVOS.get(0).stockCode); } setStockInfo(); // 键盘监听,回车键发起搜索 searchPane.setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { confirm(); } }); SearchNotificatePane searchNotificatePane = new SearchNotificatePane(stockID, searchNotificationPane, nullLabel, searchScrollPane); searchNotificatePane.setTextField(150, 25, 90); } /** * 设置股票信息 */ private void setStockInfo() { stockNameLabel.setText(kLineVOS.get(0).stockName); stockIDLabel.setText(kLineVOS.get(0).stockCode); Platform.runLater(new Runnable() { @Override public void run() { //获得kline数据大小 int num = kLineVOS.size(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); //记录数据 分别为open close high low double[][] data = new double[num][5]; //记录日期 double[] dates = new double[num]; String[] ds = new String[num]; String d; for (int i = 0; i < num; i++) { d = sdf.format(kLineVOS.get(i).date); ds[i] = d; data[i][1] = kLineVOS.get(i).open; data[i][2] = kLineVOS.get(i).close; data[i][3] = kLineVOS.get(i).high; data[i][4] = kLineVOS.get(i).low; } //获得均线图信息 DecimalFormat df = new DecimalFormat("#.000"); if (!average.isEmpty()) { double[][] ave = new double[num][6]; for (int i = 0; i < num; i++) { for (int j = 0; j < 6; j++) { ave[i][j] = 0; } } for (int i = 0; i < average.size(); i++) { int length = average.get(i).size() - 1; for (int j = num - 1; j > num - average.get(i).size() - 1 && j >= 0; j--) { String s = df.format(average.get(i).get(length).average); ave[j][i] = Double.parseDouble(s); length--; } } //绘制均线图 kLinePane.getChildren().clear(); Task<Void> task1 = new Task<Void>() { @Override protected Void call() throws Exception { Platform.runLater(new Runnable() { @Override public void run() { kLinePane.getStylesheets().add("ui/Ensemble_AdvCandleStickChart.css"); kLinePane.getChildren().add(new AdvCandleStickChart(data, ds, ave)); } }); return null; } }; Thread thread1 = new Thread(task1); thread1.start(); closeLoading(); } } }); } public void closeLoading() { Platform.runLater(() -> loadingPane.setLayoutY(720)); } /** * 按钮响应设置 */ @FXML private void turnRed() { confirmButton.setStyle("-fx-text-fill: #d97555; -fx-background-color: transparent; -fx-border-color: #d97555; -fx-border-width: 1"); } @FXML private void turnWhite() { confirmButton.setStyle("-fx-text-fill: #689cc4; -fx-background-color: transparent; -fx-border-color: #689cc4; -fx-border-width: 1"); } /** * 获得SearchVO * * @return */ private SearchVO getSearchVO() { DatePickerSettings datePickerSettings = new DatePickerSettings(); Date sDate = datePickerSettings.getDate(startDate); Date eDate = datePickerSettings.getDate(endDate); return new SearchVO(stockID.getText(), "", sDate, eDate); } /** * 开始时间选择器监听,选择开始时间后,结束时间默认为开始时间的后两个月 */ @FXML private void changeEndDate() { ZoneId zone = ZoneId.systemDefault(); try { if (startDate.getValue().plusMonths(2). isAfter(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate())) { // 若开始时间的两个月后在2014/12/31之后,则设置结束时间为2014/12/31 endDate.setValue(sdf.parse("2014-4-29").toInstant().atZone(zone).toLocalDate()); } else { endDate.setValue(startDate.getValue().plusMonths(2)); } } catch (ParseException e) { e.printStackTrace(); } } } <file_sep>package data.dataImpl; import data.dataHelper.StockInfoReader; import data.dataService.StockPlateDataService; import po.PlatePO; import po.SearchPO; import po.Stock; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by Pxr on 2017/3/23. */ public class StockPlateDataServiceImpl implements StockPlateDataService { private StockDataServiceImpl stockDataService; public StockPlateDataServiceImpl() { stockDataService = new StockDataServiceImpl(); } @Override public List<List<Stock>> getStockInStockPlate(SearchPO searchPO) { List<String> stockCodeList = getAllStockInfoInPlate(searchPO.getPlateName()); List<List<Stock>> allStock = new ArrayList<>(); for (String stockInfo : stockCodeList) { String stockCode = stockInfo.split(";")[0]; List<Stock> stockList = stockDataService.searchStock(new SearchPO(stockCode, searchPO.getStartDate(), searchPO.getEndDate())); if (stockList.size() > 0) { allStock.add(stockList); } } return allStock; } /** * 按照股票的信息(名称或股票号)获得它所在的板块 * 如果该股票不属于任何板块,则返回"" * * @param stockInfo 股票名或号码 * @return 板块名 */ public String getStockPlate(String stockInfo) { String plateFilePath = System.getProperty("user.dir") + "/datasource/plate";//板块路径 List<File> plateFileList = getFile(plateFilePath);//获得板块路径下所有板块文件 BufferedReader bufferedReader = null; try { for (File plateFile : plateFileList) {//循环所有文件 bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(plateFile))); String str = null; while ((str = bufferedReader.readLine()) != null) { String stockCode = str.split(";")[0];//股票号码 String stockName = str.split(";")[1];//股票名称 if (stockInfo.equals(stockCode) && stockInfo.equals(stockName)) {//只要股票信息等于其中任何一项,则返回该文件名,去掉txt后缀 return plateFile.getName().split(".")[0]; } } bufferedReader.close();//关闭读取流 } } catch (IOException e) { e.printStackTrace(); } return "";//若板块不属于任何股票,返回"" } /** * 读取一个文件夹下的所有txt结尾的文件 * * @param dicName 文件夹的路径 * @return 所有txt结尾的文件 */ private List<File> getFile(String dicName) { File dir = new File(dicName); File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组 List<File> fileList = new ArrayList<>(); for (File file : files) { if (file.getName().endsWith("txt")) fileList.add(file); } return fileList; } @Override public List<String> getAllStockInfoInPlate(String plateName) { File f = new File(System.getProperty("user.dir") + "/datasource/plate/" + plateName + ".txt"); List<String> stockInfoList = new ArrayList<>(); if (!f.exists()) return new ArrayList<>(); else { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String str = null; while ((str = bufferedReader.readLine()) != null) { stockInfoList.add(str.split(";")[0] + ";" + str.split(";")[1]); } return stockInfoList; } catch (IOException e) { e.printStackTrace(); } } return stockInfoList; } @Override public List<PlatePO> getPlateReturnRate(SearchPO searchPO) { BufferedReader bufferedReader = null; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy"); List<PlatePO> platePOS = new ArrayList<>(); try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(System.getProperty("user.dir") + "/datasource/plate/" + searchPO.getPlateName() + "指.txt")))); String str = null; while ((str = bufferedReader.readLine()) != null) { Date date = simpleDateFormat.parse(str.split(";")[0]); double rate = Double.parseDouble(str.split(";")[1]); if ((date.equals(searchPO.getStartDate()) || date.after(searchPO.getStartDate())) && (date.equals(searchPO.getEndDate()) || date.before(searchPO.getEndDate()))) { platePOS.add(new PlatePO(date, rate)); } } } catch (ParseException e2) { e2.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return platePOS; } } <file_sep>package ui.charts; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.Pane; import vo.StockNameVO; import vo.StockVO; import java.text.DecimalFormat; import java.util.List; /** * Created by island on 2017/4/8. */ public class SingleTableViewOfStockInfo extends Pane { private final TableView<StockNameVO> table = new TableView(); /** * 根据传入的股票列表构造出表格 * * @param stocks */ public SingleTableViewOfStockInfo(List<String> stocks) { // 新建列 TableColumn<StockNameVO,String> idColumn = new TableColumn<>("股票编号"); idColumn.setPrefWidth(275); TableColumn<StockNameVO, String> nameColumn = new TableColumn<>("股票名称"); nameColumn.setPrefWidth(275); // 传入数据 ObservableList<StockNameVO> stockNames = FXCollections.observableArrayList(); for (int i = 0; i < stocks.size(); i++) { stockNames.add(new StockNameVO(stocks.get(i).split(";")[0], stocks.get(i).split(";")[1])); } idColumn.setCellValueFactory(new PropertyValueFactory<>("specCode")); nameColumn.setCellValueFactory(new PropertyValueFactory<>("specName")); // 设置成不能排序 idColumn.setSortable(false); nameColumn.setSortable(false); table.getColumns().addAll(idColumn, nameColumn); table.setItems(stockNames); table.setEditable(false); // 设置样式 table.getStylesheets().add("ui/MyTableView2.css"); table.setPrefSize(575, 240); getChildren().add(table); } } <file_sep>import bl.stock.StockBL; import org.junit.Before; import org.junit.Test; import vo.DailyAverageVO; import vo.KLineVO; import vo.SearchVO; import vo.StockCompareVO; import java.util.Date; import java.util.List; /** * stockBL的测试类 * Created by Pxr on 2017/3/9. */ public class StockBLTest { private StockBL stockBL; @Before public void setUpBeforeClass() throws Exception { stockBL = new StockBL(); } @Test public void testGetKlineInfo() { List<KLineVO> kLineVOList = null; try { kLineVOList = stockBL.getKLineInfo(new SearchVO("155", "", new Date(2014 - 1900, 4 - 1, 28), new Date(2014 - 1900, 4 - 1, 29))); } catch (Exception e) { System.out.println("in StockBLTest, line 31: no such stock!!!"); } org.junit.Assert.assertEquals(2, kLineVOList.size()); } @Test public void testGetDailyAverageInfo() { List<List<DailyAverageVO>> list = stockBL.getDailyAverageInfo(new SearchVO("155", "", new Date(2014 - 1900, 4 - 1, 28), new Date(2014 - 1900, 4 - 1, 29))); org.junit.Assert.assertEquals(6, list.size()); List<List<DailyAverageVO>> list2 = stockBL.getDailyAverageInfo(new SearchVO("155", "", new Date(2005 - 1900, 2 - 1, 1), new Date(2006 - 1900, 12 - 1, 29))); org.junit.Assert.assertEquals(6,list2.size()); } @Test public void testCompareStock() { List<StockCompareVO> list = null; try { list = stockBL.compareStock(new SearchVO("155","1", new Date(2014 - 1900, 4 - 1, 28), new Date(2014 - 1900, 4 - 1, 29))); } catch (Exception e) { System.out.println("in StockBLTest, line 53: no such stock!!"); } org.junit.Assert.assertEquals(list.size(),2); } } <file_sep>package bl.strategy.statistics; import bl.tools.Calculator; import vo.BackTestingSingleChartVO; import vo.StrategyStatisticsVO; import java.util.*; /** * 获得统计数据 * <p> * Created by keenan on 28/03/2017. */ public class BackTestStatisticsBLHelper { private List<BackTestingSingleChartVO> backTestResult; private double annualizedReturnRate; private double stdAnnualizedReturnRate; private double beta; private double algorithmVolatility; public BackTestStatisticsBLHelper(List<BackTestingSingleChartVO> backTestResult) { this.backTestResult = backTestResult; calBasicElements(); } /** * 计算基本的四个数据:年化收益率、基准年化收益率、贝塔、策略波动率 */ private void calBasicElements() { annualizedReturnRate = getAnnualizedReturnRate(); stdAnnualizedReturnRate = getStdAnnualizedReturnRate(); beta = getBeta(); algorithmVolatility = getAlgorithmVolatility(); } /** * 得到回测统计数据 * * @return */ public StrategyStatisticsVO getStatistics() { // 年化收益率 double annualizedReturnRate = this.annualizedReturnRate; // 基准年化收益率 double stdAnnualizedReturnRate = this.stdAnnualizedReturnRate; // 阿尔法 double alpha = getAlpha(); // 贝塔 double beta = this.beta; // 夏普比率 double sharpe = getSharpe(); // 信息比率 double informationRatio = getInformationRatio(); // 策略收益波动率 double algorithmVolatility = this.algorithmVolatility; // 基准收益波动率 double benchmarkVolatility = getBenchmarkVolatility(); // 最大回撤 double maxDrawdown = getMaxDrawdown(); return new StrategyStatisticsVO(annualizedReturnRate, stdAnnualizedReturnRate, alpha, beta, sharpe, informationRatio, algorithmVolatility, benchmarkVolatility, maxDrawdown); } /** * 得到阿尔法值 * Alpha是投资者获得与市场波动无关的回报,比如投资者获得了15%的回报,其基准获得了10%的回报,那么Alpha或者价值增值的部分就是5% * * @return alpha */ private double getAlpha() { return this.annualizedReturnRate - (0.04 + this.beta * (this.stdAnnualizedReturnRate - 0.04)); } /** * 得到贝塔值 * 表示投资的系统性风险,反映了策略对大盘变化的敏感性。 * 例如一个策略的Beta为1.5,则大盘涨1%的时候,策略可能涨1.5%,反之亦然; * 如果一个策略的Beta为-1.5,说明大盘涨1%的时候,策略可能跌1.5%,反之亦然。 * * @return beta */ private double getBeta() { // 策略每日收益 List<Double> strategyDailyReturn = new ArrayList<>(); // 基准每日收益 List<Double> stdDailyReturn = new ArrayList<>(); // // System.out.println("****************** Statistics *******************"); for (BackTestingSingleChartVO backTestingSingleChartVO : backTestResult) { stdDailyReturn.add(backTestingSingleChartVO.stdValue); strategyDailyReturn.add(backTestingSingleChartVO.backTestValue); // System.out.println("zqh3 benchmark: " + backTestingSingleChartVO.stdValue); // System.out.println("zqh3 back test: " + backTestingSingleChartVO.backTestValue); } // 策略每日收益与基准每日收益的协方差 double cov = Calculator.cov(stdDailyReturn, strategyDailyReturn); // 基准每日收益的方差 double variance = Calculator.variance(stdDailyReturn); return (cov / variance); } /** * 得到夏普比率 * 表示每承受一单位总风险,会产生多少的超额报酬,可以同时对策略的收益与风险进行综合考虑。 * * @return 夏普比率 */ private double getSharpe() { return (this.annualizedReturnRate - 0.04) / this.algorithmVolatility; } /** * 得到策略年化收益率 * * @return 策略年化收益率 */ private double getAnnualizedReturnRate() { // 回测期内策略的收益率,即回测期最后一天的策略收益率 double lastDayBackTestValue = backTestResult.get(backTestResult.size() - 1).backTestValue; // 策略执行天数 int days = backTestResult.size(); double annualizedReturnRate; annualizedReturnRate = Math.pow((1 + lastDayBackTestValue), (250.0 / days)) - 1; return annualizedReturnRate; } /** * 得到基准年化收益率 * * @return 基准年化收益率 */ private double getStdAnnualizedReturnRate() { // 回测期内基准的收益率,即回测期最后一天的基准收益率 double lastDayStdValue = backTestResult.get(backTestResult.size() - 1).stdValue; // 策略执行天数 int days = backTestResult.size(); double stdAnnualizedReturnRate; stdAnnualizedReturnRate = Math.pow((1 + lastDayStdValue), (250.0 / days)) - 1; return stdAnnualizedReturnRate; } /** * 得到信息比率 * 衡量单位超额风险带来的超额收益。信息比率越大,说明该策略单位跟踪误差所获得的超额收益越高, * 因此,信息比率较大的策略的表现要优于信息比率较低的基准。合理的投资目标应该是在承担适度风险下,尽可能追求高信息比率。 * * @return 信息比率 */ private double getInformationRatio() { // 策略与基准的每日收益差值 List<Double> strategyMinusBenchmark = new ArrayList<>(); backTestResult.stream().forEach(result -> strategyMinusBenchmark.add(result.backTestValue - result.stdValue)); double minusStdDev = Calculator.std(strategyMinusBenchmark); double annualizedMinusStdDev = Math.sqrt(250.0 / strategyMinusBenchmark.size()) * minusStdDev; return (annualizedReturnRate - stdAnnualizedReturnRate) / annualizedMinusStdDev; } /** * 得到策略波动率 * 用来测量策略的风险性,波动越大代表策略风险越高。 * * @return 策略波动率 */ private double getAlgorithmVolatility() { List<Double> dailyStrategyReturnRate = new ArrayList<>(); backTestResult.stream().forEach(result -> dailyStrategyReturnRate.add(result.backTestValue)); double avg = Calculator.avg(dailyStrategyReturnRate); double minusSquareSum = 0; for (Double value : dailyStrategyReturnRate) { minusSquareSum += (value - avg) * (value - avg); } return Math.sqrt((250.0 / dailyStrategyReturnRate.size()) * minusSquareSum); } /** * 得到基准波动率 * 用来测量基准的风险性,波动越大代表基准风险越高。 * * @return 基准波动率 */ private double getBenchmarkVolatility() { List<Double> dailyBenchmarkReturnRate = new ArrayList<>(); backTestResult.stream().forEach(result -> dailyBenchmarkReturnRate.add(result.stdValue)); double avg = Calculator.avg(dailyBenchmarkReturnRate); double minusSquareSum = 0; for (Double value : dailyBenchmarkReturnRate) { minusSquareSum += (value - avg) * (value - avg); } return Math.sqrt((250.0 / dailyBenchmarkReturnRate.size()) * minusSquareSum); } /** * 得到最大回撤 * 描述策略可能出现的最糟糕的情况,最极端可能的亏损情况。 * 具体计算方法为 max(1 - 策略当日价值 / 当日之前虚拟账户最高价值) * * @return 最大回撤 */ private double getMaxDrawdown() { List<Double> dailyStrategyReturnRate = new ArrayList<>(); List<Double> possibleResults = new ArrayList<>(); for (BackTestingSingleChartVO backTestingSingleChartVO : backTestResult) { dailyStrategyReturnRate.add(backTestingSingleChartVO.backTestValue); } for (int currentPos = 0; currentPos < dailyStrategyReturnRate.size(); currentPos++) { double max = Double.MIN_VALUE; for (int j = 0; j < currentPos; j++) { if (dailyStrategyReturnRate.get(j) > max) { max = dailyStrategyReturnRate.get(j); } } possibleResults.add(1.0 - ((1.0 + dailyStrategyReturnRate.get(currentPos)) / (1.0 + max))); } return Calculator.max(possibleResults); } } <file_sep>package bl.tools; import po.Stock; import java.util.ArrayList; import java.util.List; /** * 把List<List<Stock>>中的股票代码信息提取出来 * Created by st on 2017/3/31. */ public class TransferNestedList { /** * 把List<List<Stock>>中的股票代码信息提取出来 * * @param stocks * @return 股票代码列表 */ public static List<String> transfer(List<List<Stock>> stocks) { List<String> stockCodes = new ArrayList<>(); for (List<Stock> stock : stocks) { stockCodes.add(stock.get(0).getCode()); } return stockCodes; } } <file_sep>package oquantour.util.tools; /** * Created by keenan on 08/06/2017. */ public enum PlateEnum { SH_Composite, // 上证指数 SmallPlate_Composite, // 中小板指 Gem_Composite, // 创业板指 SS_300, // 沪深300 SZ_Composite, // 深证成指 SZA_Composite;// 深证A指 } <file_sep>package oquantour.data.dao; import oquantour.exception.WrongCombinationException; import oquantour.po.StockCombination; import oquantour.po.StockCombinationPO; import java.util.List; import java.util.Map; /** * Created by island on 2017/6/5. */ public interface CombinationDao { /** * 增加股票组合 * @param username * @param combinationName * @param stocks * @param positions */ void addStockCombination(String username, String combinationName, List<String> stocks, List<Double> positions) throws WrongCombinationException; /** * 修改股票组合 * @param username * @param combinationName * @param stocks * @param positions */ void modifyStockCombination(String username, String combinationName, List<String> stocks, List<Double> positions) throws WrongCombinationException; /** * 删除股票组合 * @param username * @param combinationName */ void deleteStockCombination(String username, String combinationName); /** * 根据用户名和组合名获得股票组合 * @param username * @param combinationName * @return */ List<StockCombination> getStockCombination(String username, String combinationName); /** * 获得某用户所有股票组合 * @param username * @return */ Map<String, List<StockCombination>> getAllStockCombinationOfUser(String username); } <file_sep>package oquantour.po.util; import java.sql.Date; /** * Created by keenan on 07/05/2017. */ public class BackTestingSingleChartInfo { // 日期 private Date date; // 策略累积收益率 private double backTestValue; // 基准累积收益率 private double stdValue; public BackTestingSingleChartInfo() { } public BackTestingSingleChartInfo(Date date, double backTestValue, double stdValue) { this.date = date; this.backTestValue = backTestValue; this.stdValue = stdValue; } public BackTestingSingleChartInfo(ChartInfo backTest, ChartInfo benchmark) { this.date = backTest.getDateXAxis(); this.backTestValue = backTest.getyAxis(); this.stdValue = benchmark.getyAxis(); } public Date getDate() { return date; } public double getBackTestValue() { return backTestValue; } public double getStdValue() { return stdValue; } public void setDate(Date date) { this.date = date; } public void setBackTestValue(double backTestValue) { this.backTestValue = backTestValue; } public void setStdValue(double stdValue) { this.stdValue = stdValue; } } <file_sep>package oquantour.po; import java.util.List; /** * 此类PO为数据层将筛选后的股票返回给界面 * Created by Pxr on 2017/3/28. */ public class FilterStockPO { //有问题的名字列表 private List<String> stockWithProblem; //没问题的股票列表 private List<List<StockPO>> stockWithoutProblem; //无形成期的正常股票 private List<List<StockPO>> stockWithOutFormativePeriod; public List<String> getStockWithProblem() { return stockWithProblem; } public List<List<StockPO>> getStockWithoutProblem() { return stockWithoutProblem; } public FilterStockPO(List<String> stockWithProblem, List<List<StockPO>> stockWithoutProblem) { this.stockWithProblem = stockWithProblem; this.stockWithoutProblem = stockWithoutProblem; } public List<List<StockPO>> getStockWithOutFormativePeriod() { return stockWithOutFormativePeriod; } public FilterStockPO(List<String> stockWithProblem, List<List<StockPO>> stockWithoutProblem, List<List<StockPO>> stockWithOutFormativePeriod) { this.stockWithProblem = stockWithProblem; this.stockWithoutProblem = stockWithoutProblem; this.stockWithOutFormativePeriod = stockWithOutFormativePeriod; } } <file_sep>package exception; /** * Created by Pxr on 2017/4/19. */ public class NotTransactionDayException extends Exception { public NotTransactionDayException() { super(); } } <file_sep>import sys import tushare as ts df = ts.get_h_data(sys.argv[2], start=sys.argv[3], end=sys.argv[3], autype=None) path = sys.argv[1] df.to_csv(path, encoding="utf8") <file_sep>package oquantour.data.dao; import oquantour.po.PlateRealTimePO; import oquantour.po.PlateinfoPO; import oquantour.po.StockPO; import java.sql.Date; import java.util.List; import java.util.Map; /** * Created by island on 5/10/17. */ public interface PlateDao { /** * 根据板块名称,获得该段时间内存在数据的股票 * @param plateName * @param startDate * @param endDate * @return */ Map<String, List<StockPO>> getStockInStockPlate(String plateName, Date startDate, Date endDate); /** * 根据股票信息获得它所在的板块 * @param stockInfo 股票名或代码 * @return 板块名 */ String getStockPlate(String stockInfo); /** * 得到板块中的所有股票 代码;名称 * @param plateName 板块名 * @return 板块中的所有股票的stockID;stockName */ List<String> getAllStockInfoInPlate(String... plateName); /** * 获得板块一段时间内每个交易日的收益率 * @param plateName * @param startDate * @param endDate * @return */ List<PlateinfoPO> getPlateInfo(String plateName, Date startDate, Date endDate); /** * 获得所有板块名称 * @return */ List<String> getAllPlateName(); /** * 获得实时板块数据 * @return Map<板块名称, PlateRealTimePO></> */ Map<String, PlateRealTimePO> getRealTimePlateInfo(); /** * 更新实时板块数据 */ void updateRealTimePlateInfo(); /** * 添加板块信息 */ void addPlateInfo(); /** * 更新板块信息 * @param plateinfoPO */ void updatePlateInfo(PlateinfoPO plateinfoPO); } <file_sep>package data.dataImpl; import data.dataHelper.CodeNameRelation; import data.dataHelper.StockInfoReader; import data.dataService.StockDataService; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import po.CalMeanPO; import po.FilterStockPO; import po.SearchPO; import po.Stock; import java.io.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * Created by keenan on 04/03/2017. */ public class StockDataServiceImpl implements StockDataService { private List<Stock> stockList; // 储存股票号和股票名称的map,在根据姓名搜索时,将名字转换为股票号 private Map<String, String> map_code_name = null; private StockInfoReader stockInfoReader; private CodeNameRelation codeNameRelation; private Map<String, String> map_name_code = null; private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy"); public StockDataServiceImpl() { stockList = new ArrayList<>(); stockInfoReader = new StockInfoReader(); if (codeNameRelation == null) { codeNameRelation = CodeNameRelation.getInstance(); } if (map_name_code == null) { map_name_code = codeNameRelation.getNameCodeRelation(); } if (map_code_name == null) { map_code_name = codeNameRelation.getCodeNameRelation(); } } // /** // * 根据股票名称和日期范围查询股票数据 // * // * @param searchPO 要使用的属性包括"stockName","startDate","endDate" // * @return 搜索结果 // */ // public List<Stock> searchStockByNameAndDateRange(SearchPO searchPO) { // String code = map_code_name.get(searchPO.getStockInfo()); // // if (code == null) { // return new ArrayList<>(); // } // // SearchPO newPo = new SearchPO(code, searchPO.getStartDate(), searchPO.getEndDate()); // // return searchStock(newPo); // } /** * 根据股票代码和日期范围查询股票数据 * * @param searchPO 要使用的属性包括"stockCode","startDate","endDate" * @return 搜索结果 */ public List<Stock> searchStock(SearchPO searchPO) { List<String> stockCode = new ArrayList<>(); stockCode.add(searchPO.getStockInfo()); List<Stock> possibleStocks = stockInfoReader.readStockInfo(0, getStockCode(stockCode).get(0)); List<Stock> stocksMatch = new ArrayList<>(); for (int i = 0; i < possibleStocks.size(); i++) { Stock stock = possibleStocks.get(i); Date thisDate = stock.getDate(); Date startDate = searchPO.getStartDate(); Date endDate = searchPO.getEndDate(); if (thisDate.equals(startDate) || thisDate.equals(endDate) || (thisDate.after(startDate) && thisDate.before(endDate))) { stocksMatch.add(stock); } } Collections.reverse(stocksMatch); return stocksMatch; } /** * 根据日期搜索市场中所有股票的信息 * * @param searchPO 要使用的属性仅包括startDate和endDate * endDate和startDate必须相同,否则将返回一个空的列表 * @return 搜索结果 */ public List<Stock> searchAllStocksByDate(SearchPO searchPO) { ArrayList<Stock> stocksFound = new ArrayList<>(); if (!searchPO.getStartDate().equals(searchPO.getEndDate())) { return stocksFound; } Date searchDate = searchPO.getEndDate(); List<Stock> stocksByYear = stockInfoReader.readStockInfo(1, String.valueOf(searchDate.getYear())); if (stocksByYear.isEmpty()) { return stocksFound; } for (Stock stock : stocksByYear) { if (stock.getDate().equals(searchDate)) { stocksFound.add(stock); } } return stocksFound; } /** * 得到股票代码(无论传入的是股票名还是股票代码) * * @param stockInfoList 股票名或股票代码 * @return 股票代码 */ @Override public List<String> getStockCode(List<String> stockInfoList) { // 股票号码的正则表达式 String stockCodeCriteria = "^[0-9]*$"; // 转化后的股票号码 List<String> codeList = new ArrayList<>(); for (String s : stockInfoList) { if (s.matches(stockCodeCriteria)) { codeList.add(s); } else { String code = map_code_name.get(s); if (code == null) { continue; } codeList.add(map_code_name.get(s)); } } return codeList; } public String getStockCode(String stockInfo) { String stockCodeCriteria = "^[0-9]*$"; if (stockInfo.matches(stockCodeCriteria)) { return stockInfo; } else { String code = map_code_name.get(stockInfo); if (code == null) { return null; } return (map_code_name.get(stockInfo)); } } /** * 得到所有的股票代码和名字,格式为"名字;代码" * * @return 所有的股票代码和名字,格式为"名字;代码" */ public List<String> getAllStockCodeAndName() { BufferedReader bufferedReader = null; String temp = System.getProperty("user.dir") + "/datasource/allStocks.txt"; // String temp = String.valueOf(getClass().getResource("/")); File allStocks = new File(temp); // System.out.println("=============================="+temp+"==============================="); List<String> strings = new ArrayList<>(); try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(allStocks))); String str = null; while ((str = bufferedReader.readLine()) != null) { strings.add(str); } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } return strings; } /** * 筛选掉没有数据的股票,如果不需要形成期长度,那长度就是0,如果不需要均值日期长度,那长度就是0 * * @param stockList 股票列表 * @param startDate 开始日期 * @param endDate 结束日期 * @param formativePeriod 形成期长度 * @return 有数据的股票和没有数据的股票 */ public FilterStockPO filterStockWithoutData(List<String> stockList, Date startDate, Date endDate, int formativePeriod) { List<String> stockWithProblem = new ArrayList<>(); List<List<Stock>> stockWithoutProblem = new ArrayList<>(); List<Date> transactionDateList = stockInfoReader.readTransactionDays(); Date formativeStartDay = transactionDateList.get(transactionDateList.indexOf(getTransactionDateAfterStartDate(startDate)) + formativePeriod);//形成期开始的日期 if (formativeStartDay == null) { return null; } else { Map<String, List<Stock>> map = stockInfoReader.readManyStocks(stockList, formativeStartDay, endDate); for (String s : map.keySet()) { if (map.get(s).size() > formativePeriod) { stockWithoutProblem.add(map.get(s)); } else { stockWithProblem.add(s + ";" + map_name_code.get(s)); } } return new FilterStockPO(stockWithProblem, stockWithoutProblem); } } /** * 筛选掉停牌的股票 * * @param stockList 股票列表 * @param startDate 开始日期 * @param endDate 结束日期 * @param formativePeriod 形成期长度 * @return 停牌的股票和没有停牌的股票 */ public FilterStockPO filterStockHalt(List<List<Stock>> stockList, Date startDate, Date endDate, int formativePeriod) { List<String> stockWithProblem = new ArrayList<>(); List<List<Stock>> stockWithoutProblem = new ArrayList<>(); // List<Date> transactionDateList = stockInfoReader.readTransactionDays(); // Date formativeStartDay = transactionDateList.get(transactionDateList.indexOf(getTransactionDateAfterStartDate(startDate)) + formativePeriod); // int transactionDays = 0; // for (Date date : transactionDateList) {//目的是得出开始日期到结束日期之间交易日的长度 // // if ((date.equals(endDate) || date.before(endDate)) && (date.equals(formativeStartDay) || date.after(formativeStartDay))) { // transactionDays++; // } // } // for (List<Stock> stocks : stockList) { // if (stocks.size() > 0) { //// System.out.println(stocks.size()+" "+stocks.get(0).getName()+" "+stocks.get(0).getDate()); // if (stocks.size() == transactionDays) // stockWithoutProblem.add(stocks); // else // stockWithProblem.add(stocks.get(0).getCode()+";"+stocks.get(0).getName()); // } // } List<List<Stock>> stockWithOutFormativePeriod = new ArrayList<>(); for (List<Stock> stocks : stockList) { boolean isHalt = false; for (Stock stock : stocks) { if (stock.getVolume() == 0) { stockWithProblem.add(stock.getCode() + ";" + stock.getName()); isHalt = true; break; } } if (!isHalt) { stockWithoutProblem.add(stocks); List<Stock> temp = new ArrayList<>(); for (Stock s : stocks) { if (!s.getDate().before(startDate)) temp.add(s); } stockWithOutFormativePeriod.add(temp); } } return new FilterStockPO(stockWithProblem, stockWithoutProblem, stockWithOutFormativePeriod); } /** * 获得开始日期后的第一个交易日 * * @param startDate 开始日期 * @return 开始日期后的第一个交易日 */ private Date getTransactionDateAfterStartDate(Date startDate) { List<Date> transactionDateList = stockInfoReader.readTransactionDays(); for (int i = 0; i < transactionDateList.size() - 1; i++) { if (startDate.after(transactionDateList.get(i + 1)) && startDate.before(transactionDateList.get(i))) return transactionDateList.get(i); else if (startDate.equals(transactionDateList.get(i))) return startDate; } return null; } /** * 得到一段时间内所有股票信息 * * @param searchPO 开始日期,结束日期 * @return 所有股票信息 */ public List<List<Stock>> getAllStockInfo(SearchPO searchPO) { List<List<Stock>> allStockList = new ArrayList<>(); List<String> allCodeAndName = getAllStockCodeAndName(); for (String str : allCodeAndName) { allStockList.add(searchStock(new SearchPO(str.split(";")[0], searchPO.getStartDate(), searchPO.getEndDate()))); } return allStockList; } public CalMeanPO getStockListForMean(SearchPO searchPO, int days) { if (getStockCode(searchPO.getStockInfo()) == null) { return new CalMeanPO(new ArrayList<>(), new ArrayList<>()); } String code = getStockCode(searchPO.getStockInfo()); File f = new File(System.getProperty("user.dir") + "/datasource/stocks/" + code.substring(0, 1) + "/" + code + ".txt"); try { List<String> strings = FileUtils.readLines(f); List<Stock> stockList = new ArrayList<>(); List<Stock> beforeStockList = new ArrayList<>(); int startIndex = 0; for (int i = 0, size = strings.size(); i < size; i++) { String[] s = StringUtils.split(strings.get(i), ";"); Date date = simpleDateFormat.parse(s[1]); if (date.before(searchPO.getStartDate())) { startIndex = i; break; } else if (!date.after(searchPO.getEndDate())) { stockList.add(new Stock(strings.get(i), date)); } } Collections.reverse(stockList); if (startIndex != 0) { for (int j = startIndex, size = strings.size(); j < startIndex + days - 1 && j < size; j++) { beforeStockList.add(new Stock(strings.get(j), simpleDateFormat.parse(StringUtils.split(strings.get(j), ";")[1]))); } } Collections.reverse(beforeStockList); return new CalMeanPO(stockList, beforeStockList); } catch (IOException e) { e.printStackTrace(); } catch (ParseException p) { p.printStackTrace(); } return null; } } <file_sep>package oquantour.service.serviceImpl; import oquantour.data.dao.PlateDao; import oquantour.po.PlateRealTimePO; import oquantour.po.PlateinfoPO; import oquantour.po.util.ChartInfo; import oquantour.service.PlateService; import oquantour.util.tools.PlateEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Date; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by keenan on 10/06/2017. */ @Service @Transactional public class PlateServiceImpl implements PlateService { @Autowired PlateDao plateDao; /** * 根据板块名获得板块内股票 * * @param plateName 板块名数组 * @return 股票名;股票号 */ @Override public List<String> getStockByPlate(String... plateName) { return plateDao.getAllStockInfoInPlate(plateName); } /** * 获得所有板块名 * * @return 所有板块名 */ @Override public List<String> getAllPlateName() { return plateDao.getAllPlateName(); } /** * 获得板块收益率 * * @param startDate * @param endDate * @param plateName 板块类型 @return */ @Override public Map<String, List<ChartInfo>> getPlateReturnRates(Date startDate, Date endDate, String... plateName) { Map<String, List<ChartInfo>> map = new HashMap<>(); for (String plate : plateName) { List<PlateinfoPO> plateinfoPOS = plateDao.getPlateInfo(plate, startDate, endDate); List<ChartInfo> chartInfos = new ArrayList<>(); plateinfoPOS.stream().forEachOrdered(plateinfoPO -> chartInfos.add(new ChartInfo(plateinfoPO.getDateValue(), plateinfoPO.getReturnRate()))); map.put(plate, chartInfos); } return map; } /** * 获得实时板块数据 * * @return Map<板块名称, PlateRealTimePO></> */ @Override public Map<String, PlateRealTimePO> getRealTimePlateInfo() { return plateDao.getRealTimePlateInfo(); } } <file_sep>package oquantour.data.datagetter; import oquantour.data.dao.StockDao; import oquantour.po.StockPO; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.BufferedReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by island on 5/28/17. */ public class HistoryInfoGetter { PythonExecutor executor; Paramaters paramaters; static ClassPathXmlApplicationContext ctx; StockDao stockDao; public HistoryInfoGetter() { executor = new PythonExecutor(); paramaters = new Paramaters(); } public void addStockInfo() { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); stockDao = (StockDao) ctx.getBean("stockDao"); List<String> stocks = stockDao.getAllStockCodeAndName(); /* Thread thread = new Thread(new Runnable() { @Override public void run() { try { List<StockPO> stockPOS = new ArrayList<>(); executor.excute("StockInfoNone.py", new Object[]{Paramaters.getPath() + stocks.get(0).split(";")[0]+ ".csv", stocks.get(0).split(";")[0]}); executor.excute("StockInfo.py", new Object[]{Paramaters.getPath() + stocks.get(0).split(";")[0]+ "qfq" + ".csv", stocks.get(0).split(";")[0], "qfq"}); BufferedReader reader = Paramaters.getBufferedReader(stocks.get(0).split(";")[0]+ ".csv"); BufferedReader reader1 = Paramaters.getBufferedReader(stocks.get(0).split(";")[0]+ "qfq" + ".csv"); String tem = reader.readLine(); String tem1 = reader1.readLine(); while ((tem = reader.readLine()) != null && (tem1 = reader1.readLine()) != null) { String[] args = tem.split(","); String[] args1 = tem1.split(","); StockPO stockPO = new StockPO(); stockPO.setStockId(stocks.get(0).split(";")[0]); java.sql.Date date = new java.sql.Date(simpleDateFormat.parse(args[0]).getTime()); stockPO.setDateValue(date); stockPO.setOpenPrice(Double.parseDouble(args[1])); stockPO.setHighPrice(Double.parseDouble(args[2])); stockPO.setLowPrice(Double.parseDouble(args[4])); stockPO.setClosePrice(Double.parseDouble(args[3])); stockPO.setVolume(Double.parseDouble(args[5])); stockPO.setAmount(Double.parseDouble(args[6])); stockPO.setAdjClose(Double.parseDouble(args1[3])); stockPO.setMa5((double)(-1)); stockPO.setMa10((double)(-1)); stockPO.setMa20((double)(-1)); stockPO.setMa30((double)(-1)); stockPO.setMa60((double)(-1)); stockPO.setMa120((double)(-1)); stockPO.setMa240((double)(-1)); stockPO.setChg((double)(-1)); stockPO.setReturnRate((double)(-1)); stockPOS.add(stockPO); } calMA(stockPOS); }catch (IOException e1){ e1.printStackTrace(); }catch (InterruptedException e2){ e2.printStackTrace(); }catch (ParseException e3){ e3.printStackTrace(); } } }); thread.start(); */ int start = 0; List<Integer> wait = new ArrayList<>(); try { String stockID = stocks.get(start).split(";")[0]; executor.excute("StockInfoNone.py", new Object[]{paramaters.getPath() + stockID + ".csv", stockID}); executor.excute("StockInfo.py", new Object[]{paramaters.getPath() + stockID + "qfq" + ".csv", stockID, "qfq"}); }catch (IOException e1){ e1.printStackTrace(); }catch (InterruptedException e2){ e2.printStackTrace(); } // int threadCount = 0; // List<Thread> threads = new ArrayList<>(); // List<Integer> finishThreads = new ArrayList<>(); Thread thread = new Thread(new Runnable() { @Override public void run() { for(int i = start + 1; i < stocks.size(); i++) { try { String stockID = stocks.get(i).split(";")[0]; executor.excute("StockInfoNone.py", new Object[]{paramaters.getPath() + stockID + ".csv", stockID}); executor.excute("StockInfo.py", new Object[]{paramaters.getPath() + stockID + "qfq" + ".csv", stockID, "qfq"}); } catch (IOException e1) { e1.printStackTrace(); } catch (InterruptedException e2) { e2.printStackTrace(); } } } }); thread.start(); for (int m = start; m < stocks.size(); m++) { // System.out.print(threadCount + " " + threads.size() + " "); // System.out.println(i); try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); List<StockPO> stockPOS = new ArrayList<>(); String stockID = stocks.get(m).split(";")[0]; System.out.println(stockID); BufferedReader reader = paramaters.getBufferedReader(stockID + ".csv"); BufferedReader reader1 = paramaters.getBufferedReader(stockID + "qfq" + ".csv"); if (reader != null && reader1 != null) { String tem = reader.readLine(); String tem1 = reader1.readLine(); while ((tem = reader.readLine()) != null && (tem1 = reader1.readLine()) != null) { String[] args = tem.split(","); String[] args1 = tem1.split(","); StockPO stockPO = new StockPO(); stockPO.setStockId(stocks.get(m).split(";")[0]); java.sql.Date date = new java.sql.Date(simpleDateFormat.parse(args[0]).getTime()); stockPO.setDateValue(date); stockPO.setOpenPrice(Double.parseDouble(args[1])); stockPO.setHighPrice(Double.parseDouble(args[2])); stockPO.setLowPrice(Double.parseDouble(args[4])); stockPO.setClosePrice(Double.parseDouble(args[3])); stockPO.setVolume(Double.parseDouble(args[5])); stockPO.setAmount(Double.parseDouble(args[6])); stockPO.setAdjClose(Double.parseDouble(args1[3])); stockPO.setMa5((double) (-1)); stockPO.setMa10((double) (-1)); stockPO.setMa20((double) (-1)); stockPO.setMa30((double) (-1)); stockPO.setMa60((double) (-1)); stockPO.setMa120((double) (-1)); stockPO.setMa240((double) (-1)); stockPO.setChg((double) (-1)); stockPO.setReturnRate((double) (-1)); stockPO.setRsv((double) (-1)); stockPO.setMb((double)(-1)); stockPO.setUp((double)(-1)); stockPO.setDn((double)(-1)); stockPO.setkValue((double) (50)); stockPO.setdValue((double) (50)); stockPO.setjValue((double) (50)); stockPO.setEma12((double) (0)); stockPO.setEma26((double) (0)); stockPO.setDea((double) (0)); stockPOS.add(stockPO); } StockPO stockPO; int count; for (int i = stockPOS.size() - 1; i >= 0; i--) { count = stockPOS.size() - 1 - i; stockPO = stockPOS.get(i); if (count >= 4) { stockPO.setMa5(maValue(i, 5, stockPOS)); } if (count >= 9) { stockPO.setMa10(maValue(i, 10, stockPOS)); } if (count >= 19) { double avg = maValue(i, 20, stockPOS); stockPO.setMa20(avg); double sum = 0; double md = 0; for (int k = i; k < i + 20; k++) { sum += Math.pow(stockPOS.get(k).getClosePrice() - avg, 2); } md = Math.sqrt(sum / 20); double mb = maValue(i, 19, stockPOS); stockPO.setMb(mb); double up = mb + 2 * md; stockPO.setUp(up); double dn = mb - 2 * md; stockPO.setDn(dn); } if (count >= 29) { stockPO.setMa30(maValue(i, 30, stockPOS)); } if (count >= 59) { stockPO.setMa60(maValue(i, 60, stockPOS)); } if (count >= 119) { stockPO.setMa120(maValue(i, 120, stockPOS)); } if (count >= 239) { stockPO.setMa240(maValue(i, 240, stockPOS)); } if (stockPO.getHighPrice().doubleValue() != stockPO.getLowPrice().doubleValue()) stockPO.setRsv(((stockPO.getClosePrice() - stockPO.getLowPrice()) / (stockPO.getHighPrice() - stockPO.getLowPrice())) * 100); else stockPO.setRsv((double) (0)); if (i < stockPOS.size() - 1) { stockPO.setReturnRate(Math.log(stockPOS.get(i).getAdjClose() / stockPOS.get(i + 1).getAdjClose())); stockPO.setChg((stockPOS.get(i).getAdjClose() - stockPOS.get(i + 1).getAdjClose()) / stockPOS.get(i + 1).getAdjClose()); //计算kdj stockPO.setkValue((2 * stockPOS.get(i + 1).getkValue() + stockPO.getRsv()) / 3); stockPO.setdValue((2 * stockPOS.get(i + 1).getdValue() + stockPO.getkValue()) / 3); stockPO.setjValue(3 * stockPO.getkValue() - 2 * stockPO.getdValue()); //计算macd stockPO.setEma12((11 * stockPOS.get(i + 1).getEma12() + 2 * stockPO.getClosePrice()) / 13); stockPO.setEma26((25 * stockPOS.get(i + 1).getEma26() + 2 * stockPO.getClosePrice()) / 27); stockPO.setDif(stockPO.getEma12() - stockPO.getEma26()); stockPO.setDea((8 * stockPOS.get(i + 1).getDea() + 2 * stockPO.getDif()) / 10); } stockPO.setDif(stockPO.getEma12() - stockPO.getEma26()); //计算rsi double up = 0; double down = 0; double temp = 0; if (i < stockPOS.size() - 13) { for (int j = i; j < i + 13; j++) { temp = stockPOS.get(j).getClosePrice() - stockPOS.get(j + 1).getClosePrice(); if (temp > 0) up += temp; else down += temp; } if (down > 0) temp = 1 + up / down; else temp = 1 + up; stockPO.setRsi(100 - (100 / temp)); } else { stockPO.setRsi((double) (0)); } //计算dmi if (i < stockPOS.size() - 1) { StockPO lastDay = stockPOS.get(i + 1); double dmp = stockPO.getHighPrice() - lastDay.getHighPrice(); double dmm = lastDay.getLowPrice() - stockPO.getLowPrice(); if (dmp <= 0) dmp = 0; if (dmm <= 0) dmm = 0; if (dmm <= dmp) dmm = 0; else dmp = 0; stockPO.setDmPlus(dmp); stockPO.setDmMinus(dmm); double tr = stockPO.getHighPrice() - stockPO.getLowPrice(); temp = Math.abs(stockPO.getHighPrice() - lastDay.getClosePrice()); if (tr < temp) tr = temp; temp = Math.abs(stockPO.getLowPrice() - lastDay.getClosePrice()); if (tr < temp) tr = temp; stockPO.setTr(tr); if (i < stockPOS.size() - 13) { double dmp12 = 0; double dmm12 = 0; double tr12 = 0; for (int j = i; j < i + 12; j++) { dmp12 += stockPOS.get(j).getDmPlus(); dmm12 += stockPOS.get(j).getDmMinus(); tr12 += stockPOS.get(j).getTr(); } if (tr12 != 0) { stockPO.setDiMinus((dmm12 / tr12) * 100); stockPO.setDiPlus((dmp12 / tr12) * 100); } else { stockPO.setDiMinus((double) (0)); stockPO.setDiPlus((double) (0)); } double diDif = Math.abs(stockPO.getDiPlus() - stockPO.getDiMinus()); double diSum = Math.abs(stockPO.getDiPlus() + stockPO.getDiMinus()); double dx=0; if(diSum != 0) dx = (diDif / diSum) * 100; stockPO.setDx(dx); double adx = 0; for (int j = i; j < i + 12; j++) { adx += stockPOS.get(j).getDx(); } stockPO.setAdx(adx / 12); double adxr = 0; adxr = stockPO.getAdx() + stockPOS.get(i + 12).getAdx(); stockPO.setAdxr(adxr / 2); } else { int len = stockPOS.size() - i; double dmp12 = 0; double dmm12 = 0; double tr12 = 0; for (int j = i; j < i + len; j++) { dmp12 += stockPOS.get(j).getDmPlus(); dmm12 += stockPOS.get(j).getDmMinus(); tr12 += stockPOS.get(j).getTr(); } if (tr12 != 0) { stockPO.setDiMinus((dmm12 / tr12) * 100); stockPO.setDiPlus((dmp12 / tr12) * 100); } else { stockPO.setDiMinus((double) (0)); stockPO.setDiPlus((double) (0)); } double diDif = Math.abs(stockPO.getDiPlus() - stockPO.getDiMinus()); double diSum = Math.abs(stockPO.getDiPlus() + stockPO.getDiMinus()); double dx = 0; if(diSum != 0) dx = (diDif / diSum) * 100; stockPO.setDx(dx); double adx = 0; for (int j = i; j < i + len; j++) { adx += stockPOS.get(j).getDx(); } stockPO.setAdx(adx / len); double adxr = stockPO.getAdx() + stockPOS.get(stockPOS.size() - 2).getAdx(); stockPO.setAdxr(adxr / 2); } } else { stockPO.setDmPlus((double) (0)); stockPO.setDmMinus((double) (0)); stockPO.setTr((double) (0)); stockPO.setDiMinus((double) (0)); stockPO.setDiPlus((double) (0)); stockPO.setDx((double) (0)); stockPO.setAdx((double) (0)); stockPO.setAdxr((double) (0)); } /* System.out.print(stockPO.getStockId() + " "); System.out.print(stockPO.getMb() + " "); System.out.print(stockPO.getUp() + " "); System.out.print(stockPO.getDn() + " "); System.out.print(stockPO.getAdjClose() + " "); System.out.print(stockPO.getHighPrice() + " "); System.out.print(stockPO.getLowPrice() + " "); System.out.print(stockPO.getOpenPrice() + " "); System.out.print(stockPO.getClosePrice() + " "); System.out.print(stockPO.getChg() + " "); System.out.print(stockPO.getReturnRate() + " "); System.out.print(stockPO.getAmount() + " "); System.out.print(stockPO.getRsv() + " "); System.out.print(stockPO.getkValue() + " "); System.out.print(stockPO.getdValue() + " "); System.out.print(stockPO.getjValue() + " "); System.out.print(stockPO.getEma12() + " "); System.out.print(stockPO.getEma26() + " "); System.out.print(stockPO.getDif() + " "); System.out.print(stockPO.getDea() + " "); System.out.print(stockPO.getRsi() + " "); System.out.print(stockPO.getDmMinus() + " "); System.out.print(stockPO.getDmPlus() + " "); System.out.print(stockPO.getTr() + " "); System.out.print(stockPO.getDiPlus() + " "); System.out.print(stockPO.getDiMinus() + " "); System.out.print(stockPO.getDx() + " "); System.out.print(stockPO.getAdx() + " "); System.out.print(stockPO.getAdxr() + " "); */ // System.out.println(); // System.out.print(stockPO.getStockId() + " "); // System.out.print(stockPO.getStockId() + " "); stockDao.add(stockPO); System.out.println(stockPO.getStockId() + " " + stockPO.getDateValue()); } }else{ wait.add(m); } } catch (IOException e1) { e1.printStackTrace(); // } catch (InterruptedException e2) { // e2.printStackTrace(); } catch (ParseException e3) { e3.printStackTrace(); } } for(int i = 0; i < wait.size(); i++){ System.out.print(wait.get(i) + ";"); } //System.out.print(stocks.get(i)); } private double maValue(int position, int matype, List<StockPO> stockPOS){ double sum = 0; for(int i = position; i < position + matype; i++){ // System.out.println(i); sum += stockPOS.get(i).getClosePrice(); } return sum / matype; } } <file_sep>package init;/** * Created by island on 2017/3/5. */ import javafx.application.Application; import javafx.stage.Stage; import ui.MainViewController; import ui.StageController; public class Starter extends Application { private StageController stageController = new StageController(); @Override public void start(Stage stage) { intGUI(); } public static void main(String[] args) { launch(args); } public void intGUI(){ stageController = new StageController(); stageController.loadStage("MainView.fxml"); MainViewController mainViewController = (MainViewController) stageController.getController(); mainViewController.init(); } } <file_sep>package oquantour.po.util; /** * Created by keenan on 03/06/2017. */ public class Edge implements Comparable<Edge> { private int industryA_id; private int industryB_id; private double weight; private String industryA_Name; private String industryB_Name; public Edge(int industryA, int industryB, double weight, String industryA_Name, String industryB_Name) { super(); this.industryA_id = industryA; this.industryB_id = industryB; this.weight = weight; this.industryA_Name = industryA_Name; this.industryB_Name = industryB_Name; } @Override public int compareTo(Edge o) { if (o.weight == weight) { return 0; } else if (weight < o.weight) { return -1; } else { return 1; } } public int getIndustryA_id() { return industryA_id; } public int getIndustryB_id() { return industryB_id; } public double getWeight() { return weight; } public String getIndustryA_Name() { return industryA_Name; } public String getIndustryB_Name() { return industryB_Name; } } <file_sep>package oquantour.service; import oquantour.exception.*; import oquantour.po.UserPO; import java.io.Serializable; /** * Created by keenan on 06/05/2017. */ public interface UserService { /** * add a new user * * @param userPO * @throws InvalidInfoException 所填信息错误 * @throws UserExistedException 用户已经存在 */ void addUser(UserPO userPO) throws InvalidPhoneException, InvalidPasswordException, InvalidUsernameException, UserExistedException; /** * modify user info * * @param userPO * @throws InvalidInfoException 所填信息错误 */ void modifyUser(UserPO userPO) throws InvalidPhoneException, InvalidPasswordException; /** * find an user by ID * * @param ID * @return 查找结果 * @throws UserNotExistException 用户不存在 */ UserPO findUserByID(Serializable ID) throws UserNotExistException; } <file_sep>package vo; import javafx.beans.property.SimpleStringProperty; import po.Stock; import java.util.Date; /** * Created by island on 2017/4/18. */ public class StockBackTestWinnerVO { //日期 public String date; //股票名字 public String stockName; //股票ID public String stockID; //开盘价 public String open; //收盘价 public String close; //复权收盘价 public String stdclose; //最高价 public String high; //最低价 public String low; public SimpleStringProperty specDate; public SimpleStringProperty specCode; public SimpleStringProperty specName; public SimpleStringProperty specOpen; public SimpleStringProperty specClose; public SimpleStringProperty specStdClose; public SimpleStringProperty specHigh; public SimpleStringProperty specLow; /** * 显示市场温度计榜单时使用的构造方法 * @param specCode * @param specName * @param specOpen * @param specClose * @param specHigh * @param specLow */ public StockBackTestWinnerVO(String specDate, String specCode, String specName, String specOpen, String specClose, String specStdClose, String specHigh, String specLow) { this.specDate = new SimpleStringProperty(specDate); this.specCode = new SimpleStringProperty(specCode); this.specName = new SimpleStringProperty(specName); this.specOpen = new SimpleStringProperty(specOpen); this.specClose = new SimpleStringProperty(specClose); this.specStdClose = new SimpleStringProperty(specStdClose); this.specHigh = new SimpleStringProperty(specHigh); this.specLow = new SimpleStringProperty(specLow); } public String getSpecCode() { return specCode.get(); } public String getSpecName() { return specName.get(); } public String getSpecDate() { return specDate.get(); } public String getSpecOpen() { return specOpen.get(); } public String getSpecClose() { return specClose.get(); } public String getSpecStdClose() { return specStdClose.get(); } public String getSpecHigh() { return specHigh.get(); } public String getSpecLow() { return specLow.get(); } } <file_sep>package oquantour.serviceTest; import oquantour.BaseTest; import oquantour.po.StockRealTimePO; import oquantour.po.util.Edge; import oquantour.po.util.RelationGraph; import oquantour.service.IndustryService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; import java.util.PriorityQueue; /** * Created by keenan on 09/06/2017. */ public class IndustryTest extends BaseTest { @Autowired IndustryService industryService; @Test public void testRelationGraph() { RelationGraph relationGraph = industryService.getIndustryTree(); PriorityQueue<Edge> edges = relationGraph.getEdges(); for (Edge edge : edges) { System.out.println(edge.getIndustryA_Name() + " - " + edge.getIndustryB_Name() + " : " + edge.getWeight()); } } @Test public void testGetIndustry() { String name = "机床制造"; Map<String, StockRealTimePO> map = industryService.getIndustryStocks(name); System.out.println(map.size()); } } <file_sep>package ui; /** * Created by st on 2017/3/5. */ public interface ControlledPane { public void setPaneController(PaneAdder paneAdder); } <file_sep>package oquantour.util.tools; /** * 技术面分析指标 * Created by keenan on 08/06/2017. */ public enum IndicesAnalysis { BOLL, KDJ, DMI, MACD } <file_sep>package data.dataHelper; import java.io.*; import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; /** * 得到股票代码和股票名称的映射关系 * <p> * Created by keenan on 06/03/2017. */ public class CodeNameRelation { private static class SingletionHolder { private static final CodeNameRelation codeNameRelation = new CodeNameRelation(); } private Map<String, String> map_name_code; private Map<String, String> map_code_name; private List<String> values; private CodeNameRelation() { if (map_name_code == null) { map_name_code = generateCodeNameRelation(9, 8); } if (map_code_name == null) { map_code_name = generateCodeNameRelation(8, 9); } if (values == null) { values = generateAllValues(); } } public static final CodeNameRelation getInstance() { return SingletionHolder.codeNameRelation; } public Map<String, String> getNameCodeRelation() { return map_code_name; } public Map<String, String> getCodeNameRelation() { return map_name_code; } public List<String> getValues() { return values; } private List<String> generateAllValues() { Set<String> keySet = map_name_code.keySet(); List<String> values = new ArrayList<>(); for (Iterator it = keySet.iterator(); it.hasNext(); ) { String s = (String) it.next(); values.add(map_name_code.get(s)); } return values; } /** * 得到股票代码和股票名称的映射关系 * * @param mapFirst 对应map的key * @param mapSecond 对应map的value * @return 对应映射 */ private Map<String, String> generateCodeNameRelation(int mapFirst, int mapSecond) { Map<String, String> map = new HashMap<>(); // 查询的根目录 String folder = System.getProperty("user.dir") + "/datasource/stocks/"; // 使用Path封装 Path path = Paths.get(folder); // 储存已经遍历过的文件 List<File> files = new ArrayList<>(); SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() { @Override // 访问单个文件 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { files.add(file.toFile()); return super.visitFile(file, attrs); } }; // 遍历文件树 try { java.nio.file.Files.walkFileTree(path, finder); } catch (Exception e) { e.printStackTrace(); } InputStream inputStream = null; BufferedReader bufferedReader = null; try { for (int i = 0; i < files.size(); i++) { // 读出所有以".txt"结尾的文件(因为MacOS下会有一个额外的文件 if (files.get(i).getAbsolutePath().endsWith(".txt")) { inputStream = new BufferedInputStream(new FileInputStream(files.get(i).getAbsolutePath())); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = bufferedReader.readLine(); String[] attris = line.split(";"); //加入到map中 if (!map.containsKey(attris[mapFirst])) { map.put(attris[mapFirst], attris[mapSecond]); } } if (inputStream == null) { continue; } inputStream.close(); bufferedReader.close(); } } catch (Exception e) { e.printStackTrace(); } return map; } } <file_sep>package oquantour.action; import com.opensymphony.xwork2.ActionSupport; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import oquantour.exception.WrongCombinationException; import oquantour.po.StockCombination; import oquantour.service.PlateService; import oquantour.service.PortfolioService; import oquantour.po.util.ChartInfo; import oquantour.po.util.PortfolioInfo; import oquantour.util.tools.CalendarUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Created by st on 2017/6/6. */ @Controller public class userCombineAction extends ActionSupport { private String result; private String info; @Autowired private PortfolioService portfolioService; @Autowired private PlateService plateService; public void setPlateService(PlateService plateService) { this.plateService = plateService; } private String username; private String portfolioName; private String stocks; private String positions; public String getResult() { return result; } public void setProfolioService(PortfolioService portfolioService) { this.portfolioService = portfolioService; } public void setUsername(String username) { this.username = username; } public void setPortfolioName(String portfolioName) { this.portfolioName = portfolioName; } public void setStocks(String stocks) { this.stocks = stocks; } public void setPositions(String positions) { this.positions = positions; } public String addPortfolio() { JSONArray jsonArray = new JSONArray(); try { List<String> stocks_list = Arrays.asList(stocks.split(";")); // List<Double> positions_list = new ArrayList<>(positions.split(";")); List<Double> doubles = Arrays.asList(Arrays.stream(positions.split(";")).map(Double::valueOf).toArray(Double[]::new)); portfolioService.addPortfolio(username, portfolioName, stocks_list, doubles); info = "添加组合成功"; JSONObject jsonObject = new JSONObject(); jsonObject.put("info", info); jsonArray.add(jsonObject); result = jsonArray.toString(); } catch (WrongCombinationException e) { info = e.getMessage(); JSONObject jsonObject = new JSONObject(); jsonObject.put("info", info); jsonArray.add(jsonObject); result = jsonArray.toString(); } return SUCCESS; } public String getAllPortfolios() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); List<Map.Entry<String, Timestamp>> allPortfolios = portfolioService.getAllPortfolios(username); JSONArray jsonArray = new JSONArray(); for (Map.Entry<String, Timestamp> entry : allPortfolios) { JSONObject jsonObject = new JSONObject(); jsonObject.put("combinationName", entry.getKey()); jsonObject.put("combinationTime", simpleDateFormat.format(entry.getValue())); System.out.println("组合:" + entry.getKey() + " " + simpleDateFormat.format(entry.getValue())); jsonArray.add(jsonObject); } result = jsonArray.toString(); return SUCCESS; } public String getPortfolio() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); PortfolioInfo portfolioInfo = portfolioService.getPortfolio(username, portfolioName); JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonObject.put("totalReturnRate", portfolioInfo.getTotalReturnRate()); jsonObject.put("newNet", portfolioInfo.getNewNet()); jsonArray.add(jsonObject); List<ChartInfo> industryDistributionChart = portfolioInfo.getIndustryDistribution(); for (ChartInfo c : industryDistributionChart) { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("name", c.getStrXAxis()); jsonObject1.put("value", c.getyAxis() * 100); jsonArray.add(jsonObject1); } List<ChartInfo> returnRateChart = portfolioInfo.getReturnRates(); for (ChartInfo c : returnRateChart) { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("date", simpleDateFormat.format(c.getDateXAxis())); jsonObject1.put("y", c.getyAxis()); jsonArray.add(jsonObject1); } List<StockCombination> stockCombinations = portfolioInfo.getPortfolio(); Map<Timestamp, List<Double>> map = portfolioInfo.getPositionInfo(); for (StockCombination stockCombination : stockCombinations) { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("combinationName", stockCombination.getCombinationName()); jsonObject1.put("positions", stockCombination.getPositions()); // jsonObject1.put("prices", stockCombination.getPrices()); jsonObject1.put("timeStamp", simpleDateFormat2.format(stockCombination.getTime())); jsonObject1.put("stocks", stockCombination.getStocks()); List<Double> list = map.get(stockCombination.getTime()); if (list != null) jsonObject1.put("positions2", list); jsonArray.add(jsonObject1); } List<ChartInfo> maxProfit = portfolioInfo.getMaxProfitStocks(); Map<String, Double> avgPosition = portfolioInfo.getAvgPosition(); Map<String, Double> tradeCnt = portfolioInfo.getTradeCnt(); for (ChartInfo chartInfo : maxProfit) { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("maxPortName", chartInfo.getStrXAxis()); jsonObject1.put("avg", avgPosition.get(chartInfo.getStrXAxis())); jsonObject1.put("trade", tradeCnt.get(chartInfo.getStrXAxis())); jsonObject1.put("y", chartInfo.getyAxis()); jsonArray.add(jsonObject1); } List<ChartInfo> minProfit = portfolioInfo.getMinProfitStocks(); for (ChartInfo chartInfo : minProfit) { JSONObject jsonObject1 = new JSONObject(); jsonObject1.put("minPortName", chartInfo.getStrXAxis()); jsonObject1.put("avg", avgPosition.get(chartInfo.getStrXAxis())); jsonObject1.put("trade", tradeCnt.get(chartInfo.getStrXAxis())); jsonObject1.put("y", chartInfo.getyAxis()); jsonArray.add(jsonObject1); } java.sql.Date date = new java.sql.Date(portfolioInfo.getCreateTime().getTime()); Map<String, List<ChartInfo>> plate = plateService.getPlateReturnRates(date, CalendarUtil.getToday(), "上证指数", "中小板指", "创业板指", "沪深300", "深证成指", "深证A指"); addToJson(plate.get("深证A指"), jsonArray, "SZADate", "SZA"); addToJson(plate.get("中小板指"), jsonArray, "ZXDate", "ZX"); addToJson(plate.get("创业板指"), jsonArray, "CYDate", "CY"); addToJson(plate.get("沪深300"), jsonArray, "HSDate", "HS"); addToJson(plate.get("深证成指"), jsonArray, "SZCDate", "SZC"); addToJson(plate.get("上证指数"), jsonArray, "SZDate", "SZ"); // JSONObject jsonObject1 = new JSONObject(); // jsonObject1.put("currentStock", portfolioInfo.getCurrentCombination().getStocks()); // jsonObject1.put("currentPosition", portfolioInfo.getCurrentCombination().getPositions()); // jsonArray.add(jsonObject1); result = jsonArray.toString(); return SUCCESS; } public String getCurrentStocks() { StockCombination stockCombination = portfolioService.getLatestPortfolio(username, portfolioName); List<String> stock = stockCombination.getStocks(); List<Double> positions = stockCombination.getPositions(); JSONArray jsonArray = new JSONArray(); for (int i = 0; i < stock.size(); i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("stock", stock.get(i)); jsonObject.put("position", positions.get(i)); jsonArray.add(jsonObject); } result = jsonArray.toString(); return SUCCESS; } public String deletePortfolio() { portfolioService.deletePortfolio(username, portfolioName); return SUCCESS; } private void addToJson(List<ChartInfo> list, JSONArray jsonArray, String s1, String s2) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); for (ChartInfo chartInfo : list) { JSONObject jsonObject = new JSONObject(); jsonObject.put(s1, simpleDateFormat.format(chartInfo.getDateXAxis())); jsonObject.put(s2, chartInfo.getyAxis()); jsonArray.add(jsonObject); } } } <file_sep>package oquantour.service.serviceImpl; import oquantour.data.dao.UserDao; import oquantour.po.StockPO; import oquantour.service.OptionalStockService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Date; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by keenan on 23/05/2017. */ @Service @Transactional public class OptionalStockServiceImpl implements OptionalStockService { @Autowired private UserDao userDao; private Map<String, List<String>> map = new HashMap<>(); /** * 增加自选股 * * @param account 用户账户 * @param stockID 股票代码 */ @Override public void addOptionalStock(String account, String stockID) { userDao.addSelectedStock(account, stockID); refreshMap(account); } /** * 删除自选股 * * @param account 用户账户 * @param stockID 股票代码 */ @Override public void deleteOptionalStock(String account, String stockID) { userDao.deleteSelectedStock(account, stockID); refreshMap(account); } /** * 判断股票是否已在自选股中 * * @param account 用户账户 * @param stockID 股票代码 * @return 是否已在自选股中 */ @Override public boolean isInOptionalStock(String account, String stockID) { List<String> optionalStocks = map.get(account); if (optionalStocks == null) { refreshMap(account); List<String> os = map.get(account); if (os == null) { return false; } else { return os.contains(stockID); } } else { return optionalStocks.contains(stockID); } } /** * 获得某用户所有自选股 * * @param account 用户账户 * @return 用户所有自选股 */ @Override public List<String> getAllOptionalStock(String account) { List<String> optionalStocks = map.get(account); if (optionalStocks == null) { refreshMap(account); List<String> os = map.get(account); if (os == null) { return Collections.emptyList(); } else { return os; } } else { return optionalStocks; } } private void refreshMap(String account) { map.put(account, userDao.getSelectedStock(account)); System.out.println(account + " " + map.get(account).size()); } } <file_sep>package oquantour.service.servicehelper.analysis.stock.indices; import oquantour.po.StockPO; import org.apache.commons.math3.fitting.PolynomialCurveFitter; import org.apache.commons.math3.fitting.WeightedObservedPoints; import java.util.ArrayList; import java.util.List; /** * 股票行情分析 * <p> * Created by keenan on 16/05/2017. */ public class AdjAnalysis { /** * 得到股票投资建议 * * @param stocks 股票信息 * @return 投资建议 */ public String getInvestmentSuggestion(List<StockPO> stocks) { // 倒数一个波浪 int last_index = 0; // 倒数第二个波浪 int snd2last_index = 0; // 波浪计数 int cnt = 0; // 寻找最后两个波浪点的日期 for (int i = stocks.size() - 2; i >= 1; i--) { StockPO current = stocks.get(i); StockPO right = stocks.get(i + 1); StockPO left = stocks.get(i - 1); if ((right.getAdjClose() > current.getAdjClose() && left.getAdjClose() > current.getAdjClose()) || (right.getAdjClose() < current.getAdjClose() && left.getAdjClose() < current.getAdjClose())) { if (cnt == 0) { last_index = i; cnt++; continue; } else if (cnt == 1) { snd2last_index = i; break; } } } // 特殊情况 if (Math.abs(last_index - snd2last_index) < 2) { return "该股近几日股价波动较大,建议进一步持股观望。"; } // 非线性回归拟合 - 抛物线 int t = 1; WeightedObservedPoints adjCloseFunc = new WeightedObservedPoints(); WeightedObservedPoints volumeFunc = new WeightedObservedPoints(); for (int j = snd2last_index; j < stocks.size(); j++) { adjCloseFunc.add(t, stocks.get(j).getAdjClose()); volumeFunc.add(t, stocks.get(j).getVolume()); t++; } double[] adjCloseFunc_coeff = polynomialCurve(adjCloseFunc); double[] volumeFunc_coeff = polynomialCurve(volumeFunc); double a = adjCloseFunc_coeff[2]; double b = adjCloseFunc_coeff[1]; double c = adjCloseFunc_coeff[0]; double r = volumeFunc_coeff[2]; double p = volumeFunc_coeff[1]; double q = volumeFunc_coeff[0]; List<Double> s = new ArrayList<>(); List<Double> up = new ArrayList<>();// 分子 // 计算股票的成交量对价格的回归函数的弹性 for (int j = 1; j <= stocks.size() - snd2last_index; j++) { up.add((2 * a * r * j * j * j + (2 * b * r + q * p) * j * j + (2 * r * c + p * b) * j + p * c)); s.add((2 * a * r * j * j * j + (2 * b * r + q * p) * j * j + (2 * r * c + p * b) * j + p * c) / (2 * a * r * j * j * j) + (2 * a * p + b * r) * j * j + (2 * a * q + b * p) * j + b * q); } final String[] adviceOptions = { "股票处于价升量增阶段,价格在上升过程中受到了成交量的强有力配合和支持,投资者宜买进而不宜卖出,特别对于空仓投资者来说,选股时在同等条件下应先选择弹性最大的股票买入。", "股票处于价跌量减阶段,市场杀跌动力不足,持股的投资者不宜再杀跌,空仓的投资者应该主动补仓。", "股票处于价升量增阶段,但价格在上升过程中缺乏足够的成交量的配合和支持,许多获利筹码没有得到充分释放,此时该股的投资风险较大,股价未来可能将出现平盘整理或回调整理,建议投资者持币观望。", "股票处于价跌量减阶段,市场杀跌动力较大,该股在近期内很难有较强劲的反弹行情,空仓投资者应多看少动。", "股票处于价升量减阶段,该股的大多数筹码被庄家或机构大户所锁定,股价的无量空涨孕育了极大的投资风险,如果一有风吹草动或庄家出调,该股深幅回调势在必然,尽管该股在近日内有凌厉的涨势,投资者也不宜为贪图一时的近利而去冒不必要的危险。", "股票处于价跌量增阶段,这种量价背离现象说明,做空者出货坚决,市场杀跌动力较大,如无实质性利好消息出台,该股后期的行情将继续下行,不断向下寻求支撑。" }; String advice = ""; // 涨跌情况判断 List<Integer> statuses = new ArrayList<>(); // 生成投资建议 int status = -1; for (int i = snd2last_index; i < stocks.size(); i++) { int index = i - snd2last_index; if (s.get(index) > 1) { if (up.get(index) > 0) { status = 0; } else if (up.get(index) < 0) { status = 1; } } else if (s.get(index) > 0 && s.get(index) < 1) { if (up.get(index) > 0) { status = 2; } else if (up.get(index) < 0) { status = 3; } } else if (s.get(index) < 0) { if (up.get(index) < 0) { status = 4; } else if (up.get(index) > 0) { status = 5; } } statuses.add(status); } int currentNum = statuses.get(0); int currentStart = snd2last_index; int currentEnd = snd2last_index; for (int i = snd2last_index + 1; i < stocks.size(); i++) { int index = i - snd2last_index; if (statuses.get(index) == currentNum) { currentEnd++; continue; } else { currentNum = statuses.get(index - 1); advice += stocks.get(currentStart).getDateValue() + "到" + stocks.get(currentEnd).getDateValue() + adviceOptions[currentNum] + "\n"; currentNum = statuses.get(index); currentStart = i; currentEnd++; } } advice += stocks.get(currentStart).getDateValue() + "到" + stocks.get(currentEnd).getDateValue() + adviceOptions[currentNum] + "\n"; return advice; } /** * 获得抛物线回归拟合的参数 (0:指数为0, 1:指数为1, 2:指数为2) * * @param weightedObservedPoints 原始点集 * @return 拟合结果参数 */ private double[] polynomialCurve(WeightedObservedPoints weightedObservedPoints) { final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2); return fitter.fit(weightedObservedPoints.toList()); } }
c0d5fe915ffcc7731881c84fac52df3ab9e53ebe
[ "JavaScript", "Markdown", "Maven POM", "Java", "Python" ]
88
Java
Atlas-zqh/Oquantour
c3e91285d7099311148ee1f8f8e173afc37ea69d
2dbe44a4296ace8314734ca252db111238ae032a
refs/heads/master
<file_sep># Oxford-VA-2015-Practical-1 This is a practical project submitted to Visual Analytics course (2015) at Oxford University. The aim is to make use of existing examples in D3.js repository, e.g., parallel coordinate, tag cloud, themeriver, to visualise dataset. Please follow in the link for further details: https://sites.google.com/site/drminchen/va The project can be imported into WebStorm IDE.<file_sep>/** * Tag Cloud Plot. * Part of Visual Analytics 2015 Practical. * Candidate number: 589087 * * ----- Acknowledgement ----- * The code is adapted from <NAME>'s Word Cloud, which can be found * at the D3.js's repository at https://github.com/mbostock/d3/wiki/Gallery. The code is modified * for Visual Analytics practical. * --------------------------- */ d3.csv("assets/data/data5yearsum.csv", function(words){ var total = 0, perc = [], data = [], colour = []; words.forEach(function(d, i){ total += parseInt(d.sum); data.push(d.names); colour.push(d.colour); }); words.forEach(function(d, i){ perc.push(Math.log10(d.sum / total * 1000)); }); var fill = d3.scale.ordinal() .domain([0, 39]) .range(colour); d3.layout.cloud().size([1280, 500]) .words(data.map(function(d, i) { return {text: d, size: perc[i] * 30}; })) .rotate(function() { return ~~(Math.random() * 2) * 90; }) .font("Impact") .fontSize(function(d) { return d.size; }) .on("end", draw) .start(); function draw(words) { d3.select("#tagcloud").append("svg") .attr("width", 1280) .attr("height", 500) .append("g") .attr("transform", "translate(640,250)") .selectAll("text") .data(words) .enter().append("text") .style("font-size", function(d) { return d.size + "px"; }) .style("font-family", "Impact") .style("fill", function(d, i) { return fill(i); }) .attr("text-anchor", "middle") .attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; }) .text(function(d) { return d.text; }); } }); <file_sep>/** * Draw themeriver for word count and percentage. * Part of Visual Analytics 2015 Practical. * Candidate number: 589087 * * ----- Acknowledgement ----- * The code is adapted from Mike Bostock's Stacked Density and Quantile Graphs, which can be found * at the D3.js's repository at https://github.com/mbostock/d3/wiki/Gallery. The code is modified * for Visual Analytics practical. * --------------------------- * * @param data data to be displayed * @param id the HTML element to contain the display */ var dqData = []; d3.csv("assets/data/data1year.csv", function(words){ // data variables var titleA = "Word Count", titleB = "Percentage"; var distMin = 1990, distMax = 2014, mean; var dP = [], dist = [], quant = [], sumPerYear = []; var colour = []; for(var i = 0; i < 25; i++){ dist.push([]); quant.push([]); } // load data to variables words.forEach(function(d, i){ dP.push([d.names, parseFloat(d.avg), parseFloat(d.sum)]); colour.push(d.colour); for(var i = 0; i < 25; i++){ dist[i].push(parseInt(d[Object.keys(d)[i + 1]])); } }); var sum = 0; for(var i = 0; i < 40; i++){ sum += parseFloat(dP[i][1]); //console.log(dP[i][1]); } mean = sum / 40; // Calculate Sum per Year for(var year = 0; year < 25; year ++){ var yearSum = 0; for(var word = 0; word < 40; word++){ yearSum += parseInt(dist[year][word]); } sumPerYear.push(yearSum); } // Calculate percentage for(var year = 0; year < 25; year ++) { for (var word = 0; word < 40; word++) { quant[year].push(dist[year][word] / sumPerYear[year]); } } dqData.push({ titleA: titleA, titleB: titleB, mean: mean, dP: dP, distMin: distMin, distMax: distMax, dist: dist, quant: quant, colour: colour }); // Call the drawing function to draw two themerivers drawAll(dqData, "themeriver"); }); function drawAll(data, id){ var seg = d3.select("#"+id).selectAll("div").data(d3.range(data.length)).enter() .append("div").attr("id",function(d,i){ return "segment"+i;}).attr("class","distquantdiv"); d3.range(data.length).forEach(function(d,i){ distQuant(data[i], "segment"+i );}); } function distQuant(data, id){ function getPoints(_, i){ return _.map(function(d,j){ return {x:j, y:d[i]};}); } /* function to return 0 for all attributes except k-th attribute.*/ function getPointsZero(_, i, k){ return _.map(function(d,j){ return {x:j, y:(i==k ? d[i] : 0 )};}); } function toComma(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } var width=800, height=400, margin=20; var colors = data.colour; function draw(type){ var maxT = d3.max(data[type].map(function(d){ return d3.sum(d); })); function tW(d){ return x(d*(data[type].length - 1)/50); } function tH(d){ return y(d*maxT/50); } var svg =d3.select("#"+id).select("."+type); //x and y axis maps. var x = d3.scale.linear().domain([0, data[type].length - 1]).range([0, width]); var y = d3.scale.linear().domain([0, maxT]).range([height, 0]); //draw yellow background for graph. svg.append("rect").attr("x",0).attr("y",0).attr("width",width).attr("height",height).style("fill","rgb(235,235,209)"); // draw vertical lines of the grid. svg.selectAll(".vlines").data(d3.range(51)).enter().append("line").attr("class","vlines") .attr("x1",tW).attr("y1",0) .attr("x2", tW).attr("y2",function(d,i){ return d%10 ==0 && d!=50? height+12: height;}); //draw horizontal lines of the grid. svg.selectAll(".hlines").data(d3.range(51)).enter().append("line").attr("class","hlines") .attr("x1",function(d,i){ return d%10 ==0 && d!= 50? -12: 0;}) .attr("y1",tH) .attr("x2", width).attr("y2",tH); // make every 10th line in the grid darker. svg.selectAll(".hlines").filter(function(d){ return d%10==0}).style("stroke-opacity",0.7); svg.selectAll(".vlines").filter(function(d){ return d%10==0}).style("stroke-opacity",0.7); function getHLabel(d,i){ var r= data.distMin+i*(data.distMax-data.distMin)/5; return Math.round(r*100)/100; } function getVLabel(d,i){ if(type=="dist"){ // for dist use the maximum for sum of frequencies and divide it into 5 pieces. return Math.round(maxT*i/5); }else{ // for quantile graph, use percentages in increments of 20%. return (i*20)+' %'; } } // add horizontal axis labels svg.append("g").attr("class","hlabels") .selectAll("text").data(d3.range(41).filter(function(d){ return d%10==0})).enter().append("text") .text(getHLabel).attr("x",function(d,i){ return tW(d)+5;}).attr("y",height+14); // add vertical axes labels. svg.append("g").attr("class","vlabels") .selectAll("text").data(d3.range(41).filter(function(d){ return d%10==0 })).enter().append("text") .attr("transform",function(d,i){ return "translate(-10,"+(tH(d)-14)+")rotate(-90)";}) .text(getVLabel).attr("x",-10).attr("y",function(d){ return 5;}); var area = d3.svg.area().x(function(d) { return x(d.x); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }) .interpolate("basis"); var layers = d3.layout.stack().offset("zero")(data.dP.map(function(d,i){ return getPoints(data[type], i);})); svg.selectAll("path").data(layers).enter().append("path").attr("d", area) .style("fill", function(d,i) { return colors[i]; }) .style("stroke", function(d,i) { return colors[i]; }) .style("fill-opacity", function(d,i) { return 0.8; }) .style("stroke-opacity", function(d,i) { return 0; }); //draw a white rectangle to hide and to show some statistics. var stat = svg.append("g").attr("class","stat"); stat.append("rect").attr("x",-margin).attr("y",-margin) .attr("width",width+2*margin).attr("height",margin).style("fill","white"); // show sum and mean in statistics if(type=="dist"){ stat.append("text").attr("class","count").attr("x",20).attr("y",-6) .text(function(d){ var sum = d3.sum(data.dP.map(function(s){ return s[2];})); return "Count: " +toComma(sum)+" / "+toComma(sum)+" ( 100 % )"; }); stat.append("text").attr("class","mean").attr("x",250).attr("y",-6) .text(function(d){ return "Mean: " +data.mean + " per word per year";}); } } function transitionIn(type, p){ var maxT = d3.max(data[type].map(function(d){ return d3.sum(d); })); var max = d3.max(data[type].map(function(d){ return d[p]; })); var x = d3.scale.linear().domain([0, data[type].length - 1]).range([0, width]); var y = d3.scale.linear().domain([0, max]).range([height, 0]); function tW(d){ return x(d*(data[type].length - 1)/50); } function tH(d){ return y(d*maxT/50); } var area = d3.svg.area().x(function(d) { return x(d.x); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }) .interpolate("basis"); var layers = d3.layout.stack().offset("zero")(data.dP.map(function(d,i){ return getPointsZero(data[type], i, p);})); var svg = d3.select("#"+id).select("."+type); //transition all the lines, labels, and areas. svg.selectAll("path").data(layers).transition().duration(500).attr("d", area); svg.selectAll(".vlines").transition().duration(500).attr("x1",tW).attr("x2", tW); svg.selectAll(".hlines").transition().duration(500).attr("y1",tH).attr("y2",tH); svg.selectAll(".vlabels").selectAll("text").transition().duration(500) .attr("transform",function(d,i){ return "translate(-10,"+(tH(d)-14)+")rotate(-90)";}); //update the statistics rect for distribution graph. if(type=="dist"){ svg.select(".stat").select(".count") .text(function(d){ var sumseg = data.dP[p][2]; var sum = d3.sum(data.dP.map(function(s){ return s[2];})); return "Count: " +toComma(sumseg)+" / "+toComma(sum)+" ( "+Math.round(100*sumseg/sum)+" % )"; }); svg.select(".stat").select(".mean").text(function(d){ return "Mean: " +data.dP[p][1];}); } } function transitionOut(type){ var maxT = d3.max(data[type].map(function(d){ return d3.sum(d); })); function tW(d){ return x(d*(data[type].length - 1)/50); } function tH(d){ return y(d*maxT/50); } var x = d3.scale.linear().domain([0, data[type].length - 1]).range([0, width]); var y = d3.scale.linear().domain([0, maxT]).range([height, 0]); var area = d3.svg.area().x(function(d) { return x(d.x); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }) .interpolate("basis"); var layers = d3.layout.stack().offset("zero")(data.dP.map(function(d,i){ return getPoints(data[type], i);})); // transition the lines, areas, and labels. var svg = d3.select("#"+id).select("."+type); svg.selectAll("path").data(layers).transition().duration(500).attr("d", area); svg.selectAll(".vlines").transition().duration(500).attr("x1",tW).attr("x2", tW); svg.selectAll(".hlines").transition().duration(500).attr("y1",tH).attr("y2",tH); svg.selectAll(".vlabels").selectAll("text").transition().duration(500) .attr("transform",function(d,i){ return "translate(-10,"+(tH(d)-14)+")rotate(-90)";}); // for distribution graph, update the statistics rect. if(type=="dist"){ svg.select(".stat").select(".count") .text(function(d){ var sum = d3.sum(data.dP.map(function(s){ return s[2];})); return "Count: " +toComma(sum)+" / "+toComma(sum)+" ( 100 % )"; }); svg.select(".stat").select(".mean").text(function(d){ return "Mean: " +data.mean;}); } } function mouseoverLegend(_,p){ transitionIn("dist", p); transitionIn("quant", p); } function mouseoutLegend(){ transitionOut("dist"); transitionOut("quant"); } // add title. d3.select("#"+id).append("h3").attr("id", "wc").attr("width",width).text(data.titleA); // add svg and set attributes for distribution. d3.select("#"+id).append("svg").attr("width",width+2*margin).attr("height",height+2*margin) .append("g").attr("transform","translate("+margin+","+margin+")").attr("class","dist"); d3.select("#"+id).append("h3").attr("id", "perc").attr("width",width).attr("height",height+2*margin).text(data.titleB); //add svg and set attributes for quantil. d3.select("#"+id).append("svg").attr("width",width+2*margin).attr("height",height+2*margin) .append("g").attr("transform","translate("+margin+","+margin+")").attr("class","quant"); // Draw the two graphs. draw("dist"); draw("quant"); // draw legends. var legRow = d3.select("#"+id).append("div").attr("class","legend") .append("table").selectAll("tr").data(data.dP).enter().append("tr").append("td"); legRow.append("div").style("background",function(d,i){ return colors[i];}) .on("mouseover",mouseoverLegend).on("mouseout",mouseoutLegend).style("cursor","pointer"); legRow.append("span").text(function(d){ return d[0];}) .on("mouseover",mouseoverLegend).on("mouseout",mouseoutLegend).style("cursor","pointer"); }<file_sep>/** * Parallel Coordinate Plot * Part of Visual Analytics 2015 Practical. * Candidate number: 589087 * * ----- Acknowledgement ----- * The code is adapted from <NAME>'s Parallel Coordinate Plot, which can be found * at the D3.js's repository at https://github.com/mbostock/d3/wiki/Gallery. The code is modified * for Visual Analytics practical. * --------------------------- */ var m = [80, 160, 200, 160], w = 1280 - m[1] - m[3], // 960 h = 850 - m[0] - m[2]; // 520 var line = d3.svg.line(), axis = d3.svg.axis().orient("left"), foreground; var svg = d3.select("#paracoord").append("svg:svg") .attr("width", w + m[1] + m[3]) // 1280 .attr("height", h + m[0] + m[2]) // 800 .append("svg:g") .attr("transform", "translate(" + m[3] + "," + m[0] + ")"); // translate(160, 80) d3.csv("assets/data/class4.csv", function (words) { var names = [], reddish = [], greenish=[]; var seed = [], stem = [], root = [], leaf = [], flower=[], sweetness=[], section=[]; // load names console.log(words); words.forEach(function (d, i) { names.push(d.names); reddish.push(d.reddish); greenish.push(d.greenish); seed.push(d.seed); stem.push(d.stem); root.push(d.root); leaf.push(d.leaf); flower.push(d.flower); sweetness.push(d.sweetness); section.push(d.section); }); var axes = d3.keys(words[0]); var x = d3.scale.ordinal().domain(axes).rangePoints([0, w]),// [0, 960] y = {}; // Create a scale and brush for each trait. axes.forEach(function (d) { if (d == "names") y[d] = d3.scale.ordinal().domain(names).rangeRoundPoints([h, 0]); else if(d == "reddish") y[d] = d3.scale.ordinal().domain(reddish).rangeRoundPoints([h, 0]); else if(d == "greenish") y[d] = d3.scale.ordinal().domain(greenish).rangeRoundPoints([h, 0]); else if(d == "seed") y[d] = d3.scale.ordinal().domain(seed).rangeRoundPoints([h, 0]); else if(d == "stem") y[d] = d3.scale.ordinal().domain(stem).rangeRoundPoints([h, 0]); else if(d == "root") y[d] = d3.scale.ordinal().domain(root).rangeRoundPoints([h, 0]); else if(d == "leaf") y[d] = d3.scale.ordinal().domain(leaf).rangeRoundPoints([h, 0]); else if(d == "flower") y[d] = d3.scale.ordinal().domain(flower).rangeRoundPoints([h, 0]); else if(d == "sweetness") y[d] = d3.scale.ordinal().domain(sweetness).rangeRoundPoints([h, 0]); else if(d == "section") y[d] = d3.scale.ordinal().domain(section).rangeRoundPoints([h, 0]); else y[d] = d3.scale.linear().domain([0, 120]).range([h, 0]); y[d].brush = d3.svg.brush().y(y[d]).on("brush", brush); }); // Add a legend. var legend = svg.selectAll("g.legend") .data(names) .enter().append("svg:g") .attr("class", "legend") .attr("transform", function (d, i) { return "translate(" + 150 * Math.floor(i / 7) + "," + ((i % 7) * 20 + 584) + ")"; }); legend.append("svg:line") .attr("class", String) .attr("x2", 8); legend.append("svg:text") .attr("x", 12) .attr("dy", ".31em") .text(function (d) { return d; }); // Add foreground lines. foreground = svg.append("svg:g") .attr("class", "foreground") .selectAll("path") .data(words) .enter().append("svg:path") .attr("d", path) .attr("class", function (d) { d.names; }); // Add a group element for each trait. var g = svg.selectAll(".trait") .data(axes) .enter().append("svg:g") .attr("class", "trait") .attr("transform", function (d) { return "translate(" + x(d) + ")"; }) .call(d3.behavior.drag() .origin(function (d) { return {x: x(d)}; }) .on("dragstart", dragstart) .on("drag", drag) .on("dragend", dragend)); // Add an axis and title. g.append("svg:g") .attr("class", "axis") .each(function (d) { d3.select(this).call(axis.scale(y[d])); }) .append("svg:text") .attr("text-anchor", "middle") .attr("y", -9) .text(String); // Add a brush for each axis. g.append("svg:g") .attr("class", "brush") .each(function (d) { d3.select(this).call(y[d].brush); }) .selectAll("rect") .attr("x", -8) .attr("width", 16); function dragstart(d) { i = axes.indexOf(d); } function drag(d) { x.range()[i] = d3.event.x; axes.sort(function (a, b) { return x(a) - x(b); }); g.attr("transform", function (d) { return "translate(" + x(d) + ")"; }); foreground.attr("d", path); } function dragend(d) { x.domain(axes).rangePoints([0, w]); var t = d3.transition().duration(500); t.selectAll(".trait").attr("transform", function (d) { return "translate(" + x(d) + ")"; }); t.selectAll(".foreground path").attr("d", path); } // Returns the path for a given data point. function path(d) { return line(axes.map(function (p) { return [x(p), y[p](d[p])]; })); } // Handles a brush event, toggling the display of foreground lines. function brush() { var actives = axes.filter(function (p) { return !y[p].brush.empty(); }), extents = actives.map(function (p) { return y[p].brush.extent(); }); foreground.classed("fade", function (d, k) { return !actives.every(function (p, i) { if (p == "names") return extents[i][0] <= (40 - k) / 40 * h && (40 - k) / 40 * h <= extents[i][1]; else return extents[i][0] <= d[p] && d[p] <= extents[i][1]; }); }); } });
8177f64a5101bdd84e17691b8958dfed9127880b
[ "Markdown", "JavaScript" ]
4
Markdown
virtworld/Oxford-VA-2015-Practical-1
051679b419916d50ba999596f5642cc084c8ae3f
5639970d008a199c52a0f5a9157818feb03c676b
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 # # Image Data Augmentation with Keras # # ![Horizontal Flip](assets/horizontal_flip.jpg) # # Task 1: Import Libraries # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') import os import numpy as np import tensorflow as tf from PIL import Image from matplotlib import pyplot as plt print('Using TensorFlow', tf.__version__) # # Task 2: Rotation # In[73]: rotationGenerator = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=40) # In[3]: image_path = 'images/train/cat/cat.jpg' plt.imshow(plt.imread(image_path)); # In[4]: x, y = next(rotationGenerator.flow_from_directory('images', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[19]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/rotation.jpg','JPEG') # # Task 3: Width and Height Shifts # In[20]: dimGenerator = tf.keras.preprocessing.image.ImageDataGenerator(width_shift_range=[-100,-50,0,50,100], height_shift_range=[-50,0,50]) # In[38]: x, y = next(dimGenerator.flow_from_directory('images/train', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[39]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/verical&height1.jpg','JPEG') # # Task 4: Brightness # In[43]: brightnessGenerator = tf.keras.preprocessing.image.ImageDataGenerator(brightness_range=(-2.5,2.)) x, y = next(brightnessGenerator.flow_from_directory('images', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[44]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/brightness.jpg','JPEG') # # Task 5: Shear Transformation # In[46]: shearGenerator = tf.keras.preprocessing.image.ImageDataGenerator(shear_range=40) x, y = next(shearGenerator.flow_from_directory('images', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[47]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/shear.jpg','JPEG') # # Task 6: Zoom # In[58]: zoomGenerator = tf.keras.preprocessing.image.ImageDataGenerator(zoom_range=[0.5,1.2]) x, y = next(zoomGenerator.flow_from_directory('images', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[59]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/zoom2.jpg','JPEG') # # Task 7: Channel Shift # In[69]: channelGenerator = tf.keras.preprocessing.image.ImageDataGenerator(channel_shift_range=100) x, y = next(channelGenerator.flow_from_directory('images', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[70]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/channel_shift2.jpg','JPEG') # # Task 8: Flips # In[71]: flipGenerator = tf.keras.preprocessing.image.ImageDataGenerator(horizontal_flip=True, vertical_flip=True) x, y = next(flipGenerator.flow_from_directory('images', batch_size=1)) plt.imshow(x[0].astype('uint8')); # In[72]: img=Image.fromarray(x[0].astype('uint8')) img.save('images/augmented_images_obtained/flip.jpg','JPEG') # # Task 9: Normalization # # ### Featurewise # In[76]: (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() #x_mean=x_train.mean() #x_std=x_train.std() #x_train_norm=(x_train-x_mean)/x_std generator = tf.keras.preprocessing.image.ImageDataGenerator( featurewise_center=True,featurewise_std_normalization=True ) generator.fit(x_train) # In[77]: x, y = next(generator.flow(x_train, y_train, batch_size=1)) print(x.mean(), x.std(), y) print(x_train.mean()) # ### Samplewise # In[79]: generator2 = tf.keras.preprocessing.image.ImageDataGenerator( samplewise_center=True,samplewise_std_normalization=True ) x, y = next(generator2.flow(x_train, y_train, batch_size=1)) print(x.mean(), x.std(), y) # # Task 10: Rescale and Preprocessing Function # In[80]: generator = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.,preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input ) # In[81]: x, y = next(generator.flow(x_train, y_train, batch_size=1)) # In[82]: print(x.mean(), x.std(), y) <file_sep># Image-Augmentation-and-Image-DataSet-Generated-using-Keras It is a simple function made using Keras library to generate a larger data set of images using a set of few images. The function to generate images is in 'Image Augmentation Generator.py'. It takes 3 arguments: 1. k= number of images to be generated 2.store_loc=Location/path of the directory where new images have to be stored 3.og_loc=Location/path of the directory where images to be given as input are given Images are generated by applying one of the 7 effects, selected randomly for each image. Further, each effect generator has a list/range of tuning, hence each image generated is different and unique. The 7 types of changes that can be applied are: 1.Rotation 2.Flipping (both horizontal and vertical) 3.Channel Shift 4.Zoom 5.Shear change 6.Brightness 7.Dimension adjustment/shift The newly generated images are also further used to create new images in future iterations Sample input images are present in:python_file_set/input_set Output images generated: 1000 images in- output_generated_set/output_generated_set.rar Sample visualization of each image generator and image processing can be seen in jupyter notebook present in: images(jupyter) [Notebook created as a part of guided course] <file_sep>import tensorflow as tf import random from PIL import Image def imageGenerator(k=1000,store_loc="output_generated_set",og_loc='python_file_set'): rotationGenerator = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=40) flipGenerator = tf.keras.preprocessing.image.ImageDataGenerator(horizontal_flip=True,vertical_flip=True) channelGenerator = tf.keras.preprocessing.image.ImageDataGenerator(channel_shift_range=100) zoomGenerator = tf.keras.preprocessing.image.ImageDataGenerator(zoom_range=[0.5,2]) shearGenerator = tf.keras.preprocessing.image.ImageDataGenerator(shear_range=40) brightnessGenerator = tf.keras.preprocessing.image.ImageDataGenerator(brightness_range=(.15,2.5)) dimGenerator = tf.keras.preprocessing.image.ImageDataGenerator(width_shift_range=[-100,-50,0,50,100],height_shift_range=[-50,0,50]) l=[rotationGenerator,flipGenerator,channelGenerator,zoomGenerator,shearGenerator,brightnessGenerator,dimGenerator] for i in range(1,k+1): t=random.choice(l) x, y = next(t.flow_from_directory(og_loc, batch_size=1)) iName=store_loc+"\\generatedPic"+str(i)+".jpg" img=Image.fromarray(x[0].astype('uint8')) img.save(iName,'JPEG') #imageGenerator()
9974835e6fa8decd9532cf1069a5529e36d28d1a
[ "Markdown", "Python" ]
3
Python
AdityaVashista30/Image-Augmentation-and-Image-DataSet-Generated-using-Keras
f42a16c44eddbfadadaf7d49155ef5931c807c53
8a654f4e9499ae86adb53457d8745d4ffd907882
refs/heads/master
<file_sep># kilotrack-app kilotrack-app Making a simple weight tracking application to track daily weight measurements. 1. Login 2. Track weights daily 3. Overall list of daily weights 4. Dashboard Future 4. Mobile app with Xamarin 5. Add goals like goal weight , target timeframe to achieve goal. Vuejs .net core <file_sep>using System; namespace kilotrack.Data.Models { public class Weight { public int Id { get; set; } public double usersRecentWeight { get; set; } public DateTime RecordedDate { get; set; } } }<file_sep>using kilotrack.Data.Models; using Microsoft.EntityFrameworkCore; namespace kilotrack.Data { public class KiloTrackDbContext : DbContext { public KiloTrackDbContext() { } public KiloTrackDbContext(DbContextOptions options) : base(options) { } public virtual DbSet<Weight> Weights { get; set; } } }<file_sep>using System; namespace kilotrack.Data.Models { public class Goal { public int Id { get; set; } public double startWeight { get; set; } public double targetWeight { get; set; } public DateTime RecordedDate { get; set; } } }<file_sep>using System; using System.Linq; using System.Collections.Generic; using kilotrack.Data; using kilotrack.Data.Models; namespace kilotrack.Services { public class WeightService : IWeightService { private readonly KiloTrackDbContext _db; public WeightService(KiloTrackDbContext db) { _db = db; } public void AddWeight(Weight weight) { throw new NotImplementedException(); } public void DeleteWeight(int weightId) { throw new NotImplementedException(); } public List<Weight> GetAllWeights() { return _db.Weights.ToList(); } public Weight GetWeight(int weightId) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace kilotrack.Web.Controllers { [ApiController] public class WeightController : ControllerBase { private readonly ILogger<WeightController> _logger; public WeightController(ILogger<WeightController> logger) { _logger = logger; } [HttpGet("/api/weight")] public ActionResult GetWeight() { return Ok("Your weight is.....!"); } } } <file_sep>using kilotrack.Data.Models; using System.Collections.Generic; namespace kilotrack.Services { public interface IWeightService { public List<Weight> GetAllWeights(); public Weight GetWeight(int weightId); public void AddWeight(Weight weight); public void DeleteWeight(int weightId); } }
ae262f0f6704488a9e04b225fc4b59ecce393a50
[ "Markdown", "C#" ]
7
Markdown
thejonesbrian/kilotrack-app
d0988ad6b03b54e64e7193cd2c076ea5629210a3
67b4e5666d3b5ffa489e20eeedd411a7bec1c192
refs/heads/master
<repo_name>dmytroleonenko/snakeplissken<file_sep>/configs.py import numpy as np FPS = 5000 FPS_PLAY = 48 W_WIDTH, W_HEIGHT = 150, 150 BLACK = np.array([0, 0, 0]) GRAY = np.array([128, 128, 128]) CRIMSON = np.array([220, 20, 60]) WHITE = np.array([255, 255, 255]) GREEN = np.array([34, 139, 34]) SNAKE_SIZE = 10 SNAKE_SEPARATION = 1 WALL_SIZE = SNAKE_SIZE APPLE_SIZE = SNAKE_SIZE APPLE_QTD = 1 SNAKE_ALIVE_PRIZE = -8e-3 SNAKE_EAT_ITSELF_PRIZE = -1.0 WALL_PRIZE = -1.0 APPLE_PRIZE = 1 APPLE_RELOAD_STEPS = FPS_PLAY * 10 KEY = {"UP": 1, "DOWN": 2, "LEFT": 3, "RIGHT": 4} # Deep Learning Params IMG_SIZE = 84 BATCH_SIZE = 64 GAMMA = 0.999 EPS_START = 0.9 EPS_END = 0.01 EPS_DECAY = 1500 EPOCHS = 10_000 TARGET_UPDATE = 1_000 MODEL_SAVE = 20_000 MEM_LENGTH = 7_000 MEM_CLEAN_SIZE = 7_000 LEARNING_RATE = 1e-7 MOMENTUM = 0.95 <file_sep>/requirements.txt numpy==1.18.4 pygame==1.9.6 Pillow==7.1.1 numba==0.48.0 torch torchvision
1c9f5d6e253e58c785abc1743fad8462ee1bb286
[ "Python", "Text" ]
2
Python
dmytroleonenko/snakeplissken
7259ac23496a1a0fd046002e4281d5b5cba51638
a772f9b3311a5841105c59d5e257f37360444151
refs/heads/main
<repo_name>arifinabd/nodeJS-todo-list<file_sep>/database/config.js require('dotenv').config() const { DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT, DB_DIALECT, DB_LOGGING } = process.env; const sequalizeConfig = { dialect: DB_DIALECT, host: DB_HOST, port: parseInt(DB_PORT, 0), username: DB_USER, password: <PASSWORD>, database: DB_NAME, logging: DB_LOGGING, seederStorage: 'sequalize', seederStorageTableName: 'SequalizeData' } module.exports = sequalizeConfig;
d04eaa9adf529d5cc39b554c5dd4b3ff04c5dbe0
[ "JavaScript" ]
1
JavaScript
arifinabd/nodeJS-todo-list
adc4f07574958b7bd5359aaa7e06f08de437c0e9
9d5a964fbef7055d2577f690388bd7cc5498e89f
refs/heads/main
<file_sep>var userAnswerEl = document.querySelector("#user-form"); var answerInputBox = document.getElementById("answer"); var answerCheck = document.querySelector("#answer-check"); //Get answers from url var queryString = window.location.search; var urlParams = new URLSearchParams(queryString); var categoryTitle = urlParams.get("categoryTitle"); var categoryQuestion = urlParams.get("categoryQuestion"); var categoryAnswer = urlParams.get("categoryAnswer"); var difficulty = urlParams.get("difficulty"); document.querySelector("#trivia-question").textContent = "Question: " + categoryQuestion; document.querySelector("#trivia-categories").textContent = "The category is: " + categoryTitle; console.log(categoryAnswer); //add value to end of clickedButton array to end game once all buttons are clicked clickedButtons = JSON.parse(localStorage.getItem("clickedButtons")); //split clicked buttons list clickedButtonsList = clickedButtons.split(','); if (clickedButtonsList.length === 20) { clickedButtonsList = clickedButtonsList + ",done" localStorage.setItem("clickedButtons",JSON.stringify(clickedButtonsList)); } var formSubmitHandler = function (event) { event.preventDefault(); //get value from form input var userAnswerEl = answerInputBox.value.trim(); if (userAnswerEl) { checkAnswer(userAnswerEl); answerInputBox.value = ""; } else { alert("Please Enter an Answer!"); } }; var checkAnswer = function (userAnswerEl) { categoryAnswerLower = categoryAnswer.toLowerCase(); userAnswerLower = userAnswerEl.toLowerCase(); if (userAnswerLower === categoryAnswerLower) { console.log("Correct Answer"); answerCheck.innerHTML = ""; var answerCheckEl = document.createElement("h4"); answerCheckEl.textContent = "Correct!"; answerCheckEl.classList.add("column", "has-text-success"); answerCheck.appendChild(answerCheckEl); setTimeout(function () { //bring user back to category page after answering question scorePoints(); }, 500); } else { console.log("Wrong Answer"); answerCheck.innerHTML = ""; var answerCheckEl = document.createElement("h4"); answerCheckEl.textContent = "Incorrect!"; answerCheckEl.classList.add("column", "has-text-danger"); answerCheck.appendChild(answerCheckEl); setTimeout(function () { window.location.replace("./category.html"); }, 500); } }; var scorePoints = function() { var score = JSON.parse(localStorage.getItem("score")); score = parseInt(score); score = score + parseInt(difficulty); localStorage.setItem("score",JSON.stringify(score)); window.location.replace("./category.html"); }; var loadScore = function() { var score = JSON.parse(localStorage.getItem("score")); //assign scores to page if (!score){ score = 0; document.querySelector("#current-score").textContent = "Score: " + 0;; } else { document.querySelector("#current-score").textContent = "Score: " + score; } }; // progress bar fuctions function timer(time, update, complete) { var start = new Date().getTime(); var interval = setInterval(function () { var now = time - (new Date().getTime() - start); if (now <= 0) { clearInterval(interval); complete(); } else update(Math.floor(now / 1000)); }, 10); } timer( 30000, function move() { // updates bar var element = document.getElementById("progress"); element.value += 0.01 }, function () { // when finished, return to question selection page. console.log("Timer complete!"); //add score to the value of the replaced html setTimeout(function() { //bring user back to category page after timer displays it is over window.location.replace("./category.html") },1000); } ) //getQuestionData(); userAnswerEl.addEventListener("submit", formSubmitHandler); //load score loadScore();<file_sep>var startButtonEl = document.querySelector("#start-btn"); var leaderBoardButtonEl = document.querySelector("#leaderboard-btn"); var startNewGame = function () { //remove the old categories to refresh the page with new ones. localStorage.removeItem("categoryIds","categoryTitles"); localStorage.removeItem("categoryTitles"); localStorage.setItem("score",JSON.stringify(0)); localStorage.removeItem("clickedButtons"); window.location.replace("./category.html"); } //start a new game when the start button is clicked startButtonEl.addEventListener("click",startNewGame); //change html page when leaderboard button is clicked leaderBoardButtonEl.addEventListener("click", function() { window.location.replace("./leaderboard.html"); });<file_sep># Trivia Kings - Jeopardy Style Questions for Extremely High IQs ## Description * Test your trivia skills with Trivia Kings, a simple game that uses previous Jeopardy questions. Each question will be worth an amount of points. See how many you can accumulate! ## Installation https://jakerobs.github.io/group-12/ ## Preview <img width="974" alt="Screen Shot 2021-01-05 at 5 18 19 PM" src="https://user-images.githubusercontent.com/73309832/103714086-05b12800-4f7b-11eb-8e2f-c2b612d2457b.png"> <img width="1343" alt="Screen Shot 2021-01-05 at 5 18 40 PM" src="https://user-images.githubusercontent.com/73309832/103713824-7a379700-4f7a-11eb-8653-b2965a4e0416.png"> ## Instructions * From the homepage, you can choose to start the game, view scores or choose an avatar. * When choosing to start a game, you have 4 categories with several questions listed underneath. * Upon picking a question, you have 30 seconds to answer it. * Answering questions right will give you points, answering wrong will not give you any points. * At least attempt to answer every question to finish the game and recieve your score. ## Future Development * Add a GIPHY API for correct and wrong answers * Add quick play mode with fewer questions for arcade style play <file_sep>//get leaderboard data and parse into array that is split and then sort by highest score leaderboard = JSON.parse(localStorage.getItem("leaderboard")); //only split leaderboard if there is more than one value in it if (leaderboard.length > 1){ leaderboardArray = leaderboard.split(","); } else{ leaderboardArray = leaderboard; } //sort from hightest to lowest score leaderboardArray.sort(function(a, b){return b - a}); //add the items to the dom var leaderboardPopulator = function () { var name = JSON.parse(localStorage.getItem("name")); if (!name){ getName(); } for (var i = 0; i < leaderboardArray.length; i++) { var containerEl = document.createElement("div"); containerEl.classList.add("grid-container"); //create score element var scoreEl = document.createElement("div"); scoreEl.classList.add("grid-child"); scoreEl.classList.add("score"); scoreEl.textContent = leaderboardArray[i]; //create name element var nameEl = document.createElement("div"); nameEl.classList.add("grid-child"); nameEl.classList.add("name"); nameEl.textContent = name; //add avatar next var avatarEl = document.createElement("img"); avatarEl.classList.add("grid-child"); avatarEl.classList.add("avatar"); avatarEl.classList.add("center"); avatarEl.src = `https://robohash.org/${name}`; //append name and then score to container containerEl.appendChild(nameEl); containerEl.appendChild(scoreEl); containerEl.appendChild(avatarEl); //append to page document.querySelector("#leaderboard-body").appendChild(containerEl); } } var getName = function(){ //create modal to get name value name = "NaN"; var leaderboardNameModalEl = document.createElement("div"); leaderboardNameModalEl.classList.add("modal"); //create input box and button to submit var buttonHolderEl = document.createElement("div"); buttonHolderEl.classList.add("columns"); //add text var nameDisplayEl = document.createElement("h3"); nameDisplayEl.textContent = "Enter Your Name Below"; //add buttons to button holder var nameInputBox = document.createElement("input"); nameInputBox.classList.add("column"); nameInputBox.classList.add("is-three-fifths"); nameInputBox.classList.add("button"); nameInputBox.classList.add("clear-btn"); nameInputBox.type = "text"; nameInputBox.placeholder = "Enter Your Name"; var nameSubmitButton = document.createElement("a"); nameSubmitButton.classList.add("button"); nameSubmitButton.classList.add("column"); nameSubmitButton.classList.add("is-two-fifth"); nameSubmitButton.classList.add("avatar-btn"); nameSubmitButton.onclick = function(){localStorage.setItem("name",JSON.stringify(nameInputBox.value)); window.location.reload();}; nameSubmitButton.textContent = "Submit"; //append objects to button holder buttonHolderEl.appendChild(nameInputBox); buttonHolderEl.appendChild(nameSubmitButton); //append to dom leaderboardNameModalEl.appendChild(nameDisplayEl); leaderboardNameModalEl.appendChild(buttonHolderEl); document.querySelector("#leaderboard-page").appendChild(leaderboardNameModalEl); }; leaderboardPopulator();
e1d3651428863bbf7399e62e5767ff8ea85d5663
[ "JavaScript", "Markdown" ]
4
JavaScript
jakerobs/group-12
063f6c7f9fe666ee19bb55be1f60ee0e6c8c80a5
0361d0999bea6ded0ec27dd168d1bef8130e09ff
refs/heads/master
<repo_name>kovesdinorbert/VoiceBeatSpa<file_sep>/VoiceBeatSpa.Core/Interfaces/IGenericRepository.cs using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace VoiceBeatSpa.Core.Interfaces { public interface IGenericRepository<T> { Task<T> FindById(Guid id); Task<List<T>> FindAll(Func<bool> id, params Func<bool>[] wheres); Task Create(T entity); Task Update(T entity); Task Delete(T entity); Task Delete(Guid id); } } <file_sep>/VoiceBeatSpa.Core/Interfaces/IHasId.cs using System; namespace VoiceBeatSpa.Core.Interfaces { public interface IHasId { Guid Id { get; set; } } } <file_sep>/VoiceBeatSpa.Core/Entities/PasswordRecoveryConfirmation.cs using System; namespace VoiceBeatSpa.Core.Entities { public class PasswordRecoveryConfirmation : _CrudBase { public Guid? UserId { get; set; } public User User { get; set; } } }<file_sep>/VoiceBeatSpa.Core/Enums/RoomEnum.cs namespace VoiceBeatSpa.Core.Enums { public enum RoomEnum { Room1, Room2, Room3, Studio } } <file_sep>/VoiceBeatSpa.Core/Interfaces/IHasCrud.cs using System; using VoiceBeatSpa.Core.Entities; namespace VoiceBeatSpa.Core.Interfaces { public interface IHasCrud : IHasIsActive { DateTime Created { get; set; } Guid CreatedBy { get; set; } DateTime? Modified { get; set; } Guid? ModifiedBy { get; set; } } } <file_sep>/VoiceBeatSpa.Core/Entities/Event.cs using System; namespace VoiceBeatSpa.Core.Entities { public class Event: _CrudBase { public string Subject { get; set; } public string Description { get; set; } public DateTime ReservedDay { get; set; } public int StartHour { get; set; } public string ThemeColor { get; set; } public bool IsFullDay { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public RoomEnum Room { get; set; } } } <file_sep>/VoiceBeatSpa.Core/Enums/PermissionEnum.cs namespace VoiceBeatSpa.Core.Enums { public enum PermissionEnum { AdminPermission, UserPermission } } <file_sep>/VoiceBeatSpa.Core/Entities/Role.cs using System; using System.Collections.Generic; using VoiceBeatSpa.Core.Interfaces; namespace VoiceBeatSpa.Core.Entities { public class Role: IHasId { public Guid Id { get; set; } public string Name { get; set; } public IList<Permission> Permissions { get; set; } = new List<Permission>(); public IList<User> Users { get; set; } = new List<User>(); } }<file_sep>/VoiceBeatSpa.Core/Entities/User.cs using System; using System.Collections.Generic; namespace VoiceBeatSpa.Core.Entities { public class User: _CrudBase { public string Email { get; set; } public string Password { get; set; } public string Salt { get; set; } public bool ChangePassword { get; set; } public DateTime? LastLogin { get; set; } public DateTime? LastWrongPassword { get; set; } public int WrongPasswordCount { get; set; } public IList<Role> Roles { get; set; } = new List<Role>(); public IList<PasswordRecoveryConfirmation> PasswordRecoveryConfirmations { get; set; } = new List<PasswordRecoveryConfirmation>(); public IList<ForgottenPassword> ForgottenPasswords { get; set; } = new List<ForgottenPassword>(); public string PhoneNumber { get; set; } public bool Newsletter { get; set; } public bool ReservationRuleAccepted { get; set; } } } <file_sep>/VoiceBeatSpa.Infrastructure/Services/EventService.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using VoiceBeatSpa.Core.Entities; using VoiceBeatSpa.Core.Interfaces; namespace VoiceBeatSpa.Infrastructure.Services { public class EventService : IEventService { public async Task<List<Event>> GetEvents() { throw new NotImplementedException(); } } } <file_sep>/VoiceBeatSpa.Core/Entities/ForgottenPassword.cs using System; namespace VoiceBeatSpa.Core.Entities { public class ForgottenPassword : _CrudBase { public string VerificationCode { get; set; } public Guid? UserId { get; set; } public User User { get; set; } } } <file_sep>/VoiceBeatSpa.Core/Entities/_CrudBase.cs using System; using VoiceBeatSpa.Core.Interfaces; namespace VoiceBeatSpa.Core.Entities { public abstract class _CrudBase : IHasId, IHasCrud { public Guid Id { get; set; } public DateTime Created { get; set; } public Guid CreatedBy { get; set; } public DateTime? Modified { get; set; } public Guid? ModifiedBy { get; set; } public bool IsActive { get; set; } } } } <file_sep>/VoiceBeatSpa.Core/Interfaces/IEventService.cs using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using VoiceBeatSpa.Core.Entities; namespace VoiceBeatSpa.Core.Interfaces { public interface IEventService { Task<List<Event>> GetEvents(); } } <file_sep>/VoiceBeatSpa.Core/Enums/LivingTextTypeEnum.cs using System; using System.Collections.Generic; using System.Text; namespace VoiceBeatSpa.Core.Enums { public enum LivingTextTypeEnum { EmailReservationSent, EmailRegistration, EmailForgottenPassword, StartPageText, } } <file_sep>/VoiceBeatSpa.Core/Entities/ExceptionLog.cs namespace VoiceBeatSpa.Core.Entities { public class ExceptionLog : _CrudBase { public string Message { get; set; } } } <file_sep>/VoiceBeatSpa.Core/Entities/Permission.cs using System; using System.Collections.Generic; using VoiceBeatSpa.Core.Interfaces; namespace VoiceBeatSpa.Core.Entities { public class Permission: IHasId { public Guid Id { get; set; } public string Name { get; set; } public IList<Role> Roles { get; set; } = new List<Role>(); } }<file_sep>/VoiceBeatSpa.Core/Entities/FileDocument.cs namespace VoiceBeatSpa.Core.Entities { public class FileDocument: _CrudBase { public string FileName { get; set; } public string MimeType { get; set; } public decimal Size { get; set; } public byte[] FileContent { get; set; } } } <file_sep>/VoiceBeatSpa.Infrastructure/Repository/GenericRepository.cs using System; using System.Collections.Generic; using System.Threading.Tasks; using VoiceBeatSpa.Core.Interfaces; namespace VoiceBeatSpa.Infrastructure.Repository { public class GenericRepository<T> : IGenericRepository<T> { public Task Create(T entity) { throw new NotImplementedException(); } public Task Delete(T entity) { throw new NotImplementedException(); } public Task Delete(Guid id) { throw new NotImplementedException(); } public Task<List<T>> FindAll(Func<bool> id, params Func<bool>[] wheres) { throw new NotImplementedException(); } public Task<T> FindById(Guid id) { throw new NotImplementedException(); } public Task Update(T entity) { throw new NotImplementedException(); } } } <file_sep>/VoiceBeatSpa.Core/Interfaces/IEmailService.cs using System.Threading.Tasks; using VoiceBeatSpa.Core.Enums; namespace VoiceBeatSpa.Core.Interfaces { public interface IEmailService { Task SendEmail(string from, string to, string subject, string body, LivingTextTypeEnum type); } } <file_sep>/VoiceBeatSpa.Core/Entities/LivingText.cs namespace VoiceBeatSpa.Core.Entities { public class LivingText { public string Text { get; set; } public bool IsHtmlEncoded { get; set; } } } <file_sep>/VoiceBeatSpa.Infrastructure/Services/EmailService.cs using System; using System.Threading.Tasks; using VoiceBeatSpa.Core.Enums; using VoiceBeatSpa.Core.Interfaces; namespace VoiceBeatSpa.Infrastructure.Services { public class EmailService : IEmailService { public async Task SendEmail(string from, string to, string subject, string body, LivingTextTypeEnum type) { throw new NotImplementedException(); } } } <file_sep>/VoiceBeatSpa.Core/Interfaces/IHasIsActive.cs namespace VoiceBeatSpa.Core.Interfaces { public interface IHasIsActive { bool IsActive { get; set; } } }
4bea7fc7c1386eeafa9d06f5a631e17e4582bec4
[ "C#" ]
22
C#
kovesdinorbert/VoiceBeatSpa
7063ec6b1be2ed5094f5c9f1ad8723f949035e8e
a623b8f965c1b5af019d2d57c6ea50f73b981d7e
refs/heads/master
<repo_name>morgancmartin/sample_app<file_sep>/db/migrate/.#20160514161925_add_activation_to_users.rb <EMAIL>@mbox.Home.20884:1463236134
2527c957cef5fc15be0f981967d7cd024de7d91d
[ "Ruby" ]
1
Ruby
morgancmartin/sample_app
58981eda47225341ba0f3fe401689a5ad22fe7eb
f3c76de6ac60b13fa3e4bc7698a45225b0e3389a
refs/heads/master
<repo_name>badhwars/Mobile-Web-App-Development<file_sep>/README.md # Mobile-Web-App-Development This file uses json file to populate the contents It contains a index hmtl file which takes information from a json file and creates a list of planets user can click on any planet which will redirect to another web page the second web page will show additional details about the selected planet Technologies used : javascript , jQuery, CSS, HTML <file_sep>/myscript.js // myscript for 03-AJAX01-Canada using AJAX var solarName; var background; var pList = new Array(); var rowID; class Planet { constructor (name, color,radius , image, dfrome,dfroms) { this.name = name; this.color = color; this.radius = radius; this.image = image; this.dfrome=dfrome; this.dfroms=dfroms; } } // document.ready statement $(document).ready(function (){ $.ajax({ type:"GET", url:"dataFiles/planets.json", dataType:"json", success:loadJSON, error:function(e) { alert(`${e.status} - ${e.statusText}`); } }); $("#backHead").click(function (){ $("#background").toggle() }); }); // loadJSON function function loadJSON(data){ solarName=data.solarSystem; //background=data.country.background; for(let planet of data.solarSystem.planets){ //if(prov.type=="province"){ //var distances=new Array(); // } pList.push(new Planet(planet.planetName,planet.planetColor,planet.planetRadiusKM,planet.image,planet.distInMillionsKM.fromSun,planet.distInMillionsKM.fromEarth)); } console.log(pList); mainScreen(data); } // mainScreen function function mainScreen(data){ $("#solarName").html(`${solarName} / Planets`); $("#background").html(background); $("#background").hide(); $("#planetList").html(""); for(x =0 ; x<pList.length;x++){ $("#planetList").append( `<li li-id='${x}'> <a href='otherPages/planetpage.html'><h2>${pList[x].name}</h2><img src="images/${pList[x].name}-icon.png"></a> </li> ` ); } } // Save data to local storage $(document).on("click", "#planetList >li", function() { localStorage.setItem("rowID",$(this).closest("li").attr("li-id")); localStorage.setItem("solarName",solarName); localStorage.setItem("pList",JSON.stringify(pList)); }); <file_sep>/myscriptplanet.js // myscript for 03-AJAX-01-Canada using AJAX for individual pagevar countryName; var pList = new Array(); var rowID; var cList = new Array(); var planetName; $(document).ready(function() { // get local storage values planetName=localStorage.getItem("solarName"); rowID=localStorage.getItem("rowID"); pList=JSON.parse(localStorage.getItem("pList")); $("#solar").html(planetName); $("#pname").html(pList[rowID].name); $("#pradius").html(pList[rowID].radius); $("#pcolor").html(pList[rowID].color); $("#dfrome").html(pList[rowID].dfrome + " Million Kms"); $("#dfroms").html(pList[rowID].dfroms + " Million Kms"); // $("#bg").html(`<img src='../images/${pList[rowID].flag}'>`); // $("#cities").html("Major cities : <br />"); $("#bg").css("background-image", "url(../images/"+ pList[rowID].name+".jpg )"); // fill in output fields //for(x=0;x<pList[rowID].cities[0].length;x++){ //$("#cities").append(`-${pList[rowID].cities[0][x]}<br />`); //} });
04d9cfd1e628d16e16e89d79f3359a2d8e29df5a
[ "Markdown", "JavaScript" ]
3
Markdown
badhwars/Mobile-Web-App-Development
94c1056abe2443514f3ac160e6015751f0d8cd8e
d4792f7b11f46c0a4efd914b6fa925e705025f2d
refs/heads/master
<repo_name>cmccord/Flare<file_sep>/app/src/main/java/sunglass/com/loco/Application.java package sunglass.com.loco; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.text.InputType; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.firebase.simplelogin.SimpleLogin; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.plus.Plus; import com.google.maps.android.ui.IconGenerator; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Created by cmccord on 4/21/15. */ public class Application extends android.app.Application { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private Firebase mFirebaseRef; private IconGenerator mIconFactory; private LocationManager mLocationManager; private LocationListener mLocationListener; private Location mLocation; private Criteria mCriteria; private String mProvider; private HashMap<String, Marker> mMarkers; private String mUserID; private Intent service = null; private boolean sharingStatus; private Activity inMapsActivity = null; private static Application inst; private SimpleLogin authClient; private AuthData authData; private HashMap<String,ValueEventListener> listeners = new HashMap<>(); private String circleSelected = "All Friends"; private ArrayList<String> friendsInCircle; private boolean justOpened = true; private HashMap<String, Marker> pinMarkers; @Override public void onCreate() { super.onCreate(); inst = this; setUpFirebase(); } public void notJustOpened() { justOpened = false; } public boolean wasJustOpened() { return justOpened; } public HashMap<String,Marker> getMarkers() { return mMarkers; } public static Application instance() { return inst; } public void setUpFirebase() { Firebase.setAndroidContext(this); mFirebaseRef = new Firebase("https://loco-android.firebaseio.com/"); } public Location getmLocation() { return mLocation; } public String getCircleSelected() { return circleSelected; } public void setCircleSelected(String s) { if(!circleSelected.equals(s)) { try { circleSelected = s; friendsInCircle = new ArrayList<>(); if (circleSelected.equals("All Friends")) { mFirebaseRef.child("users").child(mUserID).child("friends").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot d : dataSnapshot.getChildren()) friendsInCircle.add(d.getKey()); updateMarkersToCircle(); } @Override public void onCancelled(FirebaseError firebaseError) { } }); } else { mFirebaseRef.child("users").child(mUserID).child("circles").child(circleSelected).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot d : dataSnapshot.getChildren()) friendsInCircle.add(d.getKey()); updateMarkersToCircle(); } @Override public void onCancelled(FirebaseError firebaseError) { } }); } Log.v("friendsInCircle", friendsInCircle.toString()); } catch(Exception e) {Log.v("Error updating circle", e.toString());} } } private void updateMarkersToCircle() { Iterator<Map.Entry<String,Marker>> iter = mMarkers.entrySet().iterator(); while(iter.hasNext()) { Map.Entry item = iter.next(); String next = (String) item.getKey(); if(!friendsInCircle.contains(next) && !mUserID.equals(next)) { try { mFirebaseRef.child("users").child(next).removeEventListener(listeners.get(next)); } catch(Exception e) {Log.v("Removing friends error", "Couldn't remove listener from friend");} Log.v("Removing marker", next); mMarkers.get(next).remove(); iter.remove(); } } for(String s : friendsInCircle) { if(!mMarkers.containsKey(s)) { trackUser(s); } } } public void refreshCircleSelected() { try { friendsInCircle = new ArrayList<>(); if (circleSelected.equals("All Friends")) { mFirebaseRef.child("users").child(mUserID).child("friends").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot d : dataSnapshot.getChildren()) friendsInCircle.add(d.getKey()); updateMarkersToCircle(); } @Override public void onCancelled(FirebaseError firebaseError) { } }); } else { mFirebaseRef.child("users").child(mUserID).child("circles").child(circleSelected).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot d : dataSnapshot.getChildren()) friendsInCircle.add(d.getKey()); updateMarkersToCircle(); } @Override public void onCancelled(FirebaseError firebaseError) { } }); } Log.v("friendsInCircle", friendsInCircle.toString()); } catch(Exception e) {Log.v("Error updating circle", e.toString());} } public Firebase getFirebaseRef() { return mFirebaseRef; } public void setSimpleLogin(SimpleLogin simpleLogin) { authClient = simpleLogin; } public SimpleLogin getSimpleLoginRef() { return authClient; } public void setmUserID(String m) { mUserID = m; } public void setUpMarkers() { mMarkers = new HashMap<String, Marker>(); pinMarkers = new HashMap<String, Marker>(); } public void setmMap(GoogleMap m){ mMap = m; } public void setService(Intent i) { service = i; } public Intent getService() { return service; } public HashMap<String, ValueEventListener> getListeners() { return listeners; } public void setSharingStatus(boolean b, Context context) { sharingStatus = b; //if(getInMapsActivity()) { Log.v("cancelling share", "inside setSharingStatus"); //Activity activity = (Activity) context; setShareButton(context); //} } // sets color of share button in maps activity public void setShareButton(Context context) { Activity activity = MapsActivity.instance(); try { //Activity activity = (Activity) context; Button mainButton = (Button) activity.findViewById(R.id.topButton); Button bottomButton = (Button) activity.findViewById(R.id.shareButton); if (mainButton != null) { Log.v("Sharing Status", "" + getSharingStatus()); if (getSharingStatus()) { mainButton.setBackgroundResource(R.drawable.button_green); bottomButton.setBackgroundResource(R.drawable.share_button_green); bottomButton.setText("Cancel"); } else { mainButton.setBackgroundResource(R.drawable.button_red); bottomButton.setBackgroundResource(R.drawable.share_button_red); bottomButton.setText("Share"); } } } catch(Exception e){Log.v("cancelling share", "couldn't cast context as activity");} } public boolean getSharingStatus() { return sharingStatus; } public void setInMapsActivity(Activity activity) { inMapsActivity = activity; Log.v("setInMapsActivity", activity + ""); } public Activity getInMapsActivity() { return inMapsActivity; } public void updateLocation() { Log.v("GPS", "Firebase GPS updated?"); if (mFirebaseRef != null) { if (mLocation != null) { mFirebaseRef.child("users").child(mUserID).child("pos").setValue( mLocation.getLatitude() + "," + mLocation.getLongitude() ); } else if (mMap != null) { Log.v("GPS", "GPS listener hasn't activated, used other option"); Location l = mMap.getMyLocation(); mFirebaseRef.child("users").child(mUserID).child("pos").setValue( l.getLatitude() + "," + l.getLongitude() ); } mFirebaseRef.child("users").child(mUserID).child("timestamp").setValue(System.currentTimeMillis()); Log.v("GPS", "Firebase GPS updated."); } } public void trackUser(String u){ listeners.put(u, new ValueEventListener() { @Override public void onDataChange(DataSnapshot d2) { if (d2.getValue() != null) { Log.v("Track", d2.toString()); String name = ""; String pos = ""; String pic_string = ""; String pin = ""; String pin_description = ""; for (DataSnapshot deets : d2.getChildren()) { Log.v("Track", deets.toString()); if (deets.getKey().equals("name")){ name = deets.getValue().toString(); } else if (deets.getKey().equals("pos")){ pos = deets.getValue().toString(); } else if (deets.getKey().equals("picture")) { pic_string = deets.getValue().toString(); } else if(deets.getKey().equals("pin")) { pin = deets.getValue().toString(); } else if(deets.getKey().equals("pin_description")) { pin_description = deets.getValue().toString(); } } if (name.length() == 0){ name = d2.getKey(); } String uid = d2.getKey(); String[] loc = pos.split(","); LatLng l; if (loc.length > 1) { l = new LatLng(Double.parseDouble(loc[0]), Double.parseDouble(loc[1])); if (mMarkers.containsKey(uid)){ mMarkers.get(uid).setPosition(l); } else { Marker new_m; new_m = mMap.addMarker(new MarkerOptions(). icon(BitmapDescriptorFactory.fromBitmap(mIconFactory.makeIcon(name))). position(l). anchor(mIconFactory.getAnchorU(), mIconFactory.getAnchorV()). title(pic_string)); mMarkers.put(uid, new_m); } Log.v("Firebase Test", d2.getRef().getParent().getKey() + " moved to " + d2.getValue()); } else { // if location is gone, remove marker from map if (mMarkers.containsKey(uid)) { mMarkers.get(uid).remove(); mMarkers.remove(uid); } } String[] pinLoc = pin.split(","); LatLng pinL; if(pinLoc.length > 1) { pinL = new LatLng(Double.parseDouble(pinLoc[0]), Double.parseDouble(pinLoc[1])); if(pinMarkers.containsKey(uid)) { pinMarkers.get(uid).remove(); pinMarkers.remove(uid); } Marker marker = mMap.addMarker(new MarkerOptions().position( new LatLng(pinL.latitude, pinL.longitude)).title(name).snippet(pin_description)); marker.setAlpha((float) .99); pinMarkers.put(uid, marker); } else { if(pinMarkers.containsKey(uid)) { pinMarkers.get(uid).remove(); pinMarkers.remove(uid); } } } } @Override public void onCancelled(FirebaseError firebaseError) { } }); mFirebaseRef.child("users").child(u).addValueEventListener(listeners.get(u)); } public void cancelTracking(String uid) { try { mFirebaseRef.child("users").child(uid).removeEventListener(listeners.get(uid)); } catch(Exception e) {Log.v("Removing friends error", "Couldn't remove listener from friend");} if(!uid.equals(mUserID) && mMarkers.containsKey(uid)) { Log.v("Removing marker", uid); mMarkers.get(uid).remove(); mMarkers.remove(uid); } for(String key : mMarkers.keySet()) { Log.v("Marker", key); } } public boolean setUpGPS() { mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mCriteria = new Criteria(); mCriteria.setAccuracy(Criteria.ACCURACY_FINE); Log.v("LocationNews", mCriteria.toString()); mProvider = mLocationManager.getBestProvider(mCriteria, true); Log.v("LocationNews", mProvider); boolean isEnabled = mLocationManager.isProviderEnabled(mProvider); Log.v("LocationNews", String.valueOf(isEnabled)); if (isEnabled) { // Define a listener that responds to location updates mLocationListener = new LocationListener() { public void onLocationChanged(Location location) { // Called when a new location is found by the network location provider. Log.v("LocationNews", location.getLatitude() + " " + location.getLongitude()); mLocation = location; } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; // Register the listener with the Location Manager to receive location updates mLocationManager.requestLocationUpdates(mProvider, 0, 1, mLocationListener); return true; } else return false; } public void setUpFactory() { mIconFactory = new IconGenerator(this); mIconFactory.setStyle(IconGenerator.STYLE_GREEN); mIconFactory.setRotation(90); mIconFactory.setContentRotation(-90); mIconFactory.setTextAppearance(R.style.marker); } public void trackAll(final Context context) { if (mFirebaseRef != null) { authData = mFirebaseRef.getAuth(); if(authData == null) { Toast.makeText(context, "Please Log In", Toast.LENGTH_SHORT).show(); Intent i = new Intent(context, loginActivity.class); startActivity(i); } mUserID = authData.getUid(); mFirebaseRef.child("users").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { boolean noFriends = !dataSnapshot.child(mUserID).hasChild("friends"); // track the current user trackUser(mUserID); // for (DataSnapshot d : dataSnapshot.getChildren()) { // Log.v("Firebase Test", d.getKey().toString()); // String curr = d.getKey().toString(); // trackUser(curr); // } // if (mIsNew) // createNewUser(); if (noFriends) { ((MapsActivity) context).noFriendsDialog(); } // track friends else { for(DataSnapshot d : dataSnapshot.child(mUserID).child("friends").getChildren()) { String curr = d.getKey(); trackUser(curr); } } } @Override public void onCancelled(FirebaseError firebaseError) { } }); } } public static String encodeTobase64(Bitmap image) { Bitmap immagex=image; ByteArrayOutputStream baos = new ByteArrayOutputStream(); immagex.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT); Log.v("Encoding Bitmap", imageEncoded); return imageEncoded; } public static Bitmap decodeBase64(String input) { byte[] decodedByte = Base64.decode(input, 0); return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); } } <file_sep>/app/src/main/java/sunglass/com/loco/LocationService.java package sunglass.com.loco; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class LocationService extends Service { LocationShareReceiver alarm = new LocationShareReceiver(); public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { int interval = Integer.parseInt(intent.getStringExtra("frequency")); int d = Integer.parseInt(intent.getStringExtra("duration")); long expiration = System.currentTimeMillis() + 1000*60*d; Log.v("duration", d + ""); alarm.SetAlarm(LocationService.this, interval, expiration); return START_NOT_STICKY; } public void onStart(Context context,Intent intent, int startId) { int interval = Integer.parseInt(intent.getStringExtra("frequency")); int d = Integer.parseInt(intent.getStringExtra("duration")); long expiration = System.currentTimeMillis() + 1000*60*d; alarm.SetAlarm(context, interval, expiration); } @Override public IBinder onBind(Intent intent) { return null; } } <file_sep>/app/src/main/java/sunglass/com/loco/newFriendsActivity.java package sunglass.com.loco; import android.app.Activity; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.MultiAutoCompleteTextView; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.tokenautocomplete.TokenCompleteTextView; import java.util.HashMap; import java.util.Map; /** * Created by cmccord on 4/29/15. */ public class newFriendsActivity extends Activity { private Firebase ref; private Application app; private Person[] people; //private ArrayAdapter<Person> adapter; private ContactsCompletionView completionView; private AuthData authData; private String userID; private Button saveButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_newfriends); app = (Application) this.getApplication(); ref = app.getFirebaseRef(); if(ref != null) { authData = ref.getAuth(); if(authData != null) userID = authData.getUid(); } saveButton = (Button) findViewById(R.id.save_button); completionView = (ContactsCompletionView) findViewById(R.id.searchView); completionView.setVisibility(View.INVISIBLE); if(ref != null && authData != null) { ref.child("users").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { boolean hasFriends = snapshot.child(userID).hasChild("friends"); int numFriends = 0; if(hasFriends) numFriends = (int) snapshot.child(userID).child("friends").getChildrenCount(); people = new Person[(int) snapshot.getChildrenCount() - 1 - numFriends]; int i = 0; // MAKE SURE YOU CAN'T FRIEND YOURSELF OR A CURRENT FRIEND for (DataSnapshot d : snapshot.getChildren()) { if(d.getKey().equals(userID)) continue; if(hasFriends && snapshot.child(userID).child("friends").hasChild(d.getKey())) continue; String email; try { email = d.child("email").getValue().toString(); } catch (Exception e) { email = ""; } String name; try { name = d.child("name").getValue().toString(); } catch(Exception e) {name = "";} String uid = d.getKey(); people[i] = new Person(name, email); people[i].setUid(uid); if(d.hasChild("picture")) people[i].setImage(Application.decodeBase64(d.child("picture").getValue().toString())); Log.v("Getting users", people[i].toString()); i++; } PersonAdapter adapter = new PersonAdapter(newFriendsActivity.this, R.layout.listview_item_row, people); //adapter = new ArrayAdapter<Person>(newFriendsActivity.this, android.R.layout.simple_list_item_1, people); completionView.setAdapter(adapter); completionView.setVisibility(View.VISIBLE); final DataSnapshot s = snapshot; saveButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { Map friends = new HashMap<>(); int numFriendsAdded = 0; for (Object token : completionView.getObjects()) { String uid = ((Person) token).getUid(); // make sure its a real user if (!s.hasChild(uid)) continue; friends.put(uid, uid); if(app.getCircleSelected().equals("All Friends")) app.trackUser(uid); if (!s.child(uid).hasChild("friends") || !s.child(uid).child("friends").hasChild(userID)) { Map requests; if (s.child(uid).hasChild("requests")) requests = (Map) s.child(uid).child("requests").getValue(); else requests = new HashMap<>(); requests.put(userID, userID); Map update = new HashMap<>(); update.put("requests", requests); ref.child("users").child(uid).updateChildren(update); } if (s.child(userID).hasChild("requests") && s.child(userID).child("requests").hasChild(uid)) ref.child("users").child(userID).child("requests").child(uid).removeValue(); Log.v("Adding Friend", uid); numFriendsAdded++; } if (s.child(userID).hasChild("friends")) { ref.child("users").child(userID).child("friends").updateChildren(friends); } else { Map update = new HashMap<>(); update.put("friends", friends); ref.child("users").child(userID).updateChildren(update); } if (numFriendsAdded > 1) Toast.makeText(getApplicationContext(), "Friends Added!", Toast.LENGTH_SHORT).show(); else if (numFriendsAdded > 0) Toast.makeText(getApplicationContext(), "Friend Added!", Toast.LENGTH_SHORT).show(); } catch(Exception e) { Log.v("Error adding friends", e.toString()); Toast.makeText(getApplicationContext(), "Could not add friends", Toast.LENGTH_SHORT).show(); } finish(); } }); } @Override public void onCancelled(FirebaseError firebaseError) { // Do nothing. } }); } } } <file_sep>/app/src/main/java/sunglass/com/loco/editProfileActivity.java package sunglass.com.loco; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.method.KeyListener; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.firebase.simplelogin.FirebaseSimpleLoginError; import com.firebase.simplelogin.SimpleLogin; import com.firebase.simplelogin.SimpleLoginCompletionHandler; import java.util.HashMap; import java.util.Map; public class editProfileActivity extends Activity { private EditText mEmail; private EditText mDisplayName; private EditText mPassword; private TextView mDescripText; private Button mRemoveUser; private Button mLogoutButton; private Button mSaveChangesButton; private Button mEditButton; private Button mCancelEditButton; private ImageButton mProPic; private Bitmap proPic; private String value; private String orig_display_name; private String orig_email; private AuthData authData; private InputMethodManager imm; private Firebase ref; private SimpleLogin authClient; private Application app; private final int MAX_CHARACTERS = 15; // private Application app; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_profile); app = (Application) this.getApplication(); mEmail = (EditText)findViewById(R.id.editEmail); mDisplayName = (EditText)findViewById(R.id.editDisplayName); mPassword = (EditText)findViewById(R.id.editPassword); mPassword.setVisibility(View.GONE); mDescripText = (TextView)findViewById(R.id.descrip_text); mRemoveUser = (Button) findViewById(R.id.removeUser_butt); mLogoutButton = (Button) findViewById(R.id.logoutButton); mSaveChangesButton = (Button) findViewById(R.id.save_changes_butt); mEditButton = (Button) findViewById(R.id.edit_butt); mCancelEditButton = (Button) findViewById(R.id.cancel_edit_butt); mProPic = (ImageButton) findViewById(R.id.editProPic); // mEmail.setKeyListener(null); mEmail.setClickable(false); mEmail.setCursorVisible(false); mEmail.setFocusable(false); mEmail.setFocusableInTouchMode(false); // mDisplayName.setKeyListener(null); mDisplayName.setClickable(false); mDisplayName.setCursorVisible(false); mDisplayName.setFocusable(false); mDisplayName.setFocusableInTouchMode(false); mCancelEditButton.setVisibility(View.GONE); ref = ((Application) this.getApplication()).getFirebaseRef(); authClient = ((Application) this.getApplication()).getSimpleLoginRef(); authData = ref.getAuth(); if (authData != null) { // mEmail.setHint(""+authData.getProviderData().get("email")); ref.child("users").child(authData.getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Map<String, Object> value = (Map<String, Object>) snapshot.getValue(); orig_display_name = (String) value.get("name"); orig_email = (String) value.get("email"); if(snapshot.hasChild("picture")) mProPic.setImageBitmap(Application.decodeBase64(snapshot.child("picture").getValue().toString())); // if (orig_email.equals("<EMAIL>")) // mProPic.setBackgroundResource(R.drawable.pro_pic); // else if (orig_email.equals("<EMAIL>")) // mProPic.setBackgroundResource(R.drawable.mccord); mDisplayName.setHint(orig_display_name); mEmail.setHint(orig_email); } @Override public void onCancelled(FirebaseError firebaseError) { // Do nothing. } }); } else { Toast.makeText(getApplicationContext(), "You are not authenticated; log in again.", Toast.LENGTH_SHORT).show(); Intent i = new Intent(editProfileActivity.this, loginActivity.class); app.notJustOpened(); startActivity(i); } mProPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { editProfileActivity.this.startActivityForResult(takePictureIntent, 1); } } }); Button backButton = (Button) findViewById(R.id.back_butt); backButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { finish(); } } ); mEditButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { AlertDialog.Builder alert = new AlertDialog.Builder(editProfileActivity.this); alert.setTitle("Verify Password:"); final EditText input = new EditText(editProfileActivity.this); input.setGravity(Gravity.CENTER); // input.setHint("<PASSWORD>"); input.setWidth(200); input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); input.requestFocus(); input.setImeOptions(EditorInfo.IME_ACTION_DONE); imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); // alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); alert.setView(input); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { value = input.getText().toString(); if (authClient != null) { authClient.changePassword(orig_email, value, value, new SimpleLoginCompletionHandler() { public void completed(FirebaseSimpleLoginError error, boolean success) { if (error != null) { Toast.makeText(getApplicationContext(), "Invalid Password", Toast.LENGTH_SHORT).show(); imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,0); // imm.hideSoftInputFromWindow(input.getWindowToken(),0); } else if (success) { imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,0); // imm.hideSoftInputFromWindow(input.getWindowToken(),0); Toast.makeText(getApplicationContext(), "Password Verified", Toast.LENGTH_SHORT).show(); mEmail.setVisibility(View.GONE); mEditButton.setVisibility(View.GONE); mCancelEditButton.setVisibility(View.VISIBLE); mDescripText.setVisibility(View.GONE); mPassword.setVisibility(View.VISIBLE); mLogoutButton.setVisibility(View.GONE); mSaveChangesButton.setVisibility(View.VISIBLE); mRemoveUser.setVisibility(View.VISIBLE); // mEmail.setKeyListener((KeyListener) mEmail.getTag()); mEmail.setClickable(true); mEmail.setCursorVisible(true); mEmail.setFocusable(true); mEmail.setFocusableInTouchMode(true); // mDisplayName.setKeyListener((KeyListener) mDisplayName.getTag()); mDisplayName.setClickable(true); mDisplayName.setCursorVisible(true); mDisplayName.setFocusable(true); mDisplayName.setFocusableInTouchMode(true); mEmail.setText(""); mDisplayName.setText(""); mPassword.setText(""); mEmail.setHint("Update Email"); mDisplayName.setHint(orig_display_name); mPassword.setHint("<PASSWORD>"); // mEmail.clearFocus(); // mDisplayName.clearFocus(); // mPassword.clearFocus(); LinearLayout our_layout = (LinearLayout) editProfileActivity.this.findViewById(R.id.our_lin_layout); our_layout.requestFocus(); mRemoveUser.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { AlertDialog.Builder remove_alert = new AlertDialog.Builder(editProfileActivity.this); remove_alert.setTitle("Are you sure?"); remove_alert.setMessage("Deleting your profile will completely remove your profile from Flare. This cannot be undone."); remove_alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(editProfileActivity.this, LocationShareReceiver.class); intent.setAction("sunglass.com.loco.LOCATION_SHARE"); PendingIntent pi = PendingIntent.getBroadcast(editProfileActivity.this, 0, intent, PendingIntent.FLAG_NO_CREATE); boolean alarmUp = (pi != null); if(alarmUp) { LocationShareReceiver alarm = new LocationShareReceiver(); alarm.CancelAlarm(editProfileActivity.this); pi.cancel(); } Intent intent2 = new Intent(editProfileActivity.this, PinShareReceiver.class); intent2.setAction("sunglass.com.loco.PIN_SHARE"); PendingIntent pi2 = PendingIntent.getBroadcast(editProfileActivity.this, 0, intent2, PendingIntent.FLAG_NO_CREATE); if(pi2 != null) { PinShareReceiver alarm = new PinShareReceiver(); alarm.CancelAlarm(editProfileActivity.this); pi2.cancel(); } authClient.removeUser(orig_email, value, new SimpleLoginCompletionHandler() { public void completed(FirebaseSimpleLoginError error, boolean success) { if (error != null) { Toast.makeText(getApplicationContext(), "You are not authenticated; log in again.", Toast.LENGTH_SHORT).show(); Intent i = new Intent(editProfileActivity.this, loginActivity.class); app.notJustOpened(); startActivity(i); } else if (success) { authClient.logout(); Toast.makeText(getApplicationContext(), "Profile deleted. Rejoin the fire soon!", Toast.LENGTH_SHORT).show(); ref.child("users").child(authData.getUid()).removeValue(); Intent i = new Intent(editProfileActivity.this, loginActivity.class); app.notJustOpened(); startActivity(i); } } }); } }); remove_alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }); remove_alert.show(); } } ); mSaveChangesButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { // ONLY DISPLAY NAME CHANGES. if (mEmail.getText().toString().equals("") && !mDisplayName.getText().toString().equals("") && mPassword.getText().toString().equals("")) { if (mDisplayName.getText().toString().matches("([0-9]|[a-z]|[A-Z]| |_)+")) { if (mDisplayName.getText().toString().length() <= MAX_CHARACTERS) { ref.child("users").child(authData.getUid()).child("name").setValue(mDisplayName.getText().toString()); Toast.makeText(getApplicationContext(), "Success! Display Name Changed", Toast.LENGTH_SHORT).show(); // Update display name and email and reset hints. ref.child("users").child(authData.getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Map<String, Object> value = (Map<String, Object>) snapshot.getValue(); orig_display_name = (String) value.get("name"); orig_email = (String) value.get("email"); mDisplayName.setHint(orig_display_name); mEmail.setHint(orig_email); } @Override public void onCancelled(FirebaseError firebaseError) { // Do nothing. } }); mEmail.setVisibility(View.VISIBLE); mEditButton.setVisibility(View.VISIBLE); mCancelEditButton.setVisibility(View.GONE); mDescripText.setVisibility(View.VISIBLE); mRemoveUser.setVisibility(View.GONE); mPassword.setVisibility(View.GONE); mLogoutButton.setVisibility(View.VISIBLE); mSaveChangesButton.setVisibility(View.GONE); mEmail.setText(""); mDisplayName.setText(""); mPassword.setText(""); mEmail.setClickable(false); mEmail.setCursorVisible(false); mEmail.setFocusable(false); mEmail.setFocusableInTouchMode(false); mDisplayName.setClickable(false); mDisplayName.setCursorVisible(false); mDisplayName.setFocusable(false); mDisplayName.setFocusableInTouchMode(false); } else { Toast.makeText(getApplicationContext(), "Limit Display Name to " + MAX_CHARACTERS + " Characters", Toast.LENGTH_SHORT).show(); } } else if (mDisplayName.getText().toString().length() == 0) { Toast.makeText(getApplicationContext(), "Display Name Must Have At Least One Character", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Invalid Character(s) in Display Name", Toast.LENGTH_SHORT).show(); } } // ONLY PASSWORD CHANGES. else if (mEmail.getText().toString().equals("") && mDisplayName.getText().toString().equals("") && !mPassword.getText().toString().equals("")) { authClient.changePassword(orig_email, value, mPassword.getText().toString(), new SimpleLoginCompletionHandler() { public void completed(FirebaseSimpleLoginError error, boolean success) { if (error != null) { // if (mPassword.getText().toString().length()==0) // Toast.makeText(getApplicationContext(), "Password Must Have At Least One Character", Toast.LENGTH_SHORT).show(); // else Toast.makeText(getApplicationContext(), "Failure; Password Not Changed", Toast.LENGTH_SHORT).show(); } else if (success) { Toast.makeText(getApplicationContext(), "Success! Password Changed", Toast.LENGTH_SHORT).show(); // Update display name and email and reset hints. ref.child("users").child(authData.getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Map<String, Object> value = (Map<String, Object>) snapshot.getValue(); orig_display_name = (String) value.get("name"); orig_email = (String) value.get("email"); mDisplayName.setHint(orig_display_name); mEmail.setHint(orig_email); } @Override public void onCancelled(FirebaseError firebaseError) { // Do nothing. } }); mEmail.setVisibility(View.VISIBLE); mEditButton.setVisibility(View.VISIBLE); mCancelEditButton.setVisibility(View.GONE); mDescripText.setVisibility(View.VISIBLE); mRemoveUser.setVisibility(View.GONE); mPassword.setVisibility(View.GONE); mLogoutButton.setVisibility(View.VISIBLE); mSaveChangesButton.setVisibility(View.GONE); mEmail.setText(""); mDisplayName.setText(""); mPassword.setText(""); mEmail.setClickable(false); mEmail.setCursorVisible(false); mEmail.setFocusable(false); mEmail.setFocusableInTouchMode(false); mDisplayName.setClickable(false); mDisplayName.setCursorVisible(false); mDisplayName.setFocusable(false); mDisplayName.setFocusableInTouchMode(false); } } }); } // BOTH DISPLAY NAME AND PASSWORD CHANGE. else if (mEmail.getText().toString().equals("") && !mDisplayName.getText().toString().equals("") && !mPassword.getText().toString().equals("")) { if (mDisplayName.getText().toString().matches("([0-9]|[a-z]|[A-Z]| |_)+")) { if (mDisplayName.getText().toString().length() <= MAX_CHARACTERS) { ref.child("users").child(authData.getUid()).child("name").setValue(mDisplayName.getText().toString()); Toast.makeText(getApplicationContext(), "Success! Display Name Changed", Toast.LENGTH_SHORT).show(); authClient.changePassword(orig_email, value, mPassword.getText().toString(), new SimpleLoginCompletionHandler() { public void completed(FirebaseSimpleLoginError error, boolean success) { if (error != null) { // if (mPassword.getText().toString().length()==0) // Toast.makeText(getApplicationContext(), "Password Must Have At Least One Character", Toast.LENGTH_SHORT).show(); // else Toast.makeText(getApplicationContext(), "Failure; Password Not Changed", Toast.LENGTH_SHORT).show(); } else if (success) { Toast.makeText(getApplicationContext(), "Success! Password Changed", Toast.LENGTH_SHORT).show(); } } }); // Update display name and email and reset hints. ref.child("users").child(authData.getUid()).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { Map<String, Object> value = (Map<String, Object>) snapshot.getValue(); orig_display_name = (String) value.get("name"); orig_email = (String) value.get("email"); mDisplayName.setHint(orig_display_name); mEmail.setHint(orig_email); } @Override public void onCancelled(FirebaseError firebaseError) { // Do nothing. } }); mEmail.setVisibility(View.VISIBLE); mEditButton.setVisibility(View.VISIBLE); mCancelEditButton.setVisibility(View.GONE); mDescripText.setVisibility(View.VISIBLE); mRemoveUser.setVisibility(View.GONE); mPassword.setVisibility(View.GONE); mLogoutButton.setVisibility(View.VISIBLE); mSaveChangesButton.setVisibility(View.GONE); mEmail.setText(""); mDisplayName.setText(""); mPassword.setText(""); mEmail.setClickable(false); mEmail.setCursorVisible(false); mEmail.setFocusable(false); mEmail.setFocusableInTouchMode(false); mDisplayName.setClickable(false); mDisplayName.setCursorVisible(false); mDisplayName.setFocusable(false); mDisplayName.setFocusableInTouchMode(false); } else { Toast.makeText(getApplicationContext(), "Limit Display Name to " + MAX_CHARACTERS + " Characters", Toast.LENGTH_SHORT).show(); } } else if (mDisplayName.getText().toString().length() == 0) { Toast.makeText(getApplicationContext(), "Display Name Must Have At Least One Character", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Invalid Character(s) in Display Name", Toast.LENGTH_SHORT).show(); } } else { mDisplayName.setHint(orig_display_name); mEmail.setHint(orig_email); mEmail.setVisibility(View.VISIBLE); mEditButton.setVisibility(View.VISIBLE); mCancelEditButton.setVisibility(View.GONE); mDescripText.setVisibility(View.VISIBLE); mRemoveUser.setVisibility(View.GONE); mPassword.setVisibility(View.GONE); mLogoutButton.setVisibility(View.VISIBLE); mSaveChangesButton.setVisibility(View.GONE); mEmail.setText(""); mDisplayName.setText(""); mPassword.setText(""); mEmail.setClickable(false); mEmail.setCursorVisible(false); mEmail.setFocusable(false); mEmail.setFocusableInTouchMode(false); mDisplayName.setClickable(false); mDisplayName.setCursorVisible(false); mDisplayName.setFocusable(false); mDisplayName.setFocusableInTouchMode(false); } } } ); } } }); } else { Toast.makeText(getApplicationContext(), "You are not authenticated; log in again.", Toast.LENGTH_SHORT).show(); Intent i = new Intent(editProfileActivity.this, loginActivity.class); app.notJustOpened(); startActivity(i); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,0); // imm.hideSoftInputFromWindow(input.getWindowToken(),0); } }); alert.show(); } } ); mCancelEditButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { mEmail.setVisibility(View.VISIBLE); mEditButton.setVisibility(View.VISIBLE); mCancelEditButton.setVisibility(View.GONE); mDescripText.setVisibility(View.VISIBLE); mPassword.setVisibility(View.GONE); mLogoutButton.setVisibility(View.VISIBLE); mSaveChangesButton.setVisibility(View.GONE); mRemoveUser.setVisibility(View.GONE); mEmail.setHint(orig_email); mDisplayName.setHint(orig_display_name); mEmail.setText(""); mDisplayName.setText(""); mPassword.setText(""); mEmail.setClickable(false); mEmail.setCursorVisible(false); mEmail.setFocusable(false); mEmail.setFocusableInTouchMode(false); mDisplayName.setClickable(false); mDisplayName.setCursorVisible(false); mDisplayName.setFocusable(false); mDisplayName.setFocusableInTouchMode(false); } } ); mLogoutButton.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(editProfileActivity.this, LocationShareReceiver.class); intent.setAction("sunglass.com.loco.LOCATION_SHARE"); PendingIntent pi = PendingIntent.getBroadcast(editProfileActivity.this, 0, intent, PendingIntent.FLAG_NO_CREATE); boolean alarmUp = (pi != null); if(alarmUp) { LocationShareReceiver alarm = new LocationShareReceiver(); alarm.CancelAlarm(editProfileActivity.this); pi.cancel(); } Intent intent2 = new Intent(editProfileActivity.this, PinShareReceiver.class); intent2.setAction("sunglass.com.loco.PIN_SHARE"); PendingIntent pi2 = PendingIntent.getBroadcast(editProfileActivity.this, 0, intent2, PendingIntent.FLAG_NO_CREATE); if(pi2 != null) { PinShareReceiver alarm = new PinShareReceiver(); alarm.CancelAlarm(editProfileActivity.this); pi2.cancel(); } try { authClient.logout(); } catch(Exception e) {Log.v("Error Logging Out", "Not authenticated");} Toast.makeText(getApplicationContext(), "Come Back Soon!", Toast.LENGTH_SHORT).show(); Intent i = new Intent(editProfileActivity.this, loginActivity.class); app.notJustOpened(); startActivity(i); } } ); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1 && resultCode == RESULT_OK) { Bundle extras = data.getExtras(); proPic = (Bitmap) extras.get("data"); if (proPic.getWidth() >= proPic.getHeight()){ proPic = Bitmap.createBitmap( proPic, proPic.getWidth()/2 - proPic.getHeight()/2, 0, proPic.getHeight(), proPic.getHeight() ); }else{ proPic = Bitmap.createBitmap( proPic, 0, proPic.getHeight()/2 - proPic.getWidth()/2, proPic.getWidth(), proPic.getWidth() ); } mProPic.setImageBitmap(proPic); Map pic = new HashMap<>(); pic.put("picture", Application.encodeTobase64(proPic)); ref.child("users").child(authData.getUid()).updateChildren(pic); Toast.makeText(getApplicationContext(), "Profile Picture Updated!", Toast.LENGTH_SHORT).show(); } } } <file_sep>/app/src/main/java/sunglass/com/loco/CustomInfoWindowAdapter.java package sunglass.com.loco; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.AuthData; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import java.util.Map; /** * Created by kwdougla on 5/5/15. */ public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { private View mymarkerview; private Context context; private Application app; private Marker marker; public CustomInfoWindowAdapter(Context context_given) { context = context_given; app = (Application) context; } public View getInfoWindow(Marker marker) { // If a pin, return null for default. if (marker.getAlpha() == (float) .99) { return null; } // If a person: LayoutInflater inflater = LayoutInflater.from(context); mymarkerview = inflater.inflate(R.layout.custom_info_window, null); this.marker = marker; render(); return mymarkerview; } public View getInfoContents(Marker marker) { return null; } private void render() { if (!marker.getTitle().equals("")) { ImageView image_disp = (ImageView) mymarkerview.findViewById(R.id.indiv_pro_pic); image_disp.setImageBitmap(Application.decodeBase64(marker.getTitle())); } } }<file_sep>/app/src/main/java/sunglass/com/loco/addFriendsActivity.java package sunglass.com.loco; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.ValueEventListener; import com.google.android.gms.maps.model.Marker; import java.util.HashMap; import java.util.Map; /** * Created by cmccord on 4/29/15. */ public class addFriendsActivity extends Activity { private Firebase ref; private Application app; private String userID; private Person[] friends; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_addfriends); app = ((Application)getApplication()); ref = app.getFirebaseRef(); try { userID = ref.getAuth().getUid(); } catch(Exception e) {userID = "";} Button mBackButton = (Button) findViewById(R.id.back_button); mBackButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); Button newFriend = (Button) findViewById(R.id.rightButton); newFriend.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(addFriendsActivity.this, newFriendsActivity.class); app.notJustOpened(); startActivity(i); } }); } @Override protected void onResume() { super.onResume(); try { ref.child("users").addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { int numFriends = (int) dataSnapshot.child(userID).child("friends").getChildrenCount(); friends = new Person[numFriends]; int i = 0; for(DataSnapshot d : dataSnapshot.child(userID).child("friends").getChildren()) { String name = (String) dataSnapshot.child(d.getKey()).child("name").getValue(); String email = (String) dataSnapshot.child(d.getKey()).child("email").getValue(); Bitmap pic; Person person = new Person(name, email); if(dataSnapshot.child(d.getKey()).hasChild("picture")) { pic = Application.decodeBase64(dataSnapshot.child(d.getKey()).child("picture").getValue().toString()); person.setImage(pic); } person.setUid(d.getKey()); friends[i] = person; i++; } PersonAdapter friendsArrayAdapter = new PersonAdapter(addFriendsActivity.this, R.layout.listview_item_row, friends); ListView listView = (ListView)findViewById(R.id.listView); listView.setAdapter(friendsArrayAdapter); final DataSnapshot s = dataSnapshot; listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { AlertDialog.Builder builder = new AlertDialog.Builder(addFriendsActivity.this); builder.setTitle("Would you like to remove " + friends[position].getName() + " as a friend?"); final String uid = friends[position].getUid(); // Set up the buttons builder.setPositiveButton("Remove", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Remove from friends list try { ref.child("users").child(userID).child("friends").child(uid).removeValue(); } catch(Exception e) {Log.v("Removing friend error", "Couldn't remove friend");} // Remove from their friends list or cancel request try { if(s.child(uid).hasChild("friends") && s.child(uid).child("friends").hasChild(userID)) ref.child("users").child(uid).child("friends").child(userID).removeValue(); else if(s.child(uid).hasChild("requests") && s.child(uid).child("requests").hasChild(userID)) ref.child("users").child(uid).child("requests").child(userID).removeValue(); } catch(Exception e) {Log.v("Removing friends error", "Couldn't remove you from their list");} app.refreshCircleSelected(); addFriendsActivity.this.onResume(); dialog.cancel(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); return true; } }); } @Override public void onCancelled(FirebaseError firebaseError) { } }); } catch(Exception e) {Log.v("addFriendsActivity", e.toString());} } } <file_sep>/app/src/main/java/sunglass/com/loco/PinService.java package sunglass.com.loco; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class PinService extends Service { PinShareReceiver alarm = new PinShareReceiver(); public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { int d = Integer.parseInt(intent.getStringExtra("duration")); long expiration = System.currentTimeMillis() + 1000*60*d; Log.v("duration", d + ""); alarm.SetAlarm(PinService.this, expiration); return START_NOT_STICKY; } public void onStart(Context context,Intent intent, int startId) { int d = Integer.parseInt(intent.getStringExtra("duration")); long expiration = System.currentTimeMillis() + 1000*60*d; alarm.SetAlarm(context, expiration); } @Override public IBinder onBind(Intent intent) { return null; } }
3ef3fa54b62f1ee203cfbb525af23fe2e2e0cbee
[ "Java" ]
7
Java
cmccord/Flare
8e4be363c1b4ef609a5c3f29cfffa3a02fafa9a3
1ebcf35132b6372a505071ca04416fa5436df3b8
refs/heads/master
<repo_name>SkyrimVovan/Eateries<file_sep>/Eateries/Page/ContentViewController.swift // // ContentViewController.swift // Eateries // // Created by Vladimir on 29/01/2020. // Copyright © 2020 Vladimir. All rights reserved. // import UIKit class ContentViewController: UIViewController { @IBOutlet weak var headerLabel: UILabel! @IBOutlet weak var subheaderLabel: UILabel! @IBOutlet weak var imageView: UIImageView! var header = "" var subheader = "" var imageFile = "" var index = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } <file_sep>/Eateries/NewEateryTableViewController.swift // // NewEateryTableViewController.swift // Eateries // // Created by Vladimir on 15/01/2020. // Copyright © 2020 Vladimir. All rights reserved. // import UIKit class NewEateryTableViewController: UITableViewController { var isVisited = false @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameTF: UITextField! @IBOutlet weak var addressTF: UITextField! @IBOutlet weak var typeTF: UITextField! @IBOutlet weak var yesButton: UIButton! @IBOutlet weak var noButton: UIButton! @IBAction func toggleIsVisitedPressed(_ sender: UIButton) { if sender == yesButton { sender.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1) noButton.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) isVisited = true } else { sender.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) yesButton.backgroundColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) isVisited = false } } @IBAction func saveButtonPressed(_ sender: UIBarButtonItem) { if nameTF.text == "" || addressTF.text == "" || typeTF.text == "" { print("Не все поля заполнены") } else { if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext { let restaurant = Restaurant(context: context) restaurant.name = nameTF.text restaurant.location = addressTF.text restaurant.type = typeTF.text restaurant.isVisited = isVisited if let image = imageView.image { restaurant.image = UIImage.pngData(image)() } do { try context.save() print("Сохранение удалось") } catch let error as NSError { print("Не удалось сохранить данные \(error), \(error.userInfo)") } } performSegue(withIdentifier: "unwindSegueFromNewEatery", sender: self) } } override func viewDidLoad() { super.viewDidLoad() yesButton.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1) noButton.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { let alertController = UIAlertController(title: "Источник фотографии", message: nil, preferredStyle: .actionSheet) let cameraAction = UIAlertAction(title: "Камера", style: .default) { (action) in self.chooseImagePickerAction(source: .camera) } let photoLibAction = UIAlertAction(title: "Фото", style: .default) { (action) in self.chooseImagePickerAction(source: .photoLibrary) } let cancelAction = UIAlertAction(title: "Отмена", style: .cancel, handler: nil) alertController.addAction(cameraAction) alertController.addAction(photoLibAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) // для выбора фото с камеры или из галереи } tableView.deselectRow(at: indexPath, animated: true) } func chooseImagePickerAction(source: UIImagePickerController.SourceType) { if UIImagePickerController.isSourceTypeAvailable(source) { // проверяем доступна ли камера или галерея let imagePicker = UIImagePickerController() imagePicker.delegate = self// для установки картинки imagePicker.allowsEditing = true // когда делаем снимок или выбираем фотку, можно обрезать ее по краям, изменяя масштаю imagePicker.sourceType = source self.present(imagePicker, animated: true, completion: nil) // в info.plist даем доступ к камере и к фото } } // MARK: - Table view data source /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension NewEateryTableViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { // для работы delegate при установке картинки func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { imageView.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true dismiss(animated: true, completion: nil) } } <file_sep>/Eateries/AppDelegate.swift // // AppDelegate.swift // Eateries // // Created by Vladimir on 25/12/2019. // Copyright © 2019 Vladimir. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var coreDataStack = CoreDataStack() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().barTintColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1) UINavigationBar.appearance().tintColor = .white let statusBarView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 20)) // Создали View чтобы поместить его на Background и т.о. изменить его цвет statusBarView.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1) window?.rootViewController?.view.insertSubview(statusBarView, at: 1) if let barFont = UIFont(name: "AppleSDGothicNeo-Light", size: 24) { UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: barFont] } return true // изменяли вид navigation bar } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } func applicationWillTerminate(_ application: UIApplication) { self.coreDataStack.saveContext() } }
c1d715876b3d24e0ede1a2d4b1b0f5ab46275464
[ "Swift" ]
3
Swift
SkyrimVovan/Eateries
3e8f52ee76f391fb862198e72c268022f55649cf
bfcddfc766e7c44de7f6c888cd8c601451b3d126
refs/heads/master
<repo_name>phg98/heartbeat<file_sep>/README.md # heartbeat : Checks heart-beat signal ### How to install npm install ### How to run npm run start or node bin/www ### How to test npm test <file_sep>/utils/uuid.js const uuid4 = require('shortid'); const shortid = require('shortid'); const uuid = () => { if (process.env.NODE_ENV === 'test') { return '123abcABC'; } return shortid.generate(); } module.exports=uuid;<file_sep>/test/ping.test.js process.env.NODE_ENV = process.env.NODE_ENV || 'test' var request = require("supertest") const chai = require("chai") var chai_expect = chai.expect // chai.use(require('chai-as-promised')) var app; const TEST_UUID = '123abcABC' before(async () => { // Set Mock for MongoDB const MongoMemoryServer = require('mongodb-memory-server').MongoMemoryServer; const mongoServer = new MongoMemoryServer(); const uri = await mongoServer.getUri(); process.env.DB_CONNECTION = uri; app = require('../app') }) describe("ping", function () { var data = { serverId: "1sec", serverName: "1sec", timeout: 1000, phoneNumber: "+12345678", isTemp:true }; it("should err when no server", function (done) { request(app).get("/ping/server_not_exists") .expect(404) .end(done); }) it("should activate when first ping", function (done) { // Arrange request(app).post("/users/") .send(data) .expect(200) .end(() => { // Act request(app).get("/ping/" + TEST_UUID) .expect(200) .end(()=>{ // Assert request(app).get("/users/" + data.serverName) .expect(200) .expect((res)=> { chai_expect(res.body[0]).to.be.an('Object').that.includes({currentStatus: "Up"}) }) .end(done) }) }) }) })<file_sep>/configs/winston.js var fs = require('fs') var winston = require('winston') const moment = require('moment-timezone') const logDir = __dirname + '/../logs' if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir) } const myFormat = winston.format.printf(info => `${info.timestamp} [${info.level}]: ${info.label} - ${info.message}`); // function myTimeStamp () { // // return new Date().toString(); // return moment().format('hh:mm:ss.SSS'); // }; const appendTimestamp = winston.format((info, opts) => { if(opts.tz) info.timestamp = moment().tz(opts.tz).format(); return info; }); const infoTransport = new winston.transports.File({ filename: 'info.log', dirname: logDir, level: 'info', json: false, timestamp: true, colorize: true, format: winston.format.combine( winston.format.label({ label: 'heartbeat' }), appendTimestamp({ tz: 'Asia/Seoul' }), winston.format.timestamp(), myFormat ) }) const errorTransport = new winston.transports.File({ filename: 'error.log', dirname: logDir, level: 'error', json: false, timestamp: true, colorize: true, format: winston.format.combine( winston.format.label({ label: 'heartbeat' }), appendTimestamp({ tz: 'Asia/Seoul' }), winston.format.timestamp(), myFormat ) }) const consoleTransport = new (winston.transports.Console)({ level: 'debug', handleExceptions: true, json: false, // 로그형태를 json으로도 뽑을 수 있다. colorize: true, timestamp: true, format: winston.format.combine( winston.format.label({ label: 'heartbeat' }), appendTimestamp({ tz: 'Asia/Seoul' }), winston.format.colorize(), myFormat ) }) const logger = winston.createLogger({ // timestamp: myTimeStamp, // json: false, // format: winston.format.combine( // winston.format.label({ label: 'main' }), // winston.format.colorize(), // winston.format.timestamp(), // myFormat // ), transports: [infoTransport, errorTransport, consoleTransport] }) module.exports = logger; <file_sep>/models/server.js const mongoose = require('mongoose'); var Schema = mongoose.Schema; const ServerSchema = new Schema({ serverId: String, serverName: String, timeout: Number, phoneNumber: String, latestPingTime: Date, latestStartTime: Date, latestClearedTime: Date, latestTimeoutTime: Date, currentStatus: String, isTemp: Boolean, email: String }) module.exports = mongoose.model('Servers', ServerSchema);<file_sep>/app.js var createError = require('http-errors'); var express = require('express'); var cors = require('cors'); const rateLimit = require("express-rate-limit"); // Enable if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc) // see https://expressjs.com/en/guide/behind-proxies.html // app.set('trust proxy', 1); var path = require('path'); var cookieParser = require('cookie-parser'); var morgan = require('morgan'); var logger = require('./configs/winston'); const stream = { write: message => { logger.info(message) } } const pingService = require('./services/pingService') pingService.init(); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var pingRouter = require('./routes/ping'); var app = express(); const dotenv = require('dotenv'); dotenv.config(); if (process.env.NODE_ENV === 'development') { app.use(cors()); } else { app.use(cors({origin:"http://test.myserverdown.com"})); } // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(morgan('combined', {stream})) app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); let limiter = rateLimit({ windowMs: 1 * 60 * 1000, // 1 minutes max: 1 // limit each IP to 1 requests per windowMs }); if (process.env.NODE_ENV === 'development') { limiter = rateLimit({ windowMs: 30 * 1000, // 30 seconds max: 1 // limit each IP to 1 requests per windowMs }); } else if (process.env.NODE_ENV === 'test') { limiter = rateLimit({ windowMs: 1 * 1000, // 1 seconds max: 1000 }); } app.post('/users', limiter); app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/ping', pingRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; <file_sep>/services/pingService.js const mongoose = require('mongoose'); // const Server = require('../models/server') var Server; try { Server = mongoose.model('Servers') } catch (error) { Server = require('../models/server'); } const dotenv = require('dotenv') dotenv.config(); const logger = require('../configs/winston') let timerList = {}; var pingService = {} pingService.end = function(callback) { mongoose.disconnect(()=>{ logger.info("Disconnected from DB"); if (callback != undefined) callback(); }) } pingService.init = function(callback) { mongoose.connect( process.env.DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true }, async (err)=>{ if (err) { logger.error(`DB connection error : ${err}`) return err } logger.info('Connected to DB' + process.env.DB_CONNECTION); // set timers for saved items try{ let activeServerList = await Server.find({currentStatus: "Up"}); logger.info('Start watching for active servers:'); for (const server of activeServerList) { logger.info(server); var id = server.serverId; var timeLeft = server.latestStartTime.getTime() + server.timeout - new Date().getTime(); timeLeft = timeLeft > 0 ? timeLeft : server.timeout; var newTimer = setTimeout(async function(){ logger.info("ID:" + id + " TimeOut!"); await Server.updateOne({serverId: id}, { $set : {latestTimeoutTime: new Date(), currentStatus: "Down"}}); pingService.send_notification(server) delete timerList[id]; }, timeLeft); timerList[id] = newTimer; logger.info("Set timeout to timeLeft: " + timeLeft + "msec"); } if (callback != undefined) callback(); } catch (err) { return err; } } ); } var AWS = require('aws-sdk') if ((process.env.NODE_ENV !== 'test') && (!process.env.AWS_ACCESS_KEY_ID)) { AWS.config.loadFromPath('./.credentials.json'); } pingService.send_notification = server => { var messageParams = { Message : "Heartbeat Error on server:" + server.serverName, PhoneNumber: server.phoneNumber } if (process.env.NODE_ENV !== 'production') { // 개발모드일때는 문자메세지 보내지 않고 이메일보낸다. logger.info(messageParams.Message); logger.info("Call " + messageParams.PhoneNumber) if (!server.email) { logger.error("E-mail address not found."); } let emailParams = { Destination: { ToAddresses: [server.email], // 받는 사람 이메일 주소 CcAddresses: [], // 참조 BccAddresses: [] // 숨은 참조 }, Message: { Body: { Text: { Data: `서버(${server.serverName})에서 응답이 없습니다.`, // 본문 내용 Charset: "utf-8" // 인코딩 타입 } }, Subject: { Data: `서버(${server.serverName})에서 응답이 없습니다.`, // 제목 내용 Charset: "utf-8" // 인코딩 타입 } }, Source: "<EMAIL>", // 보낸 사람 주소 ReplyToAddresses: [] // 답장 받을 이메일 주소 } var sendPromise = new AWS.SES({ apiVersion: '2010-12-01' }).sendEmail(emailParams).promise(); sendPromise.then( function (data) { logger.info(data.MessageId); }).catch( function (err) { logger.info(err, err.stack); }); } else { var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(messageParams).promise(); publishTextPromise.then( function(data) { logger.info("Message sent. ID is " + data.MessageId) }).catch( function(err) { logger.error(err, err.stack); }) } } pingService.handlePing = async function(id) { let foundServer = await Server.find({serverId: id}); if (foundServer.length == 0) { logger.error("Server Not Found Error"); throw new Error("Server Not Found Error"); } await Server.updateOne({serverId: id}, { $set : {latestPingTime: new Date()}}); // if timeout exists, clear it let timer = timerList[id]; if (timer !== undefined) { logger.info("Id:"+id+" Cleared.") clearTimeout(timer); delete timerList[id]; await Server.updateOne({serverId: id}, { $set : {latestClearedTime: new Date(), currentStatus: "Up"}}); } let timeout = foundServer[0].timeout || 30000; var newTimer = setTimeout(async function(){ logger.info("ID:" + id + " TimeOut!"); await Server.updateOne({serverId: id}, { $set : {latestTimeoutTime: new Date(), currentStatus: "Down"}}); pingService.send_notification(foundServer[0]) delete timerList[id]; }, timeout); await Server.updateOne({serverId: id}, { $set : {latestStartTime: new Date(), currentStatus: "Up"}}); timerList[id] = newTimer; return 'Handled'; } module.exports = pingService<file_sep>/routes/users.js /* eslint-disable no-unused-vars */ var express = require('express'); var router = express.Router(); const logger = require('../configs/winston') const uuid = require('../utils/uuid') // const Server = require('../models/server'); var Server; try { var mongoose = require('mongoose'); Server = mongoose.model('Servers') } catch (error) { Server = require('../models/server'); } /* GET users listing. */ router.get('/', async function(req, res, next) { try { logger.info('GET users'); const servers = await Server.find(); logger.info(`users found, ${servers}`); res.json(servers); }catch(err){ logger.error('GET users failed'); res.json({message: err}); } }); /* Get user */ router.get('/:serverName', async function(req, res, next) { logger.info(req.params.serverName); try{ const foundServer = await Server.find({serverName: req.params.serverName}); if (foundServer.length) { logger.info('Found server : ' + foundServer); res.json(foundServer); } else { logger.error('Can NOT find server : ' + req.params.serverName); res.json(foundServer); } } catch (err) { logger.error('GET user failed for ' + req.params.serverName); res.status(404).json({message: err}); } }); /* POST user */ router.post('/', async function(req, res, next) { logger.info("Add server : " + JSON.stringify(req.body)); var server = new Server({ //serverId: req.body.serverId, serverId: uuid(), serverName: req.body.serverName, timeout: req.body.timeout, phoneNumber: req.body.phoneNumber, isTemp: req.body.isTemp, email: req.body.email, }) try{ // 서버이름이 이미 존재하면 에러처리한다. const foundServer = await Server.find({serverName: server.serverName}); logger.info(foundServer); if (foundServer.length) { let err = 'Server name already taken : ' + server.serverName logger.error(err); res.status(409).json({message: err}); return; } const savedServer = await server.save(); logger.info("Saved server : "+JSON.stringify(savedServer)) res.json(savedServer); } catch (err) { logger.error("Saved server error: "+JSON.stringify(err)) res.json({message: err}) } }); if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') { logger.info('enable DELETE on development mode.') /* DELETE user */ router.delete('/:serverName', async function (req, res, next) { logger.info(req.params.serverName); try { const removedServer = await Server.deleteOne({ serverName: req.params.serverName }); res.json(removedServer); } catch (err) { res.json({ message: err }) } }); } /* UPDATE user */ // router.patch('/:serverId', async function(req, res, next) { // logger.info(req.params.serverId); // try{ // const updatedServer = await Server.updateOne({serverId: req.params.serverId}, // { $set : req.body}); // res.json(updatedServer); // } catch (err) { // res.json({message: err}) // } // }); module.exports = router; <file_sep>/utils/uuid.test.js const expect = require('chai').expect; const uuid = require('../utils/uuid') describe('uuid', ()=>{ it('should make uuid', ()=>{ expect(uuid()).match(/\b[0-9A-Fa-f]{9}\b/g) }) }) <file_sep>/test/users.test.js process.env.NODE_ENV = process.env.NODE_ENV || 'test' var request = require("supertest") var chai_expect = require("chai").expect var app; before(async () => { // Set Mock for MongoDB const MongoMemoryServer = require('mongodb-memory-server').MongoMemoryServer; const mongoServer = new MongoMemoryServer(); const uri = await mongoServer.getUri(); process.env.DB_CONNECTION = uri; app = require('../app') }) describe("homepage", function () { var data = { serverId: "5sec", serverName: "5sec", timeout: 5000, phoneNumber: "+12345678", isTemp:true }; it("welcomes the user", function (done) { request(app).get("/") .expect(200) .expect(/Welcome to Express/, done) }) it("should empty when start", function (done) { request(app).get("/users") .expect(200) .expect((res)=> {console.log(res.body);chai_expect(res.body).to.be.empty}) .end(done) }) it("should add user", function (done) { request(app).post("/users") .send(data) .expect(200) .expect((res)=> {chai_expect(res.body.serverId).match(/\b[0-9A-Fa-f]{9}\b/g)}) .end(done); }) it("should show user", function (done) { request(app).get("/users") .expect(200) .expect((res)=> {console.log(res.body);chai_expect(res.body[0]).to.be.an('Object').that.includes({serverName: "5sec"})}) .end(done) }) it("should show specific user", function (done) { request(app).get("/users/"+data.serverName) .expect(200) .expect((res)=> {console.log(res.body);chai_expect(res.body[0]).to.be.an('Object').that.includes({serverName: "5sec"})}) .end(done) }) it("should delete user", function (done) { // Arrange // 이미 저장된 데이터가 1개 있으니 이것을 지우자. // Act request(app).delete("/users/"+data.serverName) .expect(200) .end(() => { // Assert request(app).get("/users") .expect(200) .expect((res)=> { chai_expect(res.body).to.be.empty; }) .end(done) }) }) })<file_sep>/TodayILearned.md # Today I Learned ... ## 2019-12-28 * 로그출력시 타임존에 맞게 출력되도록 수정 * 참고 : https://medium.com/front-end-weekly/node-js-logs-in-local-timezone-on-morgan-and-winston-9e98b2b9ca45 * moment 설치후에 mongodb-memory-server 모듈을 못찾는 문제가 있어서 다시 설치함. * npm i mongodb-memory-server --save-dev * 테스트시 --watch로 테스트하면 두번째 테스트에서 'OverwriteModelError: Cannot overwrite `Servers` model once compiled.' 에러 발생. 아래와 같이 해결함. ``` let users try { users = mongoose.model('users') } catch (error) { users = mongoose.model('users', <UsersSchema...>) } ``` * 개발노트북에서는 잘 동작하는데 Ubuntu서버에서는 서버추가기능이 동작하지 않는다. * 이전 버전으로 돌려보자. * git checkout -b old-project-state 0ad5a7a6 * __서버의 문제가 아니라 Postman으로 post명령을 보내는데 'json'을 'text'로 잘못 설정한것이 문제였음.__ * 다시 원래대로 돌리자. ## 2020-1-1 * 커버리지 측정후 vscode에서 실행된 라인과 안 된 라인 표시하기 * coverage-gutters extension을 설치하고, 커버리지 툴의 옵션을 아래와 같이 수정하면 된다. ``` "coverage": "nyc --reporter=lcov --reporter=text npm test" ``` * 아직 Promise와 async/await를 잘 모르겠다.ㅠㅠ * API 테스트는 supertest 모듈을 사용하면 된다. users.test.js침조 ## 2020-1-6 * mocha 테스트시 일정시간 기다리려면 setTimeout을 그냥쓰면 안되고 Promise로 만들어서 써야한다. pingService.test.js 참고. ## 2020-1-7 * mocha 테스트시 async함수의 throw를 잡으려면 chai-as-promised를 설치하고 아래와 같이 쓰자 ```await expect(asyncFunc()).to.be.rejectedWith("error message")``` ## 2020-5-15 * git stash : 수정된 내용을 임시보관한다. * git stash list : 임시보관한 내용을 확인한다. * git stash pop : 임시보관했던 내용을 다시 적용한다. ## 2020-5-17 * mocha test시 에러 발생 : "before all" hook in "{root}": Error: Timeout of 2000ms exceeded * PC에 따라 서버 기동이 느려서 그렇다. mocha에 옵션으로 --timeout 10000 주어서 해결.<file_sep>/routes/ping.js var express = require('express'); var router = express.Router(); const pingService = require("../services/pingService") const logger = require('../configs/winston') /* GET ping from server. */ router.get('/:serverId', async function(req, res) { const id = req.params.serverId; logger.info("Got ping from " + id) try{ await pingService.handlePing(id); res.json({message:"Got ping", id: id}); } catch (err) { res.status(404).json({message: err}) } }); module.exports = router;
bed0258ad19fa145f32e4f2bd27cd9dc7e0b11d2
[ "Markdown", "JavaScript" ]
12
Markdown
phg98/heartbeat
39899fc90d3a6b27a0958f32a263bd0720f8fb66
a182504c43acc3ded5351fc5f948198c9886978f
refs/heads/master
<repo_name>Rikkubook/vue-cicd<file_sep>/src/components/Counter.test.js import { render, fireEvent} from '@testing-library/vue' import Counter from './Counter.vue' test('載入時title [當前點擊次數0]',()=>{ const { getByTestId } = render(Counter) const title = getByTestId('counterId') expect(title.innerHTML).toBe('當前點擊次數0') }) test('click [當前點擊次數1]', async()=>{ const { getByTestId, getByText } = render(Counter) const incrementButton = getByText('點我加1') // 拿到文字為 await fireEvent.click(incrementButton) // 要改成非同步點擊 const title = getByTestId('counterId') expect(title.innerHTML).toBe('當前點擊次數1') // 確認 })
37445addd1faae51b7dcfa2742d157d124aea34e
[ "JavaScript" ]
1
JavaScript
Rikkubook/vue-cicd
b023c2f99da0bdc6147f6bd6dd1ed8664366060b
34663ebcabdf9471616de0ed9e434e81a77b97db
refs/heads/master
<file_sep># Lenguajes de Marcas y Sistemas de Gestión de la Información ## Actividad 1 ### Equipo de trabajo: • <NAME> • <NAME> • <NAME> ### Ruta del [repositorio](https://github.com/sarnaizgarcia/LenguajesDeMarcasActividad1): https://github.com/sarnaizgarcia/LenguajesDeMarcasActividad1 ### Reparto de tareas: • Formulario de contacto – <NAME> • Índex – <NAME> • Quienes somos – <NAME> • CSS Y JAVASCRIPT – En conjunto ![JavaScript](assets/js.png "JavaScript") ![CSS](assets/css.png "CSS") ![HTML](assets/html.png "HTML") <file_sep>// Esta función nos permite abrir y cerrar el menú en la versión móvil. (function () { const menuButton = document.querySelector('.material-icons.menu-icon'); const menuOptions = document.querySelector('.menu-options'); // Con esta función, se cierra el menú si se pincha en cualquier lado de la pantalla // a excepción del menú y este está abierto. function closeMenu(event) { if ( menuOptions.classList.contains('open') && !event.target.classList.contains('menu-icon') ) { menuOptions.classList.remove('open'); } } // Despliega el menú si está cerrado. // Si está abierto lo cierra. function clickOnMenu() { if (menuOptions.classList.contains('open')) { menuOptions.classList.remove('open'); } else { menuOptions.classList.add('open'); } } // Esta función, hace el menú desplegable por teclado. function enterOnMenu(event) { if (event.key === 'Enter') { clickOnMenu(); } } // Recorremos todos los elementos acordeón. // Por cada elemento, borramos los eventos click y keyup para que no // Generar memory leaks y los volvemos a crear. document.removeEventListener('click', closeMenu); document.addEventListener('click', closeMenu); menuButton.removeEventListener('click', clickOnMenu); menuButton.addEventListener('click', clickOnMenu); menuButton.removeEventListener('keyup', enterOnMenu); menuButton.addEventListener('keyup', enterOnMenu); })() // Con este script de JS desencadenamos el despliegue y el cierre del menú en versión móvil.<file_sep>// Es una función autoejecutada, que crea un scope privado para evitar // conflictos con variables del mismo nombre. // Permite desplegar los elementos acordeón. (function () { // Esta función busca el elemento acordeón en el html. // Cuando lo encuentra, sale del bucle y lo devuelve. function searchAccordion(element) { while ((!element.classList.contains('accordion')) && (!element.classList.contains('main-body'))) { element = element.parentNode; } return element; } // Esta función abre y cierra el acordeón. function openCloseAccordion(event) { const accordion = searchAccordion(event.target); const section = accordion.classList.item(1); const text = document.querySelector(`.text.${section}`); if (accordion.classList.contains('open')) { accordion.classList.remove('open'); text.classList.remove('open'); } else { accordion.classList.add('open'); text.classList.add('open'); } } // Esta función, hace el acordeón desplegable por teclado. function enterOnAccordion(event) { if (event.key === 'Enter') { openCloseAccordion(event); } } // Esta constante es un array con todos nuestros elementos html de // la clase acordeón. const accordions = document.querySelectorAll('.accordion'); // Recorremos todos los elementos acordeón. // Por cada elemento, borramos los eventos click y keyup para que no // Generar memory leaks y los volvemos a crear. for (const accordion of accordions) { accordion.removeEventListener('click', openCloseAccordion); accordion.addEventListener('click', openCloseAccordion); accordion.removeEventListener('keyup', enterOnAccordion); accordion.addEventListener('keyup', enterOnAccordion); } })()
87621bbd6769aff9b6bf3bd3307bacb92b2a07e0
[ "Markdown", "JavaScript" ]
3
Markdown
sarnaizgarcia/LenguajesDeMarcasActividad1
3a8bd92a3224298cf7cac78f5d29edd1e5bc5818
1af9420856d31d73a792a03fe7f81e94725bd812
refs/heads/master
<file_sep># -*- coding: utf-8 -*- import sys import os import numpy as np import pandas as pd import time import cv2 #keras from keras.utils import to_categorical # fer2013 dataset: # Training 28709 # PrivateTest 3589 # PublicTest 3589 total 35887 #讀取資料, def read_csv(path_,fname_): #dir_path = 'D:/python/fer2013_/data' file_= os.path.join(path_,fname_).replace('\\','/') data = pd.read_csv(file_) num_of_instances = len(data) #獲取數據集的數量 print('number of instances',num_of_instances) #提取pixels,emotions,usages該columns的全部值 pixels = data[" pixels"] emotions = data['emotion'] usages = data[" Usage"] return pixels,emotions,usages #將訓練、測試集分開 def seperate_data(pixels_,emotions_,usages_): num_classes = 7 #表情有七類 x_train,y_train,x_test,y_test,y_test_label,x_vali,y_vali= [],[],[],[],[],[],[] for emotion,img,usage in zip(emotions_,pixels_,usages_): #同時遍歷多個數組或列表時,可用zip()函數進行遍歷 emotion_one = to_categorical(emotion,num_classes) # 將七類標籤轉成獨熱向量編碼one-hot encoding val = img.split(' ') pixels = np.array(val,'float32') if(usage == 'Training'): #or usage == 'PrivateTest' x_train.append(pixels) y_train.append(emotion_one) elif(usage == 'PrivateTest'): x_test.append(pixels) y_test.append(emotion_one) y_test_label.append(emotion) else: x_vali.append(pixels) y_vali.append(emotion_one) return x_train,y_train,x_test,y_test,y_test_label,x_vali,y_vali #將原圖48*48調整成224*224,符合VGGFACE的模型輸入大小 def resize_Img(train_): pixels_resize=[] for num_ in range(train_.shape[0]): if(num_ % 1000 == 0): print('now resize 48 --> 224 number',num_) pixels_resize.append(cv2.resize(train_[num_], (224, 224), interpolation=cv2.INTER_LINEAR)) #(224,224)→(224,224,3),也就是每個灰階像素copy三次到三個channels中 #stacked_img = np.stack((pixels_resize,)*3, axis=-1) pixels_=np.array(pixels_resize,'float32') #pixels_resize= np.dstack((pixels_,) * 3) return pixels_resize #x/y_train, x/y_test 轉換成numpy數組格式,並呼叫resize_Img()調成VGGface的224*224大小,方便後續處理 def transfer_numpy(xtrain_,ytrain_,xtest_,ytest_,xvali_,yvali_): #Training Set轉np.array → 48*48變成224*224 x_train = np.array(xtrain_) x_train = x_train.reshape(-1,48,48)#,1 #x_train= (x_train-np.min(x_train))/(np.max(x_train)-np.min(x_train)) #x_train_255 = x_train/255 x_train = np.stack((x_train,)*3, axis=-1)#變成3channel #x_train_resize=resize_Img(x_train) y_train = np.array(ytrain_) #Testing Set轉np.array → 48*48變成224*224 x_test = np.array(xtest_) x_test = x_test.reshape(-1,48,48)#,1 #x_test= (x_test-np.min(x_test))/(np.max(x_test)-np.min(x_test)) #x_test_255 = x_test/255 x_test = np.stack((x_test,)*3, axis=-1) #x_test_resize=resize_Img(x_test) y_test = np.array(ytest_) #cv2.imshow("original",x_train[2050].astype(np.uint8)) #cv2.imshow("resize",x_train_resize[2050].astype(np.uint8)) #cv2.waitKey(0) x_vali = np.array(xvali_) x_vali = x_vali.reshape(-1,48,48)#,1 #x_vali= (x_vali-np.min(x_vali))/(np.max(x_vali)-np.min(x_vali)) #x_vali_255 = x_vali/255 x_vali = np.stack((x_vali,)*3, axis=-1) #x_vali_resize=resize_Img(x_vali) y_vali = np.array(yvali_) return x_train,y_train,x_test,y_test,x_vali,y_vali#x_train_resize,y_train,x_test_resize,y_test def main(): dir_path = 'D:/wendy/fer2013_/data' pixels,emotions,usages=read_csv(dir_path,'icml_face_data.csv') x_train,y_train,x_test,y_test,y_test_label,x_vali,y_vali=seperate_data(pixels,emotions,usages) x_train,y_train,x_test,y_test,x_vali,y_vali=transfer_numpy(x_train,y_train,x_test,y_test,x_vali,y_vali) #存成npz檔 np.savez('./fer2013_/npz/vali_ch3_label_pri.npz',x_train,y_train,x_test,y_test,y_test_label,x_vali,y_vali) # arr_0:train_pixels / arr_1:train_emotion / arr_2:test_pixels / arr_3:test_emotion return if __name__=="__main__": start=time.clock() main() end=time.clock() print("total spend:",(end-start))<file_sep>import sys import cv2 from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import * from fer_ui import Ui_MainWindow from dlib_picture import start import numpy as np import time class mywindow(QtWidgets.QMainWindow): ## override the init function def __init__(self, parent = None): super(QMainWindow, self).__init__(parent) ## inherit self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("FER ! ") self.linkEvent() self.show() def linkEvent(self):## add link between model and view self.ui.Button_Load.clicked.connect(lambda :self.bt_load_image()) self.ui.Button_Predict.clicked.connect(lambda:self.bt_predict()) return def bt_load_image(self):#bt_load_imgae event 觸發,打開文件夾選取檔案,並檢查是否有讀取,若無則顯示no file! filename=QFileDialog.getOpenFileName(self,"choose picture","./",'Image Files(*.png *.jpg)') self.filename_=filename[0] if self.filename_=="": #print("No file !") self.ui.messagebox.setText('No file !') self.ui.messagebox.show() return None self.cvImg=cv2.imread(self.filename_) self.cvImg_gray=cv2.imread(self.filename_,0) #self.cvImg=cv2.imdecode(np.fromfile(self.filename_,dtype=np.uint8),-1) self.cvImg=cv2.resize(self.cvImg, (450,650)) self.cvImg_gray=cv2.resize(self.cvImg_gray, (450,650)) #顯示圖片 self.display_img_on_label(self.cvImg) def bt_predict(self):#bt_predict event 觸發 try: ###設定如果圖片為空則先讀取圖片###### self.cvImg except Exception as e: print("Img Warning: {}".format(e)) self.ui.messagebox.setText("Choose picture first ! ") self.ui.messagebox.show() return None start_time= time.time() self.predict_img,self.info =start(self.cvImg,self.cvImg_gray) print(time.time()-start_time) messagelist=['No face detected !'] if self.info in messagelist:####是否有偵測到圖片中的人臉 self.ui.messagebox.setText(self.info) self.ui.messagebox.show() else: self.display_img_on_label(self.predict_img) def display_img_on_label(self,cvimg):#將圖片顯示在label上 #圖片通道依灰階還彩色,轉成rgb if len(cvimg.shape) < 3 or cvimg.shape[2] == 1: #灰階圖 qimg = cv2.cvtColor(cvimg, cv2.COLOR_GRAY2RGB) else: #彩圖 qimg = cv2.cvtColor(cvimg, cv2.COLOR_BGR2RGB) #image_height, image_width, image_depth = qimg.shape image_height, image_width, image_depth = cvimg.shape qimg = QImage(qimg.data, image_width, image_height,image_width * image_depth,QImage.Format_RGB888) self.ui.Image_Show.setPixmap(QPixmap.fromImage(qimg)) def main(): app = QtWidgets.QApplication(sys.argv) window = mywindow() window.show() sys.exit(app.exec_()) if __name__ == '__main__': main()<file_sep>import dlib import cv2 import time from keras.models import load_model import numpy as np def show_emotion(frame,x,y,w,h,emotions,prob,predicted_e,show_high): font = cv2.FONT_ITALIC#cv2.FONT_HERSHEY_SIMPLEX #Drawing rectangle and showing output values on frame cv2.rectangle(frame, (x, y), (x + w, y + h),(125,125, 255),2) text_distance=15 if show_high: cv2.putText(frame,predicted_e,(x,y+h+text_distance),font,0.5,(255,255,255),1,cv2.LINE_AA) #cv2.putText(frame,predicted_e,(x,y+h+text_distance),font,0.5,(0, 0, 255),1,cv2.LINE_AA) else: #Angry for index in range(7): cv2.putText(frame, emotions[index] + ':', (x, y + h+text_distance), font,0.5, (255,255,255), 1, cv2.LINE_AA) text_distance+=15 #bar 92% y0 = 8 for score in prob.astype('int'): cv2.rectangle(frame,(x+75, y + h+y0), (x+75 + score,y + h+y0+ 9),(128, 255, 255), cv2.FILLED) cv2.putText(frame, str(score) + '% ',(x+ 80 +score, y + h+ y0 + 9),font, 0.5, (255,255,255),1, cv2.LINE_AA) y0 += 15 def preprocess(gray,x,y,w,h,num): cropped_face = gray[y:y + h,x:x + w] test_image = cv2.resize(cropped_face, (48, 48)) #cv2.imshow('cropped {0:d}'.format(num), cropped_face) ####pre-processing test_image = test_image.astype("float") / 255.0 test_image=np.asarray(test_image) #print('(48,48):',test_image.shape) test_image = np.stack((test_image,)*3, axis=-1) test_image = np.expand_dims(test_image, axis=0) #print('(1,48,48,3):',test_image.shape) return test_image def predict_emotion(frame,gray,detector,model): #Dictionary for emotion recognition model output and emotions emotions = {0:'Angry',1:'Disgust',2:'Fear',3:'Happy',4:'Sad',5:'Surprise',6:'Neutral'} # apply face detection (hog) faces_hog = detector(gray,1) try: ####是否有偵測到圖片中的人臉 faces_hog[0] except Exception as e: print("face count Warning: {}".format(e)) info = 'No face detected !' return frame,info num=1 # loop over detected faces for face in faces_hog: x = abs(face.left()) ##有遇過出現負值的現象 所以加abs y = abs(face.top()) w = abs(face.right()) - x h = abs(face.bottom()) - y test_image= preprocess(gray,x,y,w,h,num) num+=1 # Probablities of all classes #Finding class probability takes approx 0.05 seconds #start_time = time.time() probab = model.predict(test_image)[0] * 100 #每個情緒類別預測百分比 #Finding label from probabilities #Class having highest probability considered output label label = np.argmax(probab) #取百分比最大的情緒 (3) probab_predicted = int(probab[label]) #最高機率的情緒值 (99) predicted_emotion = emotions[label] #情緒數字轉成英文 (3→Happy) #show the result on the picture show_emotion(frame,x,y,w,h,emotions,probab,predicted_emotion,show_high=False) # cv2.imshow('frame', frame) # cv2.waitKey(0) # cv2.destroyWindow() info='OK' return frame,info def start(img,gray): face_detector = dlib.get_frontal_face_detector() emotion_model = load_model('./fer_ui/vgg16_batch16.h5')#vgg16_batch16_lr0.000100.h5 frame,info=predict_emotion(img,gray,face_detector,emotion_model) return frame,info ''' if __name__ == '__main__': main() '''<file_sep>import numpy as np import math from tensorflow.keras.preprocessing.image import ImageDataGenerator #VGG16 from keras.applications.vgg16 import VGG16 #VGG_Face from keras.engine import Model from keras.layers import Input from keras_vggface.vggface import VGGFace from keras.layers import Flatten,Dense,Dropout from keras.optimizers import Adam from keras.callbacks import EarlyStopping,ModelCheckpoint,CSVLogger,ReduceLROnPlateau,TensorBoard from sklearn.metrics import confusion_matrix,classification_report from keras.models import load_model import itertools import matplotlib.pyplot as plt import cv2 import time import os def read_Data(): #ferdata_vali_ch3_label data= np.load('./fer2013_/npz/vali_ch3_label_pri.npz')#arr_0:train_pixels / arr_1:train_emotion / arr_2:test_pixels / arr_3:test_emotion #trainPixels,trainEmotion,testPixels,testEmotion=data['arr_0'],data['arr_1'],data['arr_2'],data['arr_3'] #trainPixels,trainEmotion,testPixels,testEmotion,test_label = data['arr_0'],data['arr_1'],data['arr_2'],data['arr_3'],data['arr_4'] trainPixels,trainEmotion,testPixels,testEmotion,test_label,valiPixels,valiEmotion = data['arr_0'],data['arr_1'],data['arr_2'],data['arr_3'],data['arr_4'],data['arr_5'],data['arr_6'] #cv2.imshow("try",testPixels[2050].astype(np.uint8)) #cv2.waitKey(0) #print('255 shape',trainPixels.shape,trainEmotion.shape,testPixels.shape,testEmotion.shape,test_label.shape,valiPixels.shape,valiEmotion.shape)#,test_label.shape return trainPixels,trainEmotion,testPixels,testEmotion,test_label,valiPixels,valiEmotion#,test_label,valiPixels,valiEmotion def callbacks(batch,lr): #callbacks #EarlyStopping:當指定的評量數據(acc、loss)停止進步,則中斷訓練。 #ModelCheckpoint:在指定時刻,將神經網路存起來。 #ReduceLROnPlateau:當指定的評量數據(acc、loss)停止進步,則降低LR。 #CSVLogger:將每個訓練週期的評量數據,存到本地端 early_stopping_=EarlyStopping(monitor='val_loss',min_delta=0,patience=20,verbose=1,mode='auto',baseline=None) model_checkpoint_=ModelCheckpoint(filepath='./fer2013_/weights/vgg16_frozen_batch{0:d}_lr{1:f}'.format(batch,lr)+'_{epoch:02d}-{val_acc:.4f}.h5',monitor='val_acc',save_best_only=True,verbose=1) csv_logger_=CSVLogger(filename='./fer2013_/weights/vgg16_frozen_batch{0:d}_lr{1:f}_log.csv'.format(batch,lr),separator=',',append=False) ReduceLROnPlateau_=ReduceLROnPlateau(monitor='val_loss',factor=0.4,patience=4,verbose=1,min_delta=1e-6) tensorboard_=TensorBoard(log_dir='./fer2013_/weights', histogram_freq=1) return early_stopping_,model_checkpoint_,csv_logger_,ReduceLROnPlateau_,tensorboard_#,ReduceLROnPlateau_,tensorboard_ def VGG16_structure(): #VGG16架構 # Convolution Features base_model = VGG16(weights='imagenet', include_top=False,input_shape=(48,48,3)) last_layer = base_model.get_layer('block5_pool').output#block5_pool # 新分類器 x = Flatten(name='flatten')(last_layer) #x= Dropout(0.35)(x) x = Dense(512, activation='relu', name='fc6')(x) #x= Dropout(0.35)(x) #x = Dense(256, activation='relu', name='fc7')(x) #later try 256 #x= Dropout(0.35)(x) out = Dense(7, activation='softmax', name='fc7')(x) model = Model(base_model.input, out) # 首先,我们只训练顶部的几层(随机初始化的层) # 锁住所有 InceptionV3 的卷积层 #凍結權重 #base_model.trainable=False for layer in base_model.layers: layer.trainable=False model.summary() return model def VGGface_structure(): #VGGFACE架構 # Convolution Features base_model = VGGFace(include_top=False, input_shape=(48, 48, 3), pooling='avg',weights='vggface') last_layer = base_model.get_layer('pool5').output# # 新分類器 x = Flatten(name='flatten')(last_layer) x = Dense(512, activation='relu', name='fc6')(x) #x= Dropout(0.25)(x) #x = Dense(512, activation='relu', name='fc7')(x) #later try 256 #x= Dropout(0.25)(x) out = Dense(7, activation='softmax', name='fc7')(x) model = Model(base_model.input, out) #base_model.trainable=False #凍結權重 for layer in base_model.layers: layer.trainable=False model.summary() return model def image_generator(trainpixels_,trainemotion_,valipixels_,valiemotion_,testpixels_,testemotion_,batchsize_,epochs_,learningrate_): #呼叫callbacks early_stopping,model_checkpoint,csv_logger,reducelr,tensorboard=callbacks(batchsize_,learningrate_)#,reducelr fclist=[early_stopping,reducelr,csv_logger,model_checkpoint] callbacklist=[early_stopping,csv_logger,model_checkpoint,reducelr] #early_stopping,model_checkpoint,csv_logger,reducelr #Generator train=ImageDataGenerator(rescale=1./255,rotation_range=40,width_shift_range=0.05,height_shift_range=0.05,horizontal_flip=True) trn_gen=train.flow(x=trainpixels_,y=trainemotion_,batch_size=batchsize_)#,save_to_dir='./fer2013_/pic',save_format='jpg' vali = ImageDataGenerator(rescale=1./255)# vali_gen=vali.flow(x=valipixels_,y=valiemotion_,batch_size=batchsize_) test = ImageDataGenerator(rescale=1./255)# test_gen=test.flow(x=testpixels_,y=testemotion_,batch_size=batchsize_)#,save_to_dir='./fer2013_/pic',save_format='jpg' model=VGG16_structure()#VGGface_structure() model.compile(loss = 'categorical_crossentropy',optimizer = Adam(lr=learningrate_),metrics=['accuracy']) #單純train FC layer model.fit_generator(trn_gen,steps_per_epoch=len(trainpixels_)//batchsize_,validation_data=vali_gen,validation_steps=len(valipixels_)//batchsize_,epochs=epochs_,callbacks=fclist)# #model.save('./fer2013_/weights/vggface_batch{0:d}_lr{1:f}.h5'.format(batchsize_,learningrate_)) ''' #block3_conv1是VGG16, conv3_1是VGGFace unfreeze=['conv3_1','conv3_2','conv3_3','conv4_1','conv4_2','conv4_3','conv5_1','conv5_2','conv5_3','fc6','fc7'] #unfreeze = ['block3_conv1','block3_conv2','block3_conv3','block4_conv1','block4_conv2','block4_conv3','block5_conv1','block5_conv2','block5_conv3','fc6','fc7'] for layer in model.layers: if layer.name in unfreeze: layer.trainable=True else: layer.trainable=False #unfreeze train #model.compile(loss = 'categorical_crossentropy',optimizer = Adam(lr=learningrate_),metrics=['accuracy']) history=model.fit_generator(trn_gen,steps_per_epoch=len(trainpixels_)//batchsize_,validation_data=vali_gen,validation_steps=len(valipixels_)//batchsize_,epochs=epochs_,callbacks=callbacklist)# ''' model.save('./fer2013_/weights/vgg16_frozen_{0:d}_lr{1:f}.h5'.format(batchsize_,learningrate_)) test_score = model.evaluate_generator(test_gen, steps=len(test_gen), verbose=0) testLoss=test_score[0] testAcc=100*test_score[1] ''' print('vgg16_batch{0:d}_lr{1:f}_Loss_ACC \n'.format(batchsize_,learningrate_)) print('Test loss:', test_score[0]) print('Test accuracy:', 100*test_score[1]) ''' return history,testLoss,testAcc def plot_AccLoss(history_,batch,lr):#畫出accracy 跟 loss #plot accuracy and loss of each epochs print(history_.history.keys()) fig, (ax1, ax2)= plt.subplots(nrows=2,ncols=1,sharex=False,sharey=False,figsize=(10,10),constrained_layout=True) #constrained_layout自動調整圖片之間的間距 ax1.set_xlabel('epoch') ax1.set_ylabel('accuracy') acc=ax1.plot(history_.history['acc']) vacc=ax1.plot(history_.history['val_acc']) ax1.set_title('model accuracy') # summarize history for loss ax2.set_xlabel('epoch') ax2.set_ylabel('loss') loss=ax2.plot(history_.history['loss']) vloss=ax2.plot(history_.history['val_loss']) ax2.set_title('model loss') #fig.suptitle('Accuracy and Loss of each epochs') fig.legend([acc,vacc,loss,vloss],labels=['Acc','Val_Acc','Loss','Val_Loss'],loc='upper right',borderaxespad=0.1) #所有子圖的圖例 #plt.subplots_adjust(wspace=0.5) #調整子圖之間的寬距 fig.savefig('./fer2013_/weights/vgg16_frozen_batch{0:d}_lr{1:f}.png'.format(batch,lr)) #fig.show() return def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ plt.figure() if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout() plt.show() def predict(testPixels,testEmotion,test_label,batchsize_,model_path):#預測並劃出混淆矩陣 model=load_model(model_path) test = ImageDataGenerator(rescale=1./255)# test_gen=test.flow(x=testPixels,y=testEmotion,batch_size=batchsize_,shuffle=False) predict=model.predict_generator(test_gen,steps=(len(testPixels)//batchsize_)+1) predict_class = [np.argmax(pro) for pro in predict] #Confusion Matrix cm=confusion_matrix(test_label,predict_class) target_names=['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral'] #各類的precision recall f1-score print(classification_report(test_label,predict_class,target_names=target_names)) # Plot non-normalized confusion matrix plot_confusion_matrix(cm, classes=target_names,normalize=False) def main(): batchsize_=[16]#8,16,32,64,128 epochs=300 lr=[1e-4]#1e-3,5e-4, 1e-4,5e-5,1e-5 #trainPixels,trai1nEmotion,testPixels,testEmotion = read_Data() #trainPixels,trainEmotion,testPixels,testEmotion,test_label = read_Data() trainPixels,trainEmotion,testPixels,testEmotion,test_label,valiPixels,valiEmotion= read_Data() test_loss=[] test_acc=[] for batchsize in batchsize_: for lr_ in lr: history,testloss,testacc=image_generator(trainPixels,trainEmotion,valiPixels,valiEmotion,testPixels,testEmotion,batchsize,epochs,lr_) test_loss.append(testloss) test_acc.append(testacc) plot_AccLoss(history,batchsize,lr_) print(test_loss,test_acc) ''' #把acc loss存入txt檔 loss=str(test_loss[0])+', '+str(test_loss[1])+', '+str(test_loss[2])+', '+str(test_loss[3])+', '+str(test_loss[4])+'\n'+str(test_acc[0])+', '+str(test_acc[1])+', '+str(test_acc[2])+', '+str(test_acc[3])+', '+str(test_acc[4]) with open('vggface.txt','w') as f: f.write(loss) ''' ''' #predict CF model_path='./fer2013_/weights/vgg16_face_batch(0602)/vgg16_private_16_lr0.000100.h5' predict(testPixels,testEmotion,test_label,batchsize_[0],model_path) ''' return if __name__ == "__main__": start=time.clock() os.environ["CUDA_VISIBLE_DEVICES"] = "2" #因為gpu1顯體不足,所以改換成gpu3去跑 main() end=time.clock() print("total spend:",(end-start)) <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'fer.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(762, 639) MainWindow.setStyleSheet("background-color:rgb(255,255,128)") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.Image_Show = QtWidgets.QLabel(self.centralwidget) self.Image_Show.setGeometry(QtCore.QRect(30, 20, 521, 620)) self.Image_Show.setStyleSheet("border-radius:30px;") self.Image_Show.setText("") self.Image_Show.setObjectName("Image_Show") #####自己+++ self.movie = QtGui.QMovie('./fer_ui/img_start4.gif') self.Image_Show.setMovie(self.movie) self.Image_Show.setAlignment(QtCore.Qt.AlignCenter) self.movie.start() self.messagebox = QtWidgets.QMessageBox() self.messagebox.setStyleSheet( "QMessageBox{ background-color:rgb(255,255,128)}" "QPushButton { color: white; background-color:rgb(125,125,255) }" ) ##### self.Button_Load = QtWidgets.QPushButton(self.centralwidget) self.Button_Load.setGeometry(QtCore.QRect(580, 70, 151, 231)) font = QtGui.QFont() font.setFamily("Bookman Old Style") font.setPointSize(30) font.setBold(True) font.setWeight(75) self.Button_Load.setFont(font) self.Button_Load.setAutoFillBackground(False) self.Button_Load.setStyleSheet("border-radius:30px;\n" "background-color:rgb(125,125,255);\n" "color:white;") self.Button_Load.setObjectName("Button_Load") self.Button_Predict = QtWidgets.QPushButton(self.centralwidget) self.Button_Predict.setGeometry(QtCore.QRect(580, 330, 151, 231)) font = QtGui.QFont() font.setFamily("Bookman Old Style") font.setPointSize(30) font.setBold(True) font.setWeight(75) self.Button_Predict.setFont(font) self.Button_Predict.setStyleSheet("border-radius:30px;\n" "background-color:rgb(125,125,255);\n" "color:white;") self.Button_Predict.setObjectName("Button_Predict") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "FER")) self.Button_Load.setText(_translate("MainWindow", "Load ")) self.Button_Predict.setText(_translate("MainWindow", "Predict")) self.messagebox.setWindowTitle(_translate("MainWindow", "INFO")) ## 自己++ if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) <file_sep>###### tags: `github` # Facial Emotion Recognition ## 檔案說明(file description) * [preprocessing.py](https://github.com/cuta8451/FER/blob/master/preprocessing.py) * 預處理 * [trans_model.py](https://github.com/cuta8451/FER/blob/master/trans_model.py) * 模型訓練 * [dlib_picture.py](https://github.com/cuta8451/FER/blob/master/dlib_picture.py) * demo的演算法 * [fer_ui.py](https://github.com/cuta8451/FER/blob/master/fer_ui.py) * demo的ui介面 * [fer_main.py](https://github.com/cuta8451/FER/blob/master/fer_main.py) * demo的介面背後的model ## 資料集說明(dataset description) * 使用的是Kaggle上的FER2013資料集:Challenges in Representation Learning: Facial Expression Recognition * 7種情緒分別是憤怒(Anger),厭惡(Disgust),恐懼(Fear),快樂(Happy),悲傷(Sad),驚訝(Surprise)和中性(Neutral),總共35887筆資料,圖片為48*48像素灰階圖。 * ![](https://i.imgur.com/SvnZAEE.png) * ![](https://i.imgur.com/ePqq4Cm.png) ## 預處理方法 (preprocessing) * 調整圖片大小 * 特徵縮放(0~1) * 資料擴充:幾何 * 資料擴充GAN(ing) ## 模型 (model) * CNN * VGG16 * VGGFACE * MoblieNet(待做) ## 結果 (result) * Accuracy & Loss * ![](https://i.imgur.com/6X5MJQ5.png) * ![](https://i.imgur.com/GodCBbP.png) * Confusion Matrix * ![](https://i.imgur.com/VyQVZie.png) * ![](https://i.imgur.com/9b0NQhb.png) * Image Testing * ![](https://i.imgur.com/7ZDdCyv.png) * ![](https://i.imgur.com/Yjib91r.png) * * Demo * [Demo.mp4](https://github.com/cuta8451/FER/blob/master/DEMO.mp4)
804d2ae429eea9d3f4f7246fb0fbad371294285a
[ "Markdown", "Python" ]
6
Python
cuta8451/FER
43d072903ead0d5009ac0fc7170d3c5c5dfd2138
3ba4c1038319494c7e4a9fceb31495fb6f156624
refs/heads/master
<repo_name>FarukHossain2133/Shopping-List<file_sep>/config/keys.js module.exports = { mongoURI: 'mongodb+srv://Faruk:Faruk01936@cluster0-fqsei.mongodb.net/shopping?retryWrites=true&w=majority' } // mongodb://localhost:27017/mern-stack-tracker<file_sep>/client/src/store/reducers/index.js import {combineReducers} from 'redux'; import itemReducer from './itemsReducer'; const rootReducer = combineReducers({ item: itemReducer, }) export default rootReducer;<file_sep>/client/src/components/ShoppingList.js import React, { Component } from 'react' import { Container, ListGroup, ListGroupItem, Button, } from 'reactstrap'; import Spinner from './spinner/Spinner'; import { CSSTransition, TransitionGroup } from 'react-transition-group'; import './ShoppingList.css'; import {connect} from 'react-redux'; import PropTypes from 'prop-types'; import {getItems, deleteItem} from '../store/actions/itemActions'; class ShoppingList extends Component { componentDidMount(){ this.props.onGetItems() } render() { const {items} = this.props.item; const list = this.props.loading ? <Spinner/> : <div> <Container> <ListGroup> <TransitionGroup className="Shopping-list"> {items.map(({_id, name}) => ( <CSSTransition key={_id} timeout={200} className="myList"> <ListGroupItem> <Button className="remove-btn" color="danger" size="sm" onClick={() => this.props.onDeleteItem(_id)}> &times; </Button> {` ${name}`} </ListGroupItem> </CSSTransition> ))} </TransitionGroup> </ListGroup> </Container> </div> return list } } ShoppingList.propTypes = { onGetItems: PropTypes.func.isRequired, item: PropTypes.object.isRequired } const mapStateToProps = (state) => ({ item: state.item, loading: state.item.loading }) const mapDispatchToProps = dispatch => { return { onGetItems: () => dispatch(getItems()), onDeleteItem: (id) => dispatch(deleteItem(id)), } } export default connect(mapStateToProps, mapDispatchToProps)(ShoppingList);
94894d0b4ee2cec6e3038482fd2c4863b1ed9af6
[ "JavaScript" ]
3
JavaScript
FarukHossain2133/Shopping-List
a9b160e5349d3572974c1f7bba6efecaffd555ff
25f51a3557db12ec78b74a25b4e48a8861de835e
refs/heads/master
<repo_name>Davidy22/Project4<file_sep>/array.cpp #include <iostream> #include <cassert> #include <string> using namespace std; int appendToAll(string a[], int n, string value); int lookup(const string a[], int n, string target); int positionOfMax(const string a[], int n); int rotateLeft(string a[], int n, int pos); int rotateRight(string a[], int n, int pos); int flip(string a[], int n); int differ(const string a1[], int n1, const string a2[], int n2); int subsequence(const string a1[], int n1, const string a2[], int n2); int lookupAny(const string a1[], int n1, const string a2[], int n2); int split(string a[], int n, string splitter); void test(); int main() { test(); } void test() { //positionOfMax tests are sprinkled about the place because it needs an awful lot of test data just for itself. //Some of these tests may overlap/be redundant, but they definitely cover everything. string a[4] = {"SDkjd", "", "324Ls0\n", "daksjk"}; // I don't know why I started with flip, but assert(flip(a, -2) == -1 && a[0] == "SDkjd"); // it's too late to change now that I've given assert(flip(a, 0) == 0 && a[0] == "SDkjd"); // it the array named "a". Stupid OCD. assert(flip(a, 4) == 4 && a[0] == "daksjk" && a[1] == "324Ls0\n" && a[2] == "" && a[3] == "SDkjd"); assert(flip(a, 4) == 4 && a[0] == "SDkjd" && a[1] == "" && a[2] == "324Ls0\n" && a[3] == "daksjk"); assert(flip(a, 3) == 3 && a[0] == "324Ls0\n" && a[1] == "" && a[2] == "SDkjd" && a[3] == "daksjk"); assert(flip(a, 1) == 1 && a[0] == "324Ls0\n" && a[1] == "" && a[2] == "SDkjd" && a[3] == "daksjk"); assert(positionOfMax(a, 4) == 3); // Numbers < Capital letters < small letters assert(lookup(a, -4, "") == -1); assert(lookup(a, 0, "dsf") == -1); assert(lookup(a, 4, "dsf") == -1); assert(lookup(a, 2, "daksjk") == -1); assert(lookup(a, 4, "daksjk") == 3); assert(lookup(a, 1, "324Ls0\n") == 0); string b[4] = {"dsDkjd", "", "324Ls0\n", "daksjk"}; assert(positionOfMax(b, 4) == 0); assert(appendToAll(b, -2, "") == -1); assert(appendToAll(b, 0, "") == 0 && b[0] == "dsDkjd"); assert(appendToAll(b, 1, "!") == 1 && b[0] == "dsDkjd!" && b[1] == ""); assert(appendToAll(b, 4, "!") == 4 && b[0] == "dsDkjd!!" && b[1] == "!" && b[2] == "324Ls0\n!" && b[3] == "daksjk!"); string c[4] = {"dsDkjd", "", "324Ls0\n", "dsDkjd"}; assert(positionOfMax(c, 4) == 0); assert(rotateLeft(c, -2, -3) == -1 && c[1] == ""); assert(rotateLeft(c, 2, -3) == -1 && c[1] == ""); assert(rotateLeft(c, 2, 3) == -1 && c[1] == ""); assert(rotateRight(c, -2, -3) == -1 && c[1] == ""); assert(rotateRight(c, 2, -3) == -1 && c[1] == ""); assert(rotateRight(c, 2, 3) == -1 && c[1] == ""); assert(rotateLeft(c, 0, 0) == -1); assert(rotateRight(c, 0, 0) == -1); assert(rotateLeft(c, 3, 0) == 0 && c[0] == "" && c[1] == "324Ls0\n" && c[2] == "dsDkjd" && c[3] == "dsDkjd"); assert(positionOfMax(c, 4) == 2); assert(rotateRight(c, 3, 2) == 2 && c[0] == "dsDkjd" && c[1] == "" && c[2] == "324Ls0\n" && c[3] == "dsDkjd"); assert(positionOfMax(c, 4) == 0); assert(rotateLeft(c, 4, 0) == 0 && c[0] == "" && c[1] == "324Ls0\n" && c[2] == "dsDkjd" && c[3] == "dsDkjd"); assert(positionOfMax(c, 4) == 2); assert(rotateRight(c, 4, 3) == 3 && c[0] == "dsDkjd" && c[1] == "" && c[2] == "324Ls0\n" && c[3] == "dsDkjd"); assert(rotateLeft(c, 1, 0) == 0 && c[0] == "dsDkjd" && c[1] == "" && c[2] == "324Ls0\n" && c[3] == "dsDkjd"); assert(rotateRight(c, 1, 0) == 0 && c[0] == "dsDkjd" && c[1] == "" && c[2] == "324Ls0\n" && c[3] == "dsDkjd"); assert(positionOfMax(c, 4) == 0); assert(positionOfMax(c, 0) == -1); string d[4] = {"dsDkjd", "", "324Ls0\n", "dsDkjd"}; assert(differ(c, -2, a, -3) == -1); assert(differ(c, 2, a, -3) == -1); assert(differ(c, -2, a, 3) == -1); assert(differ(c, 0, a, 3) == 0); assert(differ(c, 3, a, 0) == 0); assert(differ(c, 4, a, 4) == 0); assert(differ(c, 4, b, 4) == 0); assert(differ(c, 4, b, 2) == 0); assert(differ(c, 2, b, 4) == 0); assert(differ(c, 4, d, 4) == 4); assert(differ(c, 4, d, 2) == 2); assert(differ(c, 2, d, 2) == 2); assert(differ(c, 2, d, 4) == 2); assert(differ(c, 4, d, 0) == 0); string e[2] = {"", "324Ls0\n"}; string f[1] = {"daksjk"}; assert(positionOfMax(e, 2) == 1); assert(positionOfMax(f, 1) == 0); assert(subsequence(c, -2, d, -2) == -1); assert(subsequence(c, 2, d, -2) == -1); assert(subsequence(c, -2, d, 2) == -1); assert(subsequence(c, 2, d, 3) == -1); assert(subsequence(c, 4, e, 2) == 1); assert(subsequence(c, 2, d, 2) == 0); assert(subsequence(c, 2, e, 2) == -1); assert(subsequence(c, 4, d, 2) == 0); assert(subsequence(c, 4, e, 1) == 1); assert(subsequence(c, 4, e, 0) == 0); assert(subsequence(c, 0, e, 0) == 0); assert(subsequence(a, 4, f, 1) == 3); assert(lookupAny(c, -2, d, -2) == -1); assert(lookupAny(c, 2, d, -2) == -1); assert(lookupAny(c, -2, d, 2) == -1); assert(lookupAny(c, 4, f, 1) == -1); assert(lookupAny(c, 0, d, 2) == -1); assert(lookupAny(c, 4, e, 2) == 1); assert(lookupAny(a, 4, f, 1) == 3); assert(lookupAny(c, 4, d, 2) == 0); assert(split(d, -4, "z") == -1); assert(split(d, 0, "z") == 0); assert(split(d, 4, "z") == 4); assert(split(d, 4, "D") == 2); assert(split(c, 2, "34") == 1); assert(split(c, 4, "") == 0); assert(split(c, 4, "D") == 2); assert(split(f, 1, "") == 0); assert(split(e, 2, "") == 0); assert(split(e, 2, "2") == 1); string h[7] = { "sansa", "robb", "daenerys", "tyrion", "", "jon", "arya" }; assert(lookup(h, 7, "jon") == 5); assert(lookup(h, 7, "daenerys") == 2); assert(lookup(h, 2, "daenerys") == -1); assert(positionOfMax(h, 7) == 3); string g[4] = { "sansa", "robb", "tyrion", "jon" }; assert(differ(h, 4, g, 4) == 2); assert(appendToAll(g, 4, "?") == 4 && g[0] == "sansa?" && g[3] == "jon?"); assert(rotateLeft(g, 4, 1) == 1 && g[1] == "tyrion?" && g[3] == "robb?"); string i[4] = { "daenerys", "tyrion", "", "jon" }; assert(subsequence(h, 7, i, 4) == 2); assert(rotateRight(i, 4, 1) == 1 && i[0] == "tyrion" && i[2] == ""); string j[3] = { "tyrion", "daenerys", "theon" }; assert(lookupAny(h, 7, j, 3) == 2); assert(flip(j, 3) == 3 && j[0] == "theon" && j[2] == "tyrion"); assert(split(h, 7, "jon") == 3); } int flip(string a[], int n) { // Reverse the order of the elements of the array and return n. if (n < 0) { return -1; } int start = 0; // Flip the first and last elements, move in by one, repeat. int end = n; string temp; while (end > start) { end--; temp = a[start]; a[start] = a[end]; a[end] = temp; start++; } return n; } int appendToAll(string a[], int n, string value) { // Append value to the end of each of the n elements of the array and return n. if (n < 0) { return -1; } for (int i = 0; i < n; i++) { a[i] += value; } return n; } int lookup(const string a[], int n, string target) { // Return the position of the first string in the array that is equal to target. for (int i = 0; i < n; i++) { if (a[i] == target) { return i; } } return -1; } int positionOfMax(const string a[], int n) { // Return the position of a string in the array such that that string is >= every string in the array. if (n <= 0) { return -1; } int largestIndex=0; while (n > 0) { n--; if (a[n] >= a[largestIndex]) { largestIndex = n; } } return largestIndex; } int rotateLeft(string a[], int n, int pos) { // Eliminate the item at position pos by copying all elements after it one place to the left. // Put the item that was thus eliminated into the last position of the array. Return the original // position of the item that was moved to the end. if (n <= 0 || pos < 0 || pos > n) { return -1; } string temp = a[pos]; // Keep the item in a tmp variable, shift everything else down. for (int i = pos; i < n - 1; i++) { a[i] = a[i+1]; } a[n-1] = temp; // Bring the temp variable back in. return pos; } int rotateRight(string a[], int n, int pos) { // Eliminate the item at position pos by copying all elements before it one place to the right. // Put the item that was thus eliminated into the first position of the array. Return the original // position of the item that was moved to the beginning. if (n <= 0 || pos < 0 || pos > n) { return -1; } string temp = a[pos]; for (int i = pos; i > 0; i--) { a[i] = a[i-1]; } a[0] = temp; return pos; } int differ(const string a1[], int n1, const string a2[], int n2) { // Return the position of the first corresponding elements of a1 and a2 that are not equal. n1 is the // number of interesting elements in a1, and n2 is the number of interesting elements in a2. If the // arrays are equal up to the point where one or both runs out, return the smaller of n1 and n2. if (n1 < 0 || n2 < 0) { return -1; } int i = 0; while (true) { // If either array runs out, return the array length. if (i == n1) { return n1; } else if (i == n2) { return n2; } if (a1[i] != a2[i]) { // Otherwise, if they don't match somewhere, return index of the mismatch. return i; } i++; } } int subsequence(const string a1[], int n1, const string a2[], int n2) { // If all n2 elements of a2 appear in a1, consecutively and in the same order, then return the position // in a1 where that subsequence begins. if (n1 < 0 || n2 < 0 || n2 > n1) { // Initial edge cases return -1; } else if (n2 == 0) { return 0; } for (int i = 0; i <= n1 - n2; i++) { // If one element matches, enter a loop that checks proceeding elements. if (a1[i] == a2[0]) { for (int j = 0; j < n2; j++) { if (a1[i+j] != a2[j]) { // If a proceeding element does not match, break out. break; } else if (j == n2 -1) { // Otherwise, return the initial element. return i; } } } } return -1; } int lookupAny(const string a1[], int n1, const string a2[], int n2) { // Return the smallest position in a1 of an element that is equal to any of the elements in a2. if (n1 < 0 || n2 < 0) { return -1; } for (int i = 0; i < n1; i++) { // FOr each element, check every element in a2. for (int j = 0; j < n2; j++) { if (a1[i] == a2[j]) { return i; } } } return -1; } int split(string a[], int n, string splitter) { // Rearrange the elements of the array so that all the elements whose value is < splitter come before all the // other elements, and all the elements whose value is > splitter come after all the other elements. Return the // position of the first element that, after the rearrangement, is not < splitter, or n if there are no such elements. if (n < 0) { return -1; } else if (n == 0) { return 0; } string temp; // Regurgitation of splitting algorithm from quicksort. int start = 0; int end = n - 1; while (start < end) { if (a[start] < splitter) { start++; } if (a[end] > splitter) { end--; } if (start < end) { temp = a[start]; a[start] = a[end]; a[end] = temp; } } for (int i = 0; i < n; i++) { // Final loop to find correct output value. if (a[i] >= splitter) { return i; } } return n; }
599e1fdc2d80df4b6650333cffd98dbcdd0d3d1a
[ "C++" ]
1
C++
Davidy22/Project4
2fe7e5e2d7459c5b079b57c1a8394855adbd420a
28e47622c46b439a242c86080b5aaed9e444042f
refs/heads/master
<file_sep>import math layouts = [] def register_layout(cls): layouts.append(cls) return cls def node(percent, layout, swallows, children): result = { "border": "normal", # "current_border_width": 2, "floating": "auto_off", # "name": "fish <</home/finkernagel>>", "percent": percent, "type": "con", "layout": layout, } if swallows: result["swallows"] = ([{"class": "."}],) if children: result["nodes"] = children return result def get_stack(window_count, split): return get_stack_unequal([1.0 / window_count] * window_count, split) def get_stack_unequal(percentages, split): elements = [] for p in percentages: elements.append(node(p, split, True, False)) return [{"layout": split, "type": "con", "nodes": elements}] @register_layout class Layout_vStack: name = "vStack" aliases = ["1col", "1c"] description = """\ One column / a vertical stack. --------- | 1 | --------- | 2 | --------- | 3 | --------- """ def get_json(self, window_count): return get_stack(window_count, "splitv") @register_layout class Layout_hStack: name = "hStack" aliases = ["1row", "1r"] description = """\ One row / a horizontal stack ------------- | | | | | 1 | 2 | 3 | | | | | ------------- """ def get_json(self, window_count): return get_stack(window_count, "splith") @register_layout class Layout_tabbed: name = "tabbed" aliases = [] description = """\ Tabbed --------- | | | 1/2/3 | | | --------- """ def get_json(self, window_count): return get_stack(window_count, "tabbed") @register_layout class Layout_v2Stack: name = "v2Stack" aliases = ["2col", "2c", "2v"] description = """\ Two columns of stacks ------------- | 1 | 4 | ------------- | 2 | 5 | ------------- | 3 | 6 | ------------- """ def get_json(self, window_count): s = int(math.ceil(window_count / 2)) left = get_stack(s, "splitv") right = get_stack(s if window_count % 2 == 0 else s - 1, "splitv") return [{"layout": "splith", "type": "con", "nodes": [left, right]}] @register_layout class Layout_h2Stack: name = "h2Stack" aliases = ["2row", "2r", "2h"] description = """\ Two rows of stacks ------------------- | 1 | 2 | 3 | ------------------- | 4 | 5 | 6 | ------------------- """ def get_json(self, window_count): s = int(math.ceil(window_count / 2)) left = get_stack(s, "splith") right = get_stack(s if window_count % 2 == 0 else s - 1, "splith") return [{"layout": "splitv", "type": "con", "nodes": [left, right]}] @register_layout class Layout_v3Stack: name = "v3Stack" aliases = ["3col", "3c", "3v"] description = """\ Three columns of stacks ------------------- | 1 | 3 | 5 | ------------------- | 2 | 4 | 6 | ------------------- """ def get_json(self, window_count): s = window_count // 3 a = get_stack(s + window_count % 3, "splitv") b = get_stack(s, "splitv") c = get_stack(s, "splitv") return [{"layout": "splith", "type": "con", "nodes": [a, b, c]}] @register_layout class Layout_h3Stack: name = "h3Stack" aliases = ["3row", "3r", "3h"] description = """\ Three rows of stacks ------------------- | 1 | 2 | 3 | ------------------- | 4 | 5 | 6 | ------------------- | 7 | 8 | 9 | ------------------- """ def get_json(self, window_count): s = window_count // 3 a = get_stack(s + window_count % 3, "splith") b = get_stack(s, "splith") c = get_stack(s, "splith") return [{"layout": "splitv", "type": "con", "nodes": [a, b, c]}] @register_layout class Layout_Max: name = "max" aliases = ["maxTabbed"] description = """\ One large container, in tabbed mode. --------------- | | | 1,2,3,4, | | | --------------- """ def get_json(self, window_count): return get_stack(window_count, "tabbed") @register_layout class Layout_MainLeft: name = "mainLeft" aliases = ["ml", "mv", "MonadTall"] description = """\ One large window to the left at 50%, all others stacked to the right vertically. ------------- | | 2 | | |-----| | 1 | 3 | | |-----| | | 4 | ------------- """ def get_json(self, window_count): return node( 1, "splith", False, [node(0.5, "splitv", True, []), get_stack(window_count - 1, "splitv")], ) @register_layout class Layout_MainRight: name = "mainRight" aliases = ["mr", "vm", "MonadTallFlip"] description = """\ One large window to the right at 50%, all others stacked to the right vertically. ------------- | 2 | | |-----| | | 3 | 1 | |-----| | | 4 | | ------------- """ def get_json(self, window_count): return ( node( 1, "splith", False, [get_stack(window_count - 1, "splitv"), node(0.75, "splitv", True, [])], ), list(range(1, window_count)) + [0], ) @register_layout class Layout_MainMainVStack: name = "MainMainVStack" aliases = ["mmv"] description = """\ Two large windows to the left at 30%, all others stacked to the right vertically. ------------------- | | | 3 | | | |-----| | 1 | 2 | 4 | | | |-----| | | | 5 | ------------------- """ def get_json(self, window_count): return node( 1, "splith", False, [ node(1 / 3, "splitv", True, []), node(1 / 3, "splitv", True, []), get_stack(window_count - 2, "splitv"), ], ) @register_layout class Layout_MainVStackMain: name = "MainVStackMain" aliases = ["mvm"] description = """\ Two large windows at 30% to the left and right, a vstack in the center ------------------- | | 3 | | | |-----| | | 1 | 4 | 2 | | |-----| | | | 5 | | ------------------- """ def get_json(self, window_count): return ( node( 1, "splith", False, [ node(1 / 3, "splitv", True, []), get_stack(window_count - 2, "splitv"), node(1 / 3, "splitv", True, []), ], ), [0] + list(range(2, window_count)) + [1], ) @register_layout class Layout_Matrix: name = "matrix" aliases = [] description = """\ Place windows in a n * n matrix. The matrix will place swallow-markers if you have less than n*n windows. N is math.ceil(math.sqrt(window_count)) """ def get_json(self, window_count): n = int(math.ceil(math.sqrt(window_count))) stacks = [get_stack(n, "splith") for stack in range(n)] return node(1, "splitv", False, stacks) @register_layout class Layout_VerticalTileTop: name = "VerticalTileTop" aliases = ["vtt"] description = """\ Large master area (66%) on top, horizontal stacking below """ def get_json(self, window_count): return node( 1, "splitv", False, [ node(0.66, "splitv", True, []), node( 0.33, "splitv", False, get_stack_unequal( [0.33 / (window_count - 1)] * (window_count - 1), "splitv", ), ), ], ) @register_layout class Layout_VerticalTileBottom: name = "VerticalTileBottom" aliases = ["vtb"] description = """\ Large master area (66%) on bottom, horizontal stacking above """ def get_json(self, window_count): return ( node( 1, "splitv", False, [ node( 0.33, "splitv", False, get_stack_unequal( [0.33 / (window_count - 1)] * (window_count - 1), "splitv", ), ), node(0.66, "splitv", True, []), ], ), list(range(1, window_count)) + [0], ) @register_layout class Nested: name = "NestedRight" aliases = ["nr"] description = """\ Nested layout, starting with a full left half. ------------------------- | | | | | 2 | | | | | 1 |-----------| | | | 4 | | | 3 |-----| | | |5 | 6| ------------------------- """ def get_json(self, window_count): dir = "h" parent = node(1, "splith", False, []) root = parent parent["nodes"] = [] for ii in range(window_count): parent["nodes"].append(get_stack_unequal([0.5], "split" + dir)) n = node(1, "splith", False, []) if dir == "h": dir = "v" else: dir = "h" n["layout"] = "split" + dir n["nodes"] = [] if ii < window_count - 1: parent["nodes"].append(n) parent = n return root @register_layout class Smart: name = "SmartNestedRight" aliases = ["snr"] description = """\ Nested layout, starting with a full left half, but never going below 1/16th of the size. 2 windows ------------------------- | | | | | | | | | | 1 | 2 | | | | | | | | | | ------------------------- 5 windows ------------------------- | | | | | 2 | | | | | 1 |-----------| | | | 4 | | | 3 |-----| | | | 5 | ------------------------- 6 windows ------------------------- | | | | | 2 | | | | | 1 |-----------| | | 3 | 4 | | |-----|-----| | | 5 | 6 | ------------------------- 7 windows ------------------------- | | | | | | 2 | 3 | | | | | | 1 |-----------| | | 4 | 5 | | |-----|-----| | | 6 | 7 | ------------------------- 15 windows ------------------------- | | 2 | 4 | 6 | | 1 |-----|-----|-----| | | 3 | 5 | 7 | |-----------|-----------| | 8 | A | C | E | |-----|-----|-----|-----| | 9 | B | D | F | ------------------------- Falls back to matrix layout above 16 windows. """ def get_json(self, window_count): def nest_1(): return node(1, "splith", True, []) def nest_2(): return get_stack(2, "splith") def nest_3(): return node( 1, "splith", False, [node(0.5, "splitv", True, []), get_stack(2, "splitv")], ) def nest_4(): return node( 1, "splith", False, [get_stack(2, "splitv"), get_stack(2, "splitv")], ) if window_count == 1: return nest_1() elif window_count == 2: return nest_2() elif window_count == 3: return nest_3() elif window_count == 4: return nest_4() elif window_count == 5: return node( 1, "splith", False, [ node(0.5, "splitv", True, [],), node( 0.5, "splitv", False, [node(0.5, "split", True, []), nest_3()] ), ], ) elif window_count == 6: return node( 1, "splith", False, [ node(0.5, "splitv", True, [],), node( 0.5, "splitv", False, [node(0.5, "split", True, []), nest_4()] ), ], ) elif window_count == 7: return node( 1, "splith", False, [ node(0.5, "splitv", True, [],), node(0.5, "splitv", False, [nest_2(), nest_4()]), ], ) elif window_count == 8: return node( 1, "splith", False, [ node(0.5, "splitv", True, [],), node(0.5, "splitv", False, [nest_3(), nest_4()]), ], ) elif window_count == 9: return node( 1, "splith", False, [ node(0.5, "splitv", True, [],), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 10: return node( 1, "splith", False, [ node( 0.5, "splitv", False, [node(0.5, "splitv", True, []), node(0.5, "splitv", True, [])], ), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 11: return node( 1, "splith", False, [ node( 0.5, "splitv", False, [node(0.5, "splitv", True, []), nest_2()], ), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 12: return node( 1, "splith", False, [ node( 0.5, "splitv", False, [node(0.5, "splitv", True, []), nest_3()], ), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 13: return node( 1, "splith", False, [ node( 0.5, "splitv", False, [node(0.5, "splitv", True, []), nest_4()], ), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 14: return node( 1, "splith", False, [ node(0.5, "splitv", False, [nest_2(), nest_4()],), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 15: return node( 1, "splith", False, [ node(0.5, "splitv", False, [nest_3(), nest_4()],), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) elif window_count == 16: return node( 1, "splith", False, [ node(0.5, "splitv", False, [nest_4(), nest_4()],), node(0.5, "splitv", False, [nest_4(), nest_4()]), ], ) else: return Layout_Matrix().get_json(window_count) @register_layout class Layout_MainCenter: name = "mainCenter" aliases = ["mc", "vmv"] description = """\ One large window in the midle at 50%, all others stacked to the left/right vertically. ------------------- | 2 | | 5 | |-----| |-----| | 3 | 1 | 6 | |-----| |-----| | 4 | | 7 | ------------------- """ def get_json(self, window_count): lr = window_count - 1 left = math.ceil(lr / 2) right = math.floor(lr / 2) nodes = [] if left: nodes.append(node(0.25, 'splith', False, get_stack(left, 'splitv'))) nodes.append(node(0.5, 'splitv', True, [])) if right: nodes.append(node(0.25, 'splith', False, get_stack(right, 'splitv'))) order = list(range(1, left+1)) + [0] + list(range(left+1, left+1+right)) print(order) return node(1, 'splith', False, nodes),order <file_sep>import asyncio import i3ipc import datetime import json import math import subprocess import sys import tempfile from pathlib import Path from . import layouts, __version__ counter_file = Path("~/.local/share/i3-instant-layout/counter.json").expanduser() counter_file.parent.mkdir(exist_ok=True, parents=True) def append_layout(layout_dict, window_count): """Apply a layout from this layout class""" tf = tempfile.NamedTemporaryFile(suffix=".json") tf.write(json.dumps(layout_dict, indent=4).encode("utf-8")) tf.flush() cmd = ["i3-msg", "append_layout", str(Path(tf.name).absolute())] subprocess.check_call(cmd, stdout=subprocess.PIPE) tf.close() def nuke_swallow_windows(): """Remove swallow windows before changing layout""" to_nuke = set() def walk_tree(con): if con.ipc_data.get("swallows", False): to_nuke.add(con.ipc_data["window"]) for d in con.descendants(): walk_tree(d) i3 = i3ipc.Connection() tree = i3.get_tree().find_focused().workspace() walk_tree(tree) for window_id in to_nuke: subprocess.check_call(["xdotool", "windowclose", str(window_id)]) def get_window_ids(): """use xprop to list windows on current screen. Couldn't find out how to get the right ids from i3ipc. id is con_id, but we need x11 id Sorry, this probably means this won't work on wayland & sway. """ desktop = subprocess.check_output( ["xprop", "-notype", "-root", "_NET_CURRENT_DESKTOP"] ).decode("utf-8", errors="replace") desktop = desktop[desktop.rfind("=") + 2 :].strip() res = subprocess.check_output( [ "xdotool", "search", "--all", "--onlyvisible", "--desktop", desktop, "--class", "^.*", ] ).decode("utf-8", errors="replace") return res.strip().split("\n") def get_active_window(): return ( subprocess.check_output(["xdotool", "getactivewindow"]).decode("utf-8").strip() ) def focus_window(id): return subprocess.check_call( ["i3-msg", f'[id="{id}"]', "focus"], stdout=subprocess.PIPE ) # return subprocess.check_call(['xdotool','windowraise', id]) def apply_layout(layout, dry_run=False): """Actually turn this workspace into this layout""" active = get_active_window() windows = get_window_ids() windows = [active] + [x for x in windows if x != active] window_count = len(windows) # we unmap and map all at once for speed. unmap_cmd = [ "xdotool", ] map_cmd = [ "xdotool", ] t = layout.get_json(window_count) if isinstance(t, tuple): layout_dict, remap_order = t if set(range(window_count)) != set(remap_order): raise ValueError("Layout returned invalid remap order") windows = [windows[ii] for ii in remap_order] else: layout_dict = t if dry_run: print(json.dumps(layout_dict, indent=4)) else: if layout_dict is not False: append_layout(layout_dict, window_count) for window_id in windows: unmap_cmd.append("windowunmap") map_cmd.append("windowmap") unmap_cmd.append(str(window_id)) map_cmd.append(str(window_id)) # force i3 to swallow these windows. subprocess.check_call(unmap_cmd) subprocess.check_call(map_cmd) focus_window(active) def load_usage(): try: with open(counter_file, "r") as op: return json.load(op) except (OSError, ValueError): return {} def count_usage(layout_name): usage = load_usage() if layout_name not in usage: usage[layout_name] = (0, datetime.datetime.now().timestamp()) usage[layout_name] = ( usage[layout_name][0] + 1, datetime.datetime.now().timestamp(), ) with open(counter_file, "w") as op: json.dump(usage, op) def list_layouts_in_smart_order(): """List the layouts in a 'smart' order, that means most common ones on top (by log10 usage), within one log10 unit, sorted by most-recently-used""" usage = load_usage() sort_me = [] for layout in layouts.layouts: if " " in layout.name: raise ValueError( f"No spaces in layout names please. Offender: '{layout.name}'" ) for alias in [layout.name] + layout.aliases: usage_count, last_used = usage.get( alias, (0, datetime.datetime.now().timestamp()) ) if alias == layout.name: desc = alias else: desc = f"{alias} ({layout.name})" sort_me.append( (-1 * math.ceil(math.log10(usage_count + 1)), -1 * last_used, desc) ) sort_me.sort() for _, _, name in sort_me: print(name) def print_help(): print( """i3-instant-layout applies ready made layouts to i3 workspaces, based on the numerical position of the windows. Call with '--list' to get a list of available layouts (and their aliases). Call with --desc to get detailed information about every layout available. Call with the name of a layout to apply it to the current workspace. Call with '-' to read layout name from stdin. Call with 'name --dry-run' to inspect the generated i3 append_layout compatible json. To integrate into i3, add this to your i3/config. bindsym $mod+Escape exec "i3-instant-layout --list | rofi -dmenu -i | i3-instant-layout -" """ ) sys.exit(0) def print_desc(): import textwrap for layout_class in layouts.layouts: print(f"Layout: {layout_class.name}") print(f"Aliases: {layout_class.aliases}") print(textwrap.indent(textwrap.dedent(layout_class.description), "\t")) print("") print("-" * 80) print("") def main(): if len(sys.argv) == 1 or sys.argv[1] == "--help": print_help() elif sys.argv[1] == "--desc": print_desc() sys.exit(0) elif sys.argv[1] == "--version": print(__version__) sys.exit(0) elif sys.argv[1] == "--list": list_layouts_in_smart_order() sys.exit(0) elif sys.argv[1] == "-": query = sys.stdin.readline().strip() print(f'query "{query}"') if not query.strip(): # e.g. rofi cancel sys.exit(0) else: query = sys.argv[1] if " " in query: query = query[: query.find(" ")] for layout_class in layouts.layouts: if query == layout_class.name or query in layout_class.aliases: nuke_swallow_windows() apply_layout(layout_class(), "--dry-run" in sys.argv) count_usage(query) sys.exit(0) else: print("Could not find the requested layout") sys.exit(1) <file_sep># i3-instant-layout Automatic 'list based' layouts for the [i3](https://i3wm.org) window manager ## Animated summary ![Demo of i3-instant-layout](https://github.com/TyberiusPrime/i3-instant-layout/raw/master/docs/_static/i3-instant-layout_demo.gif "i3-instant-layout demo") ## Description This python program drags i3 into the 'managed layouts tiling window manager world' kicking and screaming. What it does is apply a window layout to your current workspace, like this one: ------------- | | 2 | | |-----| | 1 | 3 | | |-----| | | 4 | ------------- The big advantage here is that it needs no 'swallow' definitions whatsoever, it's 'instant' - just add milk, eh, press the button. ## Get started i3-instant-layout depends xdotool which can be installed by your package manager (e.g. `sudo apt-get install xdotool` on Debian or Ubuntu) To get started, install with `pip install i3-instant-layout`, or if you prefer, [pipx](https://github.com/pipxproject/pipx) and add this to your i3 config: `bindsym $mod+Escape exec "i3-instant-layout --list | rofi -dmenu -i | i3-instant-layout -` (or use the interactive menu of your choice). ## Further information Call `i3-instant-layout --help` for full details, or `i3-instant-layout --desc` for the full list of supported layouts (or see below). ## Helpful tips ### How to sort windows Your current active window is what the tiler will consider the 'main window'. To get the other windows in the right order for your layout of choice, first enable the vStack or hStack layout, sort them, and the proceed to your layout of choice. ### Border styles i3-instant-layout must unmap/map the windows (ie. hide them temporarily) for i3 to place them at the right location. Unfortunatly that appears to consume the border style. Work around this with a line like this in your i3 config: ``` for_window [class="^.*"] border pixel 1 ``` ## Available layouts Layout: vStack Aliases: ['1col', '1c'] One column / a vertical stack. --------- | 1 | --------- | 2 | --------- | 3 | --------- -------------------------------------------------------------------------------- Layout: hStack Aliases: ['1row', '1r'] One row / a horizontal stack ------------- | | | | | 1 | 2 | 3 | | | | | ------------- -------------------------------------------------------------------------------- Layout: v2Stack Aliases: ['2col', '2c', '2v'] Two columns of stacks ------------- | 1 | 4 | ------------- | 2 | 5 | ------------- | 3 | 6 | ------------- -------------------------------------------------------------------------------- Layout: h2Stack Aliases: ['2row', '2r', '2h'] Two rows of stacks ------------------- | 1 | 2 | 3 | ------------------- | 4 | 5 | 6 | ------------------- -------------------------------------------------------------------------------- Layout: v3Stack Aliases: ['3col', '3c', '3v'] Three columns of stacks ------------------- | 1 | 3 | 5 | ------------------- | 2 | 4 | 6 | ------------------- -------------------------------------------------------------------------------- Layout: h3Stack Aliases: ['3row', '3r', '3h'] Three rows of stacks ------------------- | 1 | 2 | 3 | ------------------- | 4 | 5 | 6 | ------------------- | 7 | 8 | 9 | ------------------- -------------------------------------------------------------------------------- Layout: max Aliases: ['maxTabbed'] One large container, in tabbed mode. --------------- | | | 1,2,3,4, | | | --------------- -------------------------------------------------------------------------------- Layout: mainLeft Aliases: ['ml', 'mv', 'MonadTall'] One large window to the left at 50%, all others stacked to the right vertically. ------------- | | 2 | | |-----| | 1 | 3 | | |-----| | | 4 | ------------- -------------------------------------------------------------------------------- Layout: mainRight Aliases: ['mr', 'vm', 'MonadTallFlip'] One large window to the right at 50%, all others stacked to the right vertically. ------------- | 2 | | |-----| | | 3 | 1 | |-----| | | 4 | | ------------- -------------------------------------------------------------------------------- Layout: MainMainVStack Aliases: ['mmv'] Two large windows to the left at 30%, all others stacked to the right vertically. ------------------- | | | 3 | | | |-----| | 1 | 2 | 4 | | | |-----| | | | 5 | ------------------- -------------------------------------------------------------------------------- Layout: MainVStackMain Aliases: ['mvm'] Two large windows at 30% to the left and right, a vstack in the center ------------------- | | 3 | | | |-----| | | 1 | 4 | 2 | | |-----| | | | 5 | | ------------------- -------------------------------------------------------------------------------- Layout: matrix Aliases: [] Place windows in a n * n matrix. The matrix will place swallow-markers if you have less than n*n windows. N is math.ceil(math.sqrt(window_count)) -------------------------------------------------------------------------------- Layout: VerticalTileTop Aliases: ['vtt'] Large master area (66%) on top, horizontal stacking below -------------------------------------------------------------------------------- Layout: VerticalTileBottom Aliases: ['vtb'] Large master area (66%) on bottom, horizontal stacking above -------------------------------------------------------------------------------- Layout: NestedRight Aliases: ['nr'] Nested layout, starting with a full left half. ------------------------- | | | | | 2 | | | | | 1 |-----------| | | | 4 | | | 3 |-----| | | |5 | 6| ------------------------- -------------------------------------------------------------------------------- Layout: SmartNestedRight Aliases: ['snr'] Nested layout, starting with a full left half, but never going below 1/16th of the size. 2 windows ------------------------- | | | | | | | | | | 1 | 2 | | | | | | | | | | ------------------------- 5 windows ------------------------- | | | | | 2 | | | | | 1 |-----------| | | | 4 | | | 3 |-----| | | | 5 | ------------------------- 6 windows ------------------------- | | | | | 2 | | | | | 1 |-----------| | | 3 | 4 | | |-----|-----| | | 5 | 6 | ------------------------- 7 windows ------------------------- | | | | | | 2 | 3 | | | | | | 1 |-----------| | | 4 | 5 | | |-----|-----| | | 6 | 7 | ------------------------- 15 windows ------------------------- | | 2 | 4 | 6 | | 1 |-----|-----|-----| | | 3 | 5 | 7 | |-----------|-----------| | 8 | A | C | E | |-----|-----|-----|-----| | 9 | B | D | F | ------------------------- Falls back to matrix layout above 16 windows. -------------------------------------------------------------------------------- Layout: mainCenter Aliases: ['mc', 'vmv'] One large window in the midle at 50%, all others stacked to the left/right vertically. ------------------- | 2 | | 5 | |-----| |-----| | 3 | 1 | 6 | |-----| |-----| | 4 | | 7 | ------------------- -------------------------------------------------------------------------------- <file_sep>[flake8] exclude = tests/run/*, docs/* max-line-length = 88 max-complexity = 21 ignore = E501,W504,W503,E402,E203,E713 select = C,E,F,W,B,B901 <file_sep># Changelog ## Version 0.15 * added layout MainCenter, vmv ## Version 0.14 initial public release
cce0c494fac86da924db90d8d7a279a6598b254d
[ "Markdown", "Python", "INI" ]
5
Python
ur4ltz/i3-instant-layout
8c3e49c70306826dc69a889cbd44c1ab610419b1
f84e162abe353b314c11da8c5d637d4946112ce2
refs/heads/master
<repo_name>iainmck29/javascript-objects-bootcamp-prep-000<file_sep>/objects.js var playlist = {name:"title"}; function updatePlaylist(playlist, name, title) { playlist[name] = title; return playlist; } function removeFromPlaylist(playlist, artistName) { var myNewVariable = playlist delete myNewVariable[artistName]; return playlist; }
a919e39473e65e6dc63b8f5ccdb1171dc5408c9d
[ "JavaScript" ]
1
JavaScript
iainmck29/javascript-objects-bootcamp-prep-000
c1b5e6cc054179999c68e4e4922fab5ba7aa9307
fe908d2088934839be9059abeca582777a1b699f
refs/heads/master
<repo_name>MeghaShahri/Advocate-Vidhi-Chamber<file_sep>/service.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vidhi Chambers-Practice Areas</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="Law Firm Website Template" name="keywords"> <meta content="Law Firm Website Template" name="description"> <!-- Favicon --> <link href="img/favicon.ico" rel="icon"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css2?Education =EB+Garamond:ital,wght@1,600;1,700;1,800&Education =Roboto:wght@400;500&display=swap" rel="stylesheet"> <!-- CSS Libraries --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet"> <link href="lib/animate/animate.min.css" rel="stylesheet"> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <!-- Template Stylesheet --> <link href="css/style.css" rel="stylesheet"> </head> <body> <?php include 'common/nav.php'; ?> <!-- Nav Bar End --> <!-- Page Header Start --> <!-- <div class="page-header"> <div class="container"> <div class="row"> <div class="col-12"> <h2>Practices Areas</h2> </div> <div class="col-12"> <a href="">Home</a> <a href="">Practices Areas</a> </div> </div> </div> </div> --> <!-- Page Header End --> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <h2>Our Practice Areas</h2> </div> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div><hr class="myline"> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 2nd row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div><hr class="myline"> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 3rd row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div><hr class="myline"> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 4th row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 5th row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div><hr class="myline"> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 6th row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div><hr class="myline"> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div><hr class="myline"> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 7th row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 8th row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div> <h3>EducationLaw</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> <!-- 9th row --> <div class="row"> <div class="box"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div> <h3>Education Law</h3> <p> Education law is the body of state and federal law that covers teachers, schools, school districts, school boards, and the students they teach. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> </div> <!-- Service End --> <!-- Feature Start --> <div class="feature"> <div class="container"> <div class="row"> <div class="col-md-7"> <div class="section-header"> <h2>Why Choose Us</h2> </div> <div class="row align-items-center feature-item"> <div class="col-5"> <div class="feature-icon"> <i class="fa fa-gavel"></i> </div> </div> <div class="col-7"> <h3>Best law practices</h3> <!-- <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. </p> --> </div> </div> <div class="row align-items-center feature-item"> <div class="col-5"> <div class="feature-icon"> <i class="fa fa-balance-scale"></i> </div> </div> <div class="col-7"> <h3>Efficiency & Trust</h3> <!-- <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. </p> --> </div> </div> <div class="row align-items-center feature-item"> <div class="col-5"> <div class="feature-icon"> <i class="far fa-smile"></i> </div> </div> <div class="col-7"> <h3>Results you deserve</h3> <!-- <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. </p> --> </div> </div> </div> <div class="col-md-5"> <div class="feature-img"> <img src="img/feature.jpg" alt="Feature"> </div> </div> </div> </div> </div> <!-- Feature End --> <!-- Footer Start --> <?php include 'common/footer.php'; ?> <!-- Footer End --> <a href="#" class="back-to-top"><i class="fa fa-chevron-up"></i></a> </div> <!-- JavaScript Libraries --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script> <script src="lib/easing/easing.min.js"></script> <script src="lib/owlcarousel/owl.carousel.min.js"></script> <script src="lib/isotope/isotope.pkgd.min.js"></script> <!-- Template Javascript --> <script src="js/main.js"></script> </body> </html> <file_sep>/appointment.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vidhi Chambers-Home</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="Law Firm Website Template" name="keywords"> <meta content="Law Firm Website Template" name="description"> <!-- Favicon --> <link href="img/favicon.ico" rel="icon"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@1,600;1,700;1,800&family=Roboto:wght@400;500&display=swap" rel="stylesheet"> <!-- CSS Libraries --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet"> <link href="lib/animate/animate.min.css" rel="stylesheet"> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <!-- Template Stylesheet --> <link href="css/style.css" rel="stylesheet"> </head> <style> .msg { position: relative; padding: .75rem 1.25rem; border: 1px solid transparent; border-radius: .25rem; } .msg-empty{ color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; } .msg b{ color: #721c24; background-color: #f8d7da; } .msg-success{ color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; } .details2-form{ margin-top: 200px; position: relative; margin-bottom:-20px; left: 50%; transform: translate(-50%,-10%); width: 550px; height: 750px; padding: 10px 40px; box-sizing: border-box; background: #ffffff; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); margin-bottom: -50px; bottom:20%; } #submit{ cursor: pointer; margin: 0; position: absolute; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } @media(max-width:499px){ .details2-form{ width:500px; } } @media(max-width:415px){ .details2-form{ width:450px; } } @media(max-width:400px){ .details2-form{ width:400px; } } @media(max-width:370px){ .details2-form{ width:350px; } } @media(max-width:295px){ .details2-form{ width:300px; } } @media(max-width:294px){ #lname{ margin-left:125px; } } @media(max-width:242px){ .details2-form{ width:270px; } label{ width:100%; } } @media(max-width:198px){ .details2-form{ width:220px; } } </style> <body> <?php include 'common/nav.php'; $status=$_GET['status']; if($status=='empty'){ } else if($status=='sunday'){ echo' <div class="msg msg-empty"> <b>Failed!</b> Appointments on sunday not allowed.Please select another date. </div>'; } else if($status=='nosunday'){ echo' <div class="alert alert-success" role="alert"> <b>Done!</b> Noted.Wait for confirmation on call. </div>'; } else if($status=='greaterdate'){ echo' <div class="msg msg-empty"> <b>Failed!</b> Select a date within 3 days from today. </div>'; } else if($status=='existemail'){ echo' <div class="msg msg-empty"> <b>Failed!</b> Email already exists. </div>';} ?> <!-- <p style="color:red;">Please fill the deatils below.Note-Appointment date should be within three days from today and appointments on sunday not allowed.</p> --> <div id="details2-form" class="details2-form"> <form role="form" class="form" action="get_appointment.php" method="post"> <div class="form-group"> <label for="name">Name :</label> <div class="row"> <div class="col"> <input type="text" name="fname" class="form-control" placeholder="First name" required> </div> <div class="col" id="lname"> <input type="text" class="form-control" name="lname" placeholder="Last name" required> </div> </div> </div> <div class="form-group"> <label for="exampleInputEmail1">Email Id :</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email" required/> </div> <div class="form-group"> <label for="phone">Phone Number :</label> <input type="tel" class="form-control" id="phone" name="phone" placeholder="Enter phone" required/> </div> <div class="form-group"> <label for="gender">Select your gender:</label><br> <input type="radio" id="male" name="gender" value="male" required> <label for="male" style="font-weight:normal">Male</label><br> <input type="radio" id="female" name="gender" value="female"> <label for="female" style="font-weight:normal">Female</label><br> <input type="radio" id="other" name="gender" value="other"> <label for="other" style="font-weight:normal">Other</label> </div> <div class="form-group"> <label for="appt_date">Select a date :</label> <input type="date" id="appt_date" name="appt_date" min="<?php echo date('Y'); ?>" value="<?php echo date('Y-m-d'); ?>" required> </div><br> <?php function create_time_range($start, $end, $interval = '60 mins', $format = '12') { $startTime = strtotime($start); $endTime = strtotime($end); $returnTimeFormat = ($format == '12')?'g:i:s A':'G:i:s'; $current = time(); $addTime = strtotime('+'.$interval, $current); $diff = $addTime - $current; $times = array(); while ($startTime < $endTime) { $times[] = date($returnTimeFormat, $startTime); $startTime += $diff; } $times[] = date($returnTimeFormat, $startTime); return $times; } $times = create_time_range('10:00', '17:00', '60 mins'); ?> <div class="form-group"> <label for="appt_time">Select a time:</label> <!-- <input type="time" id="appt_time" name="appt_time"> --> <select name="time_picker"> <option value="">Select time</option> <?php foreach($times as $key=>$val){ ?> <option value="<?php echo $val; ?>"><?php echo $val; ?></option> <?php } ?> </select> </div> <br> <br><button type="submit" class="btn" id="submit" style="background:#ffc40c; color:black; border:2px solid black"> Submit </button> </form> </div> <?php include 'common/footer.php'; ?> <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } today = yyyy + '-' + mm + '-' + dd; document.getElementById("appt_date").setAttribute("min", today); var someDate = new Date(); var numberOfDaysToAdd = 2; someDate.setDate(someDate.getDate() + numberOfDaysToAdd); var ddd = someDate.getDate(); var mmm = someDate.getMonth() + 1; var yyy = someDate.getFullYear(); var someFormattedDate = yyy + '-' + mmm + '-' + ddd; document.getElementById("appt_date").setAttribute("max",someFormattedDate ); </script><file_sep>/portfolio.php <?php include 'simple_html_dom.php'; $html = file_get_html('https://doj.gov.in/news'); // echo '<h1>' . $html->find('title',0)->iplaintext . '</h1>'; $html->find('div[id="content"]', 0); echo $html; ?> <file_sep>/get_appointment.php <?php include 'common/_dbconnect.php'; if($_SERVER["REQUEST_METHOD"]=="POST"){ $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $phone = $_POST['phone']; $timee = $_POST['time_picker']; echo $fname .'<br>'; echo $lname .'<br>'; echo $email .'<br>'; echo $phone .'<br>'; echo $timee .'<br>'; $sql1 = "INSERT INTO `appointment` (`fname`, `lname`, `email`, `phone`, `timee`) VALUES ('$fname','$lname','$email','$phone','$timee')"; $result1 = mysqli_query($conn,$sql1); if($result1){ }else{ header("location:/Advocate-Vidhi-Chambers/appointment.php?status=existemail"); } $entered_date=$_POST['appt_date']; $timestamp = strtotime($_POST['appt_date']); $today=date("Y-m-d"); echo $today; echo '<br>'; echo $entered_date.'<br>'; // $today=strtotime($today); $date_one=strtotime($today. ' + 1 days'); $date_two=strtotime($today. ' + 2 days'); $date_three=strtotime($today. ' + 3 days'); $date1=date('Y-m-d', strtotime($today. ' + 1 days')); // echo $date1; $date2=date('Y-m-d', strtotime($today. ' + 2 days')); // echo $date2; $date3=date('Y-m-d', strtotime($today. ' + 3 days')); // echo $date3; $date=date('d',$timestamp); $month=date('m',$timestamp); $year=date('Y',$timestamp); $date11=date('d',$date_one); $month11=date('m',$date_one); $year11=date('Y',$date_one); $date22=date('d',$date_two); $month22=date('m',$date_two); $year22=date('Y',$date_two); $date33=date('d',$date_three); $month33=date('m',$date_three); $year33=date('Y',$date_three); function dayofweek($d, $m, $y) { static $t = array(0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4); $y -= $m < 3; return ($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7; } $day = dayofweek($date, $month, $year); $day=$day+1; $day1 = dayofweek($date11, $month11, $year11); $day1=$day1+1; $day2 = dayofweek($date22, $month22, $year22); $day2=$day2+1; $day3 = dayofweek($date33, $month33, $year33); $day3=$day3+1; // 1-monday // 2-tuesday // 3-wed // 4-thur // 5-friday // 6-saturday // 7-sunday if ($entered_date==$today and $day!=7) { echo 'appointment today and today no sunday'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=nosunday"); } elseif ($entered_date==$today and $day==7) { echo 'appoitment today but today sunday'.'<br>'; echo 'select another date'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=sunday"); } elseif($entered_date==$date1 and $day1!=7) { echo 'appointment tom and tom no sunday'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=nosunday"); } elseif($entered_date==$date1 and $day1==7) { echo 'appointment tom and tom sunday'.'<br>'; echo 'select another date'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=sunday"); }elseif($entered_date==$date2 and $day2!=7) { echo 'appointment day after tom and no sunday'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=nosunday"); }elseif($entered_date==$date2 and $day2==7) { echo 'appointment day after tom and sunday'.'<br>'; echo 'select another date'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=sunday"); } elseif($entered_date==$date3 and $day3!=7) { echo 'appointment done no sunday'.'<br>'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=nosunday"); } elseif($entered_date==$date3 and $day3==7) { echo 'sunday no appointments'.'<br>'; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=sunday"); }else{ echo "appointments can only be given till three days from today."; header("location:/Advocate-Vidhi-Chambers/appointment.php?status=greaterdate"); } } ?> <file_sep>/index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Vidhi Chamber</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="Law Firm Website Template" name="keywords"> <meta content="Law Firm Website Template" name="description"> <!-- Favicon --> <link href="img/favicon.ico" rel="icon"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@1,600;1,700;1,800&family=Roboto:wght@400;500&display=swap" rel="stylesheet"> <!-- CSS Libraries --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet"> <link href="lib/animate/animate.min.css" rel="stylesheet"> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <!-- Template Stylesheet --> <link href="css/style.css" rel="stylesheet"> <style> #agree{ width: 20%; color: white; padding: 10px 10px; border: none; border-radius: 4px; cursor: pointer; margin: 0; position: absolute; background:#ff6600; color:white; border:2px solid black; margin-bottom:20px; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } .modal-content{ padding:20px; } .modal-body{ text-align:center; } .modal-footerr{ margin-top:20px; margin-bottom:20px; } </style> </head> <body> <!-- Button trigger modal --> <!-- <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter"> Launch demo modal </button> --> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class='col-12 modal-title text-center' id="exampleModalLongTitle" style="font-family:Arial;color:blue;">VIDHI CHAMBERS</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="closeMe()"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p style="color:black;">Disclaimer & Confirmation As per the rules of the Bar Council of India,law firms are not permitted to solicit work and advertise.<br><br><b>By clicking on the "I AGREE" button below,user acknowledges the following:</b><br><br> a)there has been no advertisements,personal communication,solicitation,invitation or inducement of any sort whatsoever from us or any of our members to solicit any work through this website;<br><br> b)user wishes to gain more information about "VIDHI CHAMBERS" and its attorneys for his/her own. </p> </div> <div class="modal-footerr"> <button type="button" id="agree" onclick="location.href='home.php';" >I Agree</button> <!-- <button type="button" class="btn"style="background:black; color:white;" data-dismiss="modal" onclick="closeMe()"> I Diasagree</button> --> </div> </div> </div> </div> <?php include 'common/nav.php'; ?> <!-- Nav Bar End --> <!-- Carousel Start --> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="img/img1.jpg"alt="First slide"> <div class="carousel-caption" id="caption1"> <h1 class="animated fadeInLeft" id="caption1">We fight for your Privilege</h1> <!-- <p class="animated fadeInRight">Lorem ipsum dolor sit amet elit. Mauris odio mauris...</p> --> <!-- <a class="btn animated fadeInUp" href="#">Get free consultation</a> --> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="img/img3.jpg" alt="Second slide"> <div class="carousel-caption" id="caption2"> <h1 id="banner-two-text" class="animated fadeInLeft" id="caption2">We fight for your Privilege</h1> <!-- <p class="animated fadeInRight">Lorem ipsum dolor sit amet elit. Mauris odio mauris...</p> --> <!-- <a class="btn animated fadeInUp" href="#">Get free consultation</a> --> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="img/img2.jpg" alt="Third slide"> <div class="carousel-caption" id="caption3"> <h1 class="animated fadeInLeft" id="caption3">We fight for your Privilege</h1> <!-- <p class="animated fadeInRight">Lorem ipsum dolor sit amet elit. Mauris odio mauris...</p> --> <!-- <a class="btn animated fadeInUp" href="#">Get free consultation</a> --> </div> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <!-- Carousel End --> <!-- Carousel End --> <!-- Top Feature Start--> <!-- <div class="feature-top"> <div class="container-fluid"> <div class="row align-items-center"> <div class="col-md-3 col-sm-6"> <div class="feature-item"> <i class="far fa-check-circle"></i> <h3>Legal</h3> <p>Govt Approved</p> </div> </div> <div class="col-md-3 col-sm-6"> <div class="feature-item"> <i class="fa fa-user-tie"></i> <h3>Attorneys</h3> <p>Expert Attorneys</p> </div> </div> <div class="col-md-3 col-sm-6"> <div class="feature-item"> <i class="far fa-thumbs-up"></i> <h3>Success</h3> <p>99.99% Case Won</p> </div> </div> <div class="col-md-3 col-sm-6"> <div class="feature-item"> <i class="far fa-handshake"></i> <h3>Support</h3> <p>Quick Support</p> </div> </div> </div> </div> </div> --> <!-- Top Feature End--> <!-- About Start --> <div class="about"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-5 col-md-6"> <div class="about-img"> <img src="img/about.jpg" alt="Image"> </div> </div> <div class="col-lg-7 col-md-6"> <div class="section-header"> <h2>Learn About Us</h2> </div> <div class="about-text"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. </p> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor, auctor id gravida condimentum, viverra quis sem. Curabitur non nisl nec nisi scelerisque maximus. Aenean consectetur convallis porttitor. Aliquam interdum at lacus non blandit. </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> </div> <!-- About End --> <!-- Service Start --> <div class="service"> <div class="container"> <div class="section-header"> <h2>Our Practices Areas</h2> </div> <div class="row"> <div class="col-lg-4 col-md-6"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-landmark"></i> </div> <h3>Civil Law</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="col-lg-4 col-md-6"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-users"></i> </div> <h3>Family Law</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="col-lg-4 col-md-6"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-hand-holding-usd"></i> </div> <h3>Business Law</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="col-lg-4 col-md-6"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-graduation-cap"></i> </div> <h3>Education Law</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="col-lg-4 col-md-6"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-gavel"></i> </div> <h3>Criminal Law</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non </p> <a class="btn" href="">Learn More</a> </div> </div> <div class="col-lg-4 col-md-6"> <div class="service-item"> <div class="service-icon"> <i class="fa fa-globe"></i> </div> <h3>Cyber Law</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non </p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> </div> <!-- Service End --> <!-- Feature Start --> <div class="feature"> <div class="container"> <div class="row"> <div class="col-md-7"> <div class="section-header"> <h2>Why Choose Us</h2> </div> <div class="row align-items-center feature-item"> <div class="col-5"> <div class="feature-icon"> <i class="fa fa-gavel"></i> </div> </div> <div class="col-7"> <h3>Best law practices</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. </p> </div> </div> <div class="row align-items-center feature-item"> <div class="col-5"> <div class="feature-icon"> <i class="fa fa-balance-scale"></i> </div> </div> <div class="col-7"> <h3>Efficiency & Trust</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. </p> </div> </div> <div class="row align-items-center feature-item"> <div class="col-5"> <div class="feature-icon"> <i class="far fa-smile"></i> </div> </div> <div class="col-7"> <h3>Results you deserve</h3> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. </p> </div> </div> </div> <div class="col-md-5"> <div class="feature-img"> <img src="img/feature.jpg" alt="Feature"> </div> </div> </div> </div> </div> <!-- Feature End --> <!-- Team Start --> <div class="team"> <div class="container"> <div class="section-header"> <h2>Meet Our Expert Attorneys</h2> </div> <div class="row"> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-1.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Business Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-2.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Criminal Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-3.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Divorce Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-4.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Immigration Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> </div> </div> </div> <!-- Team End --> <!-- FAQs Start --> <div class="faqs"> <div class="container"> <div class="row"> <div class="col-md-5"> <div class="faqs-img"> <img src="img/faqs.jpg" alt="Image"> </div> </div> <div class="col-md-7"> <div class="section-header"> <h2>Have A Questions?</h2> </div> <div id="accordion"> <div class="card"> <div class="card-header"> <a class="card-link collapsed" data-toggle="collapse" href="#collapseOne" aria-expanded="true"> <span>1</span> Lorem ipsum dolor sit amet? </a> </div> <div id="collapseOne" class="collapse show" data-parent="#accordion"> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#collapseTwo"> <span>2</span> Lorem ipsum dolor sit amet? </a> </div> <div id="collapseTwo" class="collapse" data-parent="#accordion"> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#collapseThree"> <span>3</span> Lorem ipsum dolor sit amet? </a> </div> <div id="collapseThree" class="collapse" data-parent="#accordion"> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#collapseFour"> <span>4</span> Lorem ipsum dolor sit amet? </a> </div> <div id="collapseFour" class="collapse" data-parent="#accordion"> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non. </div> </div> </div> <div class="card"> <div class="card-header"> <a class="card-link" data-toggle="collapse" href="#collapseFive"> <span>5</span> Lorem ipsum dolor sit amet? </a> </div> <div id="collapseFive" class="collapse" data-parent="#accordion"> <div class="card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non. </div> </div> </div> </div> <a class="btn" href="">Ask more</a> </div> </div> </div> </div> <!-- FAQs End --> <!-- Testimonial Start --> <div class="testimonial"> <div class="container"> <div class="section-header"> <h2>Review From Client</h2> </div> <div class="owl-carousel testimonials-carousel"> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-1.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-2.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-3.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-4.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-1.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-2.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> <div class="testimonial-item"> <i class="fa fa-quote-right"></i> <div class="row align-items-center"> <div class="col-3"> <img src="img/testimonial-3.jpg" alt=""> </div> <div class="col-9"> <h2>Client Name</h2> <p>Profession</p> </div> <div class="col-12"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam accumsan lacus eget velit </p> </div> </div> </div> </div> </div> </div> <!-- Testimonial End --> <!-- Blog Start --> <div class="blog"> <div class="container"> <div class="section-header"> <h2>Latest From Blog</h2> </div> <div class="owl-carousel blog-carousel"> <div class="blog-item"> <img src="img/blog-1.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Civil Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> <div class="blog-item"> <img src="img/blog-2.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Family Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> <div class="blog-item"> <img src="img/blog-3.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Business Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> <div class="blog-item"> <img src="img/blog-1.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Education Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> <div class="blog-item"> <img src="img/blog-2.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Criminal Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> <div class="blog-item"> <img src="img/blog-3.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Cyber Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> <div class="blog-item"> <img src="img/blog-1.jpg" alt="Blog"> <h3>Lorem ipsum dolor</h3> <div class="meta"> <i class="fa fa-list-alt"></i> <a href="">Business Law</a> <i class="fa fa-calendar-alt"></i> <p>01-Jan-2045</p> </div> <p> Lorem ipsum dolor sit amet elit. Phasellus nec pretium mi. Curabitur facilisis ornare velit non vulputate. Aliquam metus tortor </p> <a class="btn" href="">Read More <i class="fa fa-angle-right"></i></a> </div> </div> </div> </div> <!-- Blog End --> <!-- Footer Start --> <?php include 'common/footer.php'; ?> <!-- Footer End --> <a href="#" class="back-to-top"><i class="fa fa-chevron-up"></i></a> </div> <!-- JavaScript Libraries --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script> <script src="lib/easing/easing.min.js"></script> <script src="lib/owlcarousel/owl.carousel.min.js"></script> <script src="lib/isotope/isotope.pkgd.min.js"></script> <!-- Template Javascript --> <script src="js/main.js"></script> <script type="text/javascript"> $(window).on('load', function() { $('#exampleModalCenter').modal('show'); }); function closeMe() { window.open('','_parent',''); window.close(); //document.getElementsByTagName ('html') [0] .remove (); window.open('https://www.google.com/', '_self'); } </script> </body> </html> <file_sep>/web_scrap.php <?php include 'simple_html_dom.php'; $html = file_get_html('https://amlegals.com/indian-lawyers-firm-amlegals/practice-areas/'); // echo '<h1>' . $html->find('title',0)->iplaintext . '</h1>'; $html->find('bt_bb_port', 0)->plaintext ; echo $html; ?> <file_sep>/about.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><NAME>-About Us</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="Law Firm Website Template" name="keywords"> <meta content="Law Firm Website Template" name="description"> <!-- Favicon --> <link href="img/favicon.ico" rel="icon"> <!-- Google Font --> <link href="https://fonts.googleapis.com/css2?family=EB+Garamond:ital,wght@1,600;1,700;1,800&family=Roboto:wght@400;500&display=swap" rel="stylesheet"> <!-- CSS Libraries --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet"> <link href="lib/animate/animate.min.css" rel="stylesheet"> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <!-- Template Stylesheet --> <link href="css/style.css" rel="stylesheet"> </head> <body> <!-- Nav Bar Start --> <?php include 'common/nav.php'; ?> <!-- Nav Bar End --> <!-- Page Header Start --> <!-- <div class="page-header"> <div class="container"> <div class="row"> <div class="col-12"> <h2>About Us</h2> </div> <div class="col-12"> <a href="">Home</a> <a href="">About Us</a> </div> </div> </div> </div> --> <!-- Page Header End --> <!-- About Start --> <div class="about"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-5 col-md-6"> <div class="about-img"> <img src="img/about.jpg" alt="Image"> </div> </div> <div class="col-lg-7 col-md-6"> <div class="section-header"> <h2>Learn About Us</h2> </div> <div class="about-text"> <p style="color:black;"> Vidhi chambers is a full service law institute established with the objective of providing comprehensive and sophisticated legal advice and services to its clients, who are a mix of small and large companies including the individual clients engaged in a myriad of complex commercial activities. The vidhi chambers recognize that its ability to provide high quality and useful advice to clients is entirely driven by the expertise and experience of its attorneys. Consequently the firm lays utmost emphasis on ensuring that its attorneys not only posses strong legal acumen but also diligence and commercial understanding required to meet clients expectations and offer reliable and business oriented legal solutions.</p> <a class="btn" href="">Learn More</a> </div> </div> </div> </div> </div> <!-- About End --> <!-- Timeline Start --> <div class="timeline"> <div class="container"> <div class="section-header"> <h2>Learn About Our Journey</h2> </div> <div class="timeline-start"> <div class="timeline-container left"> <div class="timeline-content"> <h2><span>2020</span>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet elit. Aliquam odio dolor, id luctus erat sagittis non. Ut blandit semper pretium. </p> </div> </div> <div class="timeline-container right"> <div class="timeline-content"> <h2><span>2019</span>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet elit. Aliquam odio dolor, id luctus erat sagittis non. Ut blandit semper pretium. </p> </div> </div> <div class="timeline-container left"> <div class="timeline-content"> <h2><span>2018</span>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet elit. Aliquam odio dolor, id luctus erat sagittis non. Ut blandit semper pretium. </p> </div> </div> <div class="timeline-container right"> <div class="timeline-content"> <h2><span>2017</span>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet elit. Aliquam odio dolor, id luctus erat sagittis non. Ut blandit semper pretium. </p> </div> </div> <div class="timeline-container left"> <div class="timeline-content"> <h2><span>2016</span>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet elit. Aliquam odio dolor, id luctus erat sagittis non. Ut blandit semper pretium. </p> </div> </div> <div class="timeline-container right"> <div class="timeline-content"> <h2><span>2015</span>Lorem ipsum dolor sit amet</h2> <p> Lorem ipsum dolor sit amet elit. Aliquam odio dolor, id luctus erat sagittis non. Ut blandit semper pretium. </p> </div> </div> </div> </div> </div> <!-- Timeline End --> <!-- Team Start --> <div class="team"> <div class="container"> <div class="section-header"> <h2>Meet Our Expert Attorneys</h2> </div> <div class="row"> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-1.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Business Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-2.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Criminal Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-3.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Divorce Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> <div class="col-lg-3 col-md-6"> <div class="team-item"> <div class="team-img"> <img src="img/team-4.jpg" alt="Team Image"> </div> <div class="team-text"> <h2><NAME></h2> <p>Immigration Consultant</p> <div class="team-social"> <a class="social-tw" href=""><i class="fab fa-twitter"></i></a> <a class="social-fb" href=""><i class="fab fa-facebook-f"></i></a> <a class="social-li" href=""><i class="fab fa-linkedin-in"></i></a> <a class="social-in" href=""><i class="fab fa-instagram"></i></a> </div> </div> </div> </div> </div> </div> </div> <!-- Team End --> <!-- Footer Start --> <?php include 'common/footer.php'; ?> <!-- Footer End --> <a href="#" class="back-to-top"><i class="fa fa-chevron-up"></i></a> </div> <!-- JavaScript Libraries --> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script> <script src="lib/easing/easing.min.js"></script> <script src="lib/owlcarousel/owl.carousel.min.js"></script> <script src="lib/isotope/isotope.pkgd.min.js"></script> <!-- Template Javascript --> <script src="js/main.js"></script> </body> </html> <file_sep>/disclaimer.php <!DOCTYPE html> <html> <head> <title><NAME>-Disclaimer</title> <script src="https://use.fontawesome.com/0cf079388a.js"></script> </head> <style> /* html { background: url(img/flag1.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } */ /* body { font-family: "Poppins", sans-serif; height: 100vh; } */ a { color: #0e76a8 ; display:inline-block; text-decoration: none; font-weight: 400; } h2 { text-align: center; font-size: 20px; font-weight: 800; text-transform: uppercase; display:inline-block; margin: 40px 8px 10px 8px; color: #cccccc; } .wrapper { display: flex; align-items: center; flex-direction: column; justify-content: center; width: 100%; min-height: 100%; padding: 20px; } #formContent { -webkit-border-radius: 10px 10px 10px 10px; border-radius: 10px 10px 10px 10px; background: #87CEEB; padding: 40px; padding-top:20px; width: 60%; position: relative; -webkit-box-shadow: 0 30px 60px 0 rgba(0,0,0,0.3); box-shadow: 0 30px 60px 0 rgba(0,0,0,0.3); } #exampleModalLongTitle{ text-align:center; font-size:20px; font-weight:600; } #agree{ width: 10%; color: white; padding: 10px 10px; border: none; border-radius: 4px; cursor: pointer; margin: 0; position: absolute; margin-top:15px; margin-bottom:35px; left: 50%; -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } #formFooter { background-color: #f6f6f6; border-top: 1px solid #dce8f1; padding: 25px; text-align: center; -webkit-border-radius: 0 0 10px 10px; border-radius: 0 0 10px 10px; } h2.inactive { color: #cccccc; } h2.active { color: #0d0d0d; border-bottom: 2px solid #5fbae9; } input[type=button], input[type=submit], input[type=reset] { background-color: #56baed; border: none; color: white; padding: 15px 80px; text-align: center; text-decoration: none; display: inline-block; text-transform: uppercase; font-size: 13px; -webkit-box-shadow: 0 10px 30px 0 rgba(95,186,233,0.4); box-shadow: 0 10px 30px 0 rgba(95,186,233,0.4); -webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; margin: 5px 20px 40px 20px; -webkit-transition: all 0.3s ease-in-out; -moz-transition: all 0.3s ease-in-out; -ms-transition: all 0.3s ease-in-out; -o-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } input[type=button]:hover, input[type=submit]:hover, input[type=reset]:hover { background-color: #39ace7; } input[type=button]:active, input[type=submit]:active, input[type=reset]:active { -moz-transform: scale(0.95); -webkit-transform: scale(0.95); -o-transform: scale(0.95); -ms-transform: scale(0.95); transform: scale(0.95); } input[type=email],input[type=password],input[type=text] { background-color: #f6f6f6; border: none; color: #0d0d0d; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 5px; width: 85%; border: 2px solid #f6f6f6; -webkit-transition: all 0.5s ease-in-out; -moz-transition: all 0.5s ease-in-out; -ms-transition: all 0.5s ease-in-out; -o-transition: all 0.5s ease-in-out; transition: all 0.5s ease-in-out; -webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; } input[type=text],input[type=email],input[type=password]:focus { background-color: #fff; border-bottom: 2px solid #5fbae9; } input[type=text]:placeholder { color: #a6a6a6; } .fadeInDown { -webkit-animation-name: fadeInDown; animation-name: fadeInDown; -webkit-animation-duration: 1s; animation-duration: 1s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translate3d(0, -100%, 0); transform: translate3d(0, -100%, 0); } 100% { opacity: 1; -webkit-transform: none; transform: none; } } @keyframes fadeInDown { 0% { opacity: 0; -webkit-transform: translate3d(0, -100%, 0); transform: translate3d(0, -100%, 0); } 100% { opacity: 1; -webkit-transform: none; transform: none; } } @-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } } @-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } } @keyframes fadeIn { from { opacity:0; } to { opacity:1; } } .fadeIn { opacity:0; -webkit-animation:fadeIn ease-in 1; -moz-animation:fadeIn ease-in 1; animation:fadeIn ease-in 1; -webkit-animation-fill-mode:forwards; -moz-animation-fill-mode:forwards; animation-fill-mode:forwards; -webkit-animation-duration:1s; -moz-animation-duration:1s; animation-duration:1s; } .fadeIn.first { -webkit-animation-delay: 0.4s; -moz-animation-delay: 0.4s; animation-delay: 0.4s; } .fadeIn.second { -webkit-animation-delay: 0.6s; -moz-animation-delay: 0.6s; animation-delay: 0.6s; } .fadeIn.third { -webkit-animation-delay: 0.8s; -moz-animation-delay: 0.8s; animation-delay: 0.8s; } .fadeIn.fourth { -webkit-animation-delay: 1s; -moz-animation-delay: 1s; animation-delay: 1s; } .underlineHover:after { display: block; left: 0; bottom: -10px; width: 0; height: 2px; background-color: #56baed; content: ""; transition: width 0.2s; } .underlineHover:hover { color: #0d0d0d; } .underlineHover:hover:after{ width: 100%; } /* OTHERS */ *:focus { outline: none; } #icon { width:40%; } * { box-sizing: border-box; } @media(max-width:500px){ #formContent{ width:100%; } } @media(max-width: 430px){ #formContent{ width:100%; max-width:550px; } @media(max-width:330px){ #formContent{ background: #000; width:100%; max-width:670px; } </style> <div class="wrapper fadeInDown"> <div id="formContent"> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">VIDHI CHAMBERS</h5> </div> <div class="modal-body"> <p style="color:black;">Disclaimer & Confirmation As per the rules of the Bar Council of India,law firms are not permitted to solicit work and advertise.<br><br>By clicking on the "I AGREE" button below,user acknowledges the following:<br><br> a)there has been no advertisements,personal communication,solicitation,invitation or inducement of any sort whatsoever from us or any of our members to solicit any work through this website;<br><br> b)user wishes to gain more information about "VIDHI CHAMBERS" and its attorneys for his/her own. </p> </div> <div class="modal-footer"> <button type="button" class="btn" style="background:white; color:black;" id="agree" onclick="location.href='home.php';" >I Agree</button> </div> </div> </div> </div> </div> <script> const togglePassword = document.querySelector('#show'); const password = document.querySelector('#password'); togglePassword.addEventListener('click', function (e) { const type = password.getAttribute('type') === 'password' ? 'text' : 'password'; password.setAttribute('type', type); this.classList.toggle('fa-eye-slash'); }); </script> </html>
607c0a53667c867c89d75f1d1ae76bb79711bdae
[ "PHP" ]
8
PHP
MeghaShahri/Advocate-Vidhi-Chamber
1c7833dc922e1870b115a05b152e1e85c28a48cf
524bda4d22c9fda3f7b9d6bfaa971cbd93f5ef5f
refs/heads/master
<repo_name>team-obliq/obliq<file_sep>/README.md # obliq Human Beings. We all have problems needing to be solved. Yet sometimes, no matter what experts surround us in our field/career, we simply don't know where to turn to solve them. This is where Obliq steps in. Based on & implementing <NAME>'s "Oblique Strategies" from 1975, Obliq is a full stack web application designed to bring people together to help solve problems in real time. After sign up, a user is set into a "tribe" of users - paired together according to the OPPOSITE spectrum of their field/career. This facilitates conversations organically that wouldn't normally happen to help solve individual, business or artistic concerns. Within each communication, the entire card system of "Oblique Strategies" is able to be shared & upvoted between members - as not only a "gnomic" expressions, but comments on that particular problem presented. For every successful problem solved by either card or post, a user of the tribe then gains points, further building standing within the tribe. The points eventually lead to access of completely new, bigger tribes - tribes completely dissimilar to the previous one! In this way, Obliq aims - through constraint - to redefine how people connect to solve the issues facing our world today. Obliq - Problem Solving: Redefined. <file_sep>/src/main/java/com/obliq/obliq/ENTITYS/Career.java package com.obliq.obliq.ENTITYS; import javax.persistence.*; @Entity @Table(name="careers") public class Career{ @Id @GeneratedValue private long id; @Column (name = "title", nullable = false, length = 250, unique=true ) private String title; public Career(){} public Career(String title) { this.title = title; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } /* --1 (name of the table you want to create----------------------------------------------------------------------------------------- */ /* --2 (name of the entity object you are creating----------------------------------------------------------------------------------------- */ /* --3 (title of the column heading----------------------------------------------------------------------------------------- */ /* --4 (If this entity is owned by an Object----------------------------------------------------------------------------------------- */ /* --5 (Object owners nickname----------------------------------------------------------------------------------------- */ <file_sep>/careers.sql use obliq_db; INSERT INTO careers(title) values ('Doctor'), ('Programmer'), ('Astrologist'), ('Nutritionist'), ('Archaeologist'), ('Architect'), ('Writer'), ('<NAME>'), ('Painter'), ('Soldier'), ('Musician'), ('Carpenter'), ('Data Scientist'), ('Teacher');<file_sep>/src/main/resources/static/js/keys.js const filestackToken = '<PASSWORD>'; const twilioToken = '<PASSWORD>'; console.log("hello from keys.js")<file_sep>/src/main/resources/static/js/navbar.js $(function () { $("a.nav-link[href='" + window.location.pathname + "']").addClass('font-weight-bold') }) $(function () { $('[data-toggle="popover"]').popover() })<file_sep>/src/main/java/com/obliq/obliq/TESTING/Testing.java package com.obliq.obliq.TESTING; import org.hibernate.annotations.CreationTimestamp; import org.springframework.format.annotation.DateTimeFormat; import java.util.Calendar; import java.util.Date; import javax.persistence.*; import java.sql.Time; @Entity @Table(name="testing") public class Testing{ @Id @GeneratedValue private long id; @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false, name = ("date_created")) @DateTimeFormat(pattern="dd.MM.yyyy HH:mm:ss") private Date dateCreated; /* -Constructor------------------------------------------------------------------------------------------ */ public Testing() {} /* -Getters------------------------------------------------------------------------------------------ */ public long getId() { return id; } public Date getDateCreated() { return dateCreated; } /* -Setters------------------------------------------------------------------------------------------ */ public void setId(long id) { this.id = id; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } } /* --1 (name of the table you want to create----------------------------------------------------------------------------------------- */ /* --2 (name of the entity object you are creating----------------------------------------------------------------------------------------- */ /* --3 (title of the column heading----------------------------------------------------------------------------------------- */ /* --4 (If this entity is owned by an Object----------------------------------------------------------------------------------------- */ /* --5 (Object owners nickname----------------------------------------------------------------------------------------- */ <file_sep>/src/main/resources/static/js/showPost.js //adding event listener to upvote button function upvoteListener(){ document.getElementById('upvote').addEventListener('click',function (e) { e.preventDefault(); console.log('WERE LISTENING'); }); } upvoteListener();<file_sep>/src/main/java/com/obliq/obliq/CTRL/comments_CTRL.java package com.obliq.obliq.CTRL; import com.obliq.obliq.ENTITYS.Comment; import com.obliq.obliq.ENTITYS.User; import com.obliq.obliq.REPOS.CommentRepository; import com.obliq.obliq.REPOS.PostRepository; import com.obliq.obliq.REPOS.UserRepository; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller public class comments_CTRL { private UserRepository userRepo; private PostRepository postRepo; private CommentRepository commentRepo; public comments_CTRL(UserRepository userRepo, PostRepository postRepo, CommentRepository commentRepo) { this.userRepo = userRepo; this.postRepo = postRepo; this.commentRepo = commentRepo; } @GetMapping("/comments/create") public String showCommentForm(Model model) { model.addAttribute("comment", new Comment()); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); model.addAttribute("user", user); return "posts/showPost"; } @PostMapping("/comments/create") public String createComment(@ModelAttribute Comment comment, @RequestParam(name="postId") long postId) { User sessionUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User userDb = userRepo.findOne(sessionUser.getId()); comment.setUser(userRepo.findOne(sessionUser.getId())); comment.setPost(postRepo.findOne(postId)); commentRepo.save(comment); return "redirect:/posts/showPost/" + postId; } @GetMapping("/add/{id}") public String upVoteShow(@PathVariable long id, Model model) { User sessionUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User userDb = userRepo.findOne(sessionUser.getId()); Comment comment = commentRepo.findOne(id); userDb.addToCommentList(comment); userRepo.save(userDb); model.addAttribute("comment", commentRepo.findOne(id)); return "redirect:/posts/showPost/" + comment.getPost().getId(); } @GetMapping("/edit/{id}") public String showEditForm(@PathVariable long id, Model model) { Comment comment = commentRepo.findOne(id); model.addAttribute("comment", comment); model.addAttribute("post", comment.getPost()); return "comments/edit"; } @PostMapping("/edit/{id}") public String editComment(@ModelAttribute Comment commentEdited) { User sessionUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); commentEdited.setUser(userRepo.findOne(sessionUser.getId())); commentRepo.save(commentEdited); return "redirect:/posts/showPost/" + commentEdited.getPost().getId(); } @GetMapping("/delete/{id}") public String deleteComment(@PathVariable long id) { Comment comment = commentRepo.findOne(id); commentRepo.delete(comment); return "redirect:/my-profile"; } } <file_sep>/src/main/java/com/obliq/obliq/CTRL/tribe_CTRL.java package com.obliq.obliq.CTRL; import com.obliq.obliq.ENTITYS.Career; import com.obliq.obliq.ENTITYS.Post; import com.obliq.obliq.ENTITYS.User; import com.obliq.obliq.REPOS.CareersRepository; import com.obliq.obliq.REPOS.CommentRepository; import com.obliq.obliq.REPOS.PostRepository; import com.obliq.obliq.REPOS.UserRepository; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import java.util.ArrayList; import java.util.List; @Controller public class tribe_CTRL { // repo injection private UserRepository userRepo; private PostRepository postRepo; private CommentRepository commentRepo; private CareersRepository careerRepo; public tribe_CTRL(UserRepository userRepo, PostRepository postRepo, CommentRepository commentRepo, CareersRepository careerRepo) { this.userRepo = userRepo; this.postRepo = postRepo; this.commentRepo = commentRepo; this.careerRepo = careerRepo; } // map profile view @GetMapping("/my-tribe") public String profile_get(Model model) { User sessionUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user = userRepo.findOne(sessionUser.getId()); List <User> tribe_users = new ArrayList<>(); for (User u : userRepo.findAll()) { if (u.getTribe_id() == user.getTribe_id()) tribe_users.add(u); } List<Career> careers = new ArrayList<>(); for (Career c : careerRepo.findAll()) { for (User u : tribe_users) { if (c.getId() == u.getCareer_id()) { careers.add(c); } } } model.addAttribute("users", tribe_users); model.addAttribute("careers", careers); List<Post> tribe_posts = new ArrayList<>(); for(Post p: postRepo.findAll()) { if (p.getUser().getTribe_id() == user.getTribe_id()) tribe_posts.add(p); } model.addAttribute("posts", tribe_posts); return "tribes/tribe"; } // // /* ---Post info attributes---------------------------------------------------------------------------------------- */ //// post_owner_name = postRepo.findOne(id).getUser().getFirst_name(); //// long career_id = postRepo.findOne(id).getUser().getCareer_id(); //// post_owner_career = careerRepo.findOne(career_id).getTitle(); //// post_date = postRepo.findOne(id).getDateCreated(); //// //// model.addAttribute("post_owner_name", post_owner_name); //// model.addAttribute("post_owner_career", post_owner_career); //// model.addAttribute("post_date", post_date); // /* ------------------------------------------------------------------------------------------- */ // // // model.addAttribute("comment", new Comment()); // model.addAttribute("comments", commentRepo.findByPostId(id)); // model.addAttribute("postId"); // return "tribes/posts"; // } @PostMapping("/Tribe") public String profile_post() { return "Tribe"; } }<file_sep>/seeder.sql use obliq; INSERT INTO users (username, email, password, first_name, bio, continent, points, tribe_id, career_id, date_created) VALUES ('travis', '<EMAIL>', 'travis', 'travis', 'this is my bio', 1, 0, 1, 2, CURRENT_DATE ); INSERT INTO users (username, email, password, first_name, bio, continent, points, tribe_id, career_id, date_created) VALUES ('carlo', '<EMAIL>', 'carlo', 'carlo', 'this is carlos bio', 1, 0 , 2, 1, current_date ); INSERT INTO posts (title, body, date_created, user_id) values ('Post #1', 'This is post #1', CURRENT_DATE, 1); INSERT INTO posts (title, body, date_created, user_id) values ('Post #3', 'This is post #3', CURRENT_DATE, 1); INSERT INTO posts (title, body, date_created, user_id) values ('Post #3', 'This is post #3', CURRENT_DATE, 2); INSERT INTO comments (date_created, body, points, post_id, user_id) values (current_date, 'This is the body of the comment', 1, 1, 2); INSERT INTO comments (date_created, body, points, post_id, user_id) values (CURRENT_DATE, 'this is the comment body', 1, 2, 1); INSERT INTO comments (date_created, body, points, post_id, user_id) values (CURRENT_DATE, 'this is the comment body for comment #3', 1, 1, 1); INSERT INTO card (card_name) values ('Remove specifics and convert to ambiguities'), ('Think of the Radio'), ('Dont be frightened of cliches'), ('Allow an easement'),('What is the reality of the situation?'), ('Simple Subtraction'), ('Are there sections? Consider transitions'), ('Turn it upside down'), ('Go slowly all the way round the outside'),('A line has two sides'), ('Infinitesimal gradations'), ('Make an exhaustive list of everything you might do and do the last thing on the list'), ('Change instrument roles'),( 'Into the impossible'), ('Accretion'), ('Ask people to work against their better judgement'),('Disconnect from desire'), ('Take away the elements in order of apparent non-importance'),('Emphasize repetitions'), ('Dont be afraid of things because theyre easy to do'),('Is there something missing?'), ('Dont be frightened to display your talents'),('Use unqualified people'), ('Breathe more deeply'),('How would you have done it?'),('Honor thy error has hidden intention'), ('Emphasize differences'),('Only one element of each kind'),('Do nothing for as long as possible'), ('Bridges: build, burn'),('Water'),('You dont have to be ashamed of using your own ideas'), ('Make a sudden, destructive unpredictable action; incorporate'), ('Tidy up'),('Consult other sources'),('Do the words need changing?'), ('Use an unacceptable color'),('Ask your body'),('Humanize something free of error'), ('Use filters'),('Balance the consistency principle with the inconsistency principle'), ('Fill every beat with something'),('Discard an axiom'),('Listen to the quiet voice'), ('What wouldnt you do?'),('Is it finished?'),('Decorate, decorate'),('Put in earplugs'), ('Give the game away'),('Reverse'),('Abandon normal instruments'),('Trust in the you of now'), ('Use fewer notes'),('What would your closest friend do?'),('Repetition is a form of change'), ('Distorting time'),('Give way to your worst impulse'),('Make a blank valuable by putting in an exquisite frame'), ('Blankness'),('The inconsistency principle'),('Ghost echoes'), ('Dont break the silence'),('You can only make one dot at a time'), ('Discover the recipes you are using & abandon them'),('Just carry on'), ('Cascades'),('(Organic) machinery'),('Courage!'),('What mistakes did you make last time?'), ('You are an engineer'),('Consider different fading systems'),('Remove ambiguities and convert to specifics'), ('Mute and continue'),('Look at the order in which you do things'), ('It is quite possible(after all)'),('Go outside. Shut the door'), ('Dont stress one thing more than another'),('Do we need holes'), ('Cluster analysis'),('Work at a different speed'),('Do something boring'),('Look closely at the most embarrassing details and amplify them'), ('Define an area as safe and use it as an anchor'),('Mechanicalize something idiosyncratic'), ('Overly resist change'),('Emphasize the flaws'),('Accept Advice'),('Remember those quiet evenings'), ('Take a break'),('The tape is now the music'),('Short Circuit: (example; a man eating peas with the idea that they will improve his virility shovels them straight into his lap'), ('Imagine the music as a moving chain or caterpillar'),('Use an old idea'), ('Intentions: credibility of, nobility of, humility of'),('Destroy: nothing, the most important thing'), ('Change nothing and continue with immaculate consistency'),('Imagine the music as a set of disconnected events'), ('Imagine the piece as a set of disconnected events'),('What are you really thinking about just now? Incorporate'), ('Childrens voices: speaking, singing'),('Assemble some of the instruments in a group and treat the group'), ('Feedback recordings into an acoustic situation'),('Shut the door and listen from outside'), ('Towards the insignificant'),('Is the tuning appropriate?'),('Simply a matter of work'), ('Look at a very small object, look at its center'),('Not building a wall but making a brick'), ('Re-evaluation(a warm feeling)'),('Disciplined self-indulgence'), ('The most important thing is the thing most easily forgotten'),('Always first steps'), ('Idiot glee'),('Question the heroic approach'),('Be extravagant'), ('Always give yourself credit for having more personality'),('State the problems in words as clear as possible'), ('Faced with choice, do both'),('Tape your mouth'),('Twist the spine'), ('Get your neck massaged'),('Lowest common denominator check: single beat, single note, single riff'), ('Do the washing up'),('Listen in total darkness, or in a very large room, very quietly'), ('Convert a melodic element into a rhythmic element'),('Would anybody want it?'), ('Spectrum analysis'),('Retrace your steps'),('Go to an extreme, move back to the more comfortable place'), ('Once the search is in the progress, something will be found'),('Only a part, not the whole'), ('From nothing to more than nothing'),('Be less critical more often'); INSERT INTO users (username, email, password, first_name, bio, continent, points, tribe_id, career_id, date_created) values ('MinaMoon', '<EMAIL>', 'mina', 'Mina', 'My name is Mina and I am a user', 'Africa', 0, 1, 1, current_date), ('JesseRune', '<EMAIL>', 'jesse', 'Jesse', 'My name is Jesse & I am not a user', 'Australia', 0, 1, 1, current_date), ('MarshaTizzo', '<EMAIL>', 'marsha', 'Marsha', 'My name is Marsha, I dont care', 'United States', 0, 1, 1, current_date), ('RoamByaz', '<EMAIL>', 'roam', 'Roam', 'I roam and thats it', 'Europe', 0, 1, 1, current_date), ('ClydeDina', '<EMAIL>', 'clyde', 'Clyde', 'My name is Clyde, thats all', 'Africa', 0, 1, 1, current_date), ('MagentaPatriot', '<EMAIL>', 'magenta', 'Magenta', 'Magenta is my name', 'South America', 0, 1, 4, current_date), ('CyanMyst', '<EMAIL>', 'myst', 'Cyan', 'My name is an island - Myst', 'United States', 0, 1, 4, current_date), ('NadiaGeorgino', '<EMAIL>', 'nadia', 'Nadia', 'Nadia is my name yo', 'Asia', 0, 1, 4, current_date), ('MaroonAcme', '<EMAIL>', 'maroon', 'Maroon', 'Acme Brick Company - Maroon', 'Australia', 0, 1, 4, current_date); INSERT INTO comments (date_created, body, points, post_id, user_id) VALUES (current_date,'this is Minas comment',0,1,1), (current_date,'this is Maroons comment',0,2,2), (current_date, 'this is Magentas comment', 0, 3, 3), (current_date, 'this is Roams comment',0,4,4), (current_date, 'This Clydes comment',0,5,5), (current_date, 'This is Jesses comment', 0,6,6), (current_date, 'This is Marshas comment', 0,7,7), (current_date, 'This is Nadias comment', 0,8,8), (current_date, 'This is Cyans comment', 0,9,9); INSERT INTO posts (title, body, date_created, user_id) VALUES ('Minas gonna Mean', 'Mina cant choose what color for her room', current_date, 1), ('Maroon Acme rises Again', 'How come my bricks keep failing?', current_date, 2), ('Magenta is no color at all!', 'Magenta needs more clarity on her problem', current_date, 3), ('Roam is gonna Roam - thats it', 'Roam has had it with Peanuts - who can help?', current_date, 4), ('Clyde doesnt belong here', 'Clyde cant get this paint to mix', current_date, '5'), ('Jesse doesnt play that', 'Homie literally doesnt play that', current_date, '6'), ('Marsha is not a Warfield', 'The warfield is my home & Im having a hard time adjusting', current_date, 7), ('Nadia is in control of everything', 'How can I relinquish control more?',current_date, 8) ('Cyan thinks Myst is awesome', 'Did I tell you the game Myst is awesome - how is it not awesome?', current_date, 9); INSERT INTO users (username, email, password, first_name, bio, continent, points, tribe_id, career_id, date_created) VALUES ('<NAME>', '<EMAIL>', 'triphone', 'Triphone', 'My name is <NAME>', 'Asia', 0, 1, 2,current_date); INSERT INTO posts (title, body, date_created, user_id) VALUES ('Triphone is going to Try', 'I need help switching to Android', current_date, 10); INSERT INTO comments (date_created, body, points, post_id, user_id) VALUES (current_date, 'further comment: android sucks', 0, 4,10);
5e9b5f82f0f76cb6ee7b28ce139e87b898483a52
[ "Markdown", "Java", "JavaScript", "SQL" ]
10
Markdown
team-obliq/obliq
e79e3d80cf8ac7aa2f124d022c62db7b46e12cf6
3a155603f6f4b4aeed940801634a0ac3d2b4e538
refs/heads/master
<file_sep><?php class DatabaseFactory { static function getConnection() { $Host = SysProperties::getPropertyValue("bancodados.servidor"); $User = SysProperties::getPropertyValue("bancodados.usuario"); $Pass = SysProperties::getPropertyValue("bancodados.senha"); $dbname = SysProperties::getPropertyValue("bancodados.basedados"); return DBImpl::db_connect($Host, $User, $Pass, $dbname); } } ?> <file_sep><?php class SessionCtlr { public static function StartLongSession() { if ( ! session_id() ) { if (!session_start()) { $error = error_get_last(); Logger::logerror($error['message']); } } @header("Connection: Keep-Alive"); @header("Keep-Alive: timeout=7200"); @ini_set("default_socket_timeout", "7200"); @ini_set("max_execution_time", "0"); @ini_set("max_input_time", "7200"); @ini_set("file_uploads", "1"); @ini_set("upload_max_filesize", "150M"); @ini_set("max_file_uploads", "1000"); @ini_set("post_max_size", "150M"); @ini_set("memory_limit", "1024M"); @ini_set("session.gc_maxlifetime", "7200"); @ini_set("session.cookie_lifetime", "0"); @ini_set('session.gc_probability', 1); @ini_set('session.gc_divisor', "100"); @ini_set("from", "<EMAIL>"); @ini_set("sendmail_from", "<EMAIL>"); @ini_set('safe_mode', 0); @ini_set("output_buffering", "Off"); @ini_set('implicit_flush', 1); @ini_set('zlib.output_compression', 0); @ini_set('max_execution_time', 800); session_cache_expire(7200); session_cache_limiter(null); set_time_limit(7200); ignore_user_abort(TRUE); } public static function FlushSession() { ob_flush(); flush(); sleep(1); } public static function EndSession() { session_write_close(); } } ?><file_sep>CarregaNoticias =============== Carrega noticas querocarros.com <file_sep><?php mb_internal_encoding("ISO-8859-1"); require_once 'core/SysProperties.php'; require_once 'PHPMailer/class.smtp.php'; require_once 'PHPMailer/class.phpmailer.php'; require_once 'core/Logger.php'; require_once 'core/SessionCtrl.php'; require_once 'core/FileIO.php'; require_once 'core/xmlLoad.php'; require_once 'core/DBImpl.php'; require_once 'core/BancoDadosFactory.php'; require_once 'core/HTTPRequest.php'; SessionCtlr::StartLongSession(); echo "<pre>".PHP_EOL; $dirin = SysProperties::getPropertyValue("carga.diretorio.leitura"); Logger::loginfo("Drietorior:" . $dirin); echo "Diretório: " . realpath($dirin) . "<br/>"; $listaarquivos = array(); foreach (scandir($dirin) as $file) { if (strpos($file, ".xml")) { $listaarquivos[] = realpath($dirin . "/" . $file); } } Logger::loginfo("Total de arquivos a processar:" . count($listaarquivos)); echo "Total de arquivos a processar:" . count($listaarquivos)."<br>".PHP_EOL; foreach ($listaarquivos as $arquivo) { $fields = array("arquivo" => $arquivo); echo "Arquivo encontrado: $arquivo<br>".PHP_EOL; Logger::loginfo("Arquivo encontrado: $arquivo"); HTTPRequest::PostDataAssync("noticias/CarregaNoticiasXML.php", $fields); } echo "</pre>".PHP_EOL; exit(0); ?><file_sep>carga.tipo.origem=diretorio carga.arquivo.nome= carga.diretorio.leitura=. carga.diretorio.backup=. carga.tempo.interacao=1 carga.upload.maximage=4 logger.level=0 logger.sendmail=false logger.mailto="<EMAIL>, <EMAIL>" mail.host=mail.websitelive.net mail.port=25 mail.from="<EMAIL>" mail.usuario="<EMAIL>" mail.senha="<PASSWORD>!" bancodados.drive=sqlsrv bancodados.servidor=mssql2.websitelive.net bancodados.usuario=itcar bancodados.senha=<PASSWORD> bancodados.basedados=itcar<file_sep><?php class DBImpl { static function db_connect($host, $usr, $pwd, $databasename) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); $return = null; switch ($db_dialect) { case 'mysql': { $return = mysql_connect($host, $usr, $pwd); if ($return === FALSE) { Logger::logerror(mysql_error()); return FALSE; } mysql_select_db($databasename, $return); break; } case 'mysqli': { $return = mysqli_connect($host, $usr, $pwd, $databasename); if ($return === FALSE) { Logger::logerror(mysqli_error($return)); return FALSE; } break; } case 'mssql': { $return = mssql_connect($host, $usr, $pwd); if ($return === FALSE) { Logger::logerror(mssql_get_last_message()); return FALSE; } mssql_select_db($databasename); break; } case 'sqlsrv': { $return = sqlsrv_connect($host, array('UID' => $usr, 'PWD' => $pwd, 'Database' => $databasename)); if ($return === FALSE) { $sql_errors = sqlsrv_errors(); Logger::logerror(print_r($sql_errors, TRUE)); return FALSE; } break; } } return $return; } static function db_query($query, $conn) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); $return = null; switch ($db_dialect) { case 'mysql': { $return = mysql_query($query, $conn); if ($return === FALSE) { Logger::logerror(mysql_error()); return FALSE; } break; } case 'mysqli': { $return = mysqli_query($conn, $query); if ($return === FALSE) { Logger::logerror(mysqli_error($return)); return FALSE; } break; } case 'mssql': { $return = mssql_query($query, $conn); if ($return === FALSE) { Logger::logerror(mssql_get_last_message()); return FALSE; } break; } case 'sqlsrv': { $return = sqlsrv_query($conn, $query); if ($return === FALSE) { $sql_errors = sqlsrv_errors(); Logger::logerror(print_r($sql_errors, TRUE)); return FALSE; } break; } } return $return; } static function db_fetch_array($result) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); $return = null; switch ($db_dialect) { case 'mysql': { $return = mysql_fetch_array($result); break; } case 'mysqli': { $return = mysqli_fetch_array($result); break; } case 'mssql': { $return = mssql_fetch_array($result); break; } case 'sqlsrv': { $return = sqlsrv_fetch_array($result); break; } } return $return; } static function db_fetch_assoc($result) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); $return = null; switch ($db_dialect) { case 'mysql': { $return = mysql_fetch_assoc($result); break; } case 'mysqli': { $return = mysqli_fetch_assoc($result); break; } case 'mssql': { $return = mssql_fetch_assoc($result); break; } case 'sqlsrv': { $return = false; break; } } return $return; } static function db_close($conn) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); switch ($db_dialect) { case 'mysql': { mysql_close($conn); break; } case 'mysqli': { mysqli_close($conn); break; } case 'mssql': { mssql_close($conn); break; } case 'sqlsrv': { sqlsrv_close($conn); break; } } } static function db_num_rows($result) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); $return = null; switch ($db_dialect) { case 'mysql': { $return = mysql_num_rows($result); break; } case 'mysqli': { $return = mysqli_num_rows($result); break; } case 'mssql': { $return = mssql_num_rows($result); break; } case 'sqlsrv': { $return = sqlsrv_num_rows($result); break; } } return $return; } static function db_execute($query, $conn) { $db_dialect = SysProperties::getPropertyValue('bancodados.drive'); $return = null; switch ($db_dialect) { case 'mysql': { $return = mysql_query($query, $conn); if ($return === FALSE) { Logger::logerror(mysql_error()); return FALSE; } break; } case 'mysqli': { $return = mysqli_query($conn, $query); if ($return === FALSE) { Logger::logerror(mysqli_error($return)); return FALSE; } break; } case 'mssql': { $return = mssql_execute($query, $conn); if ($return === FALSE) { Logger::logerror(mssql_get_last_message()); return FALSE; } break; } case 'sqlsrv': { $stmt = sqlsrv_prepare($conn, $query); if ($stmt === FALSE) { $sql_errors = sqlsrv_errors(); Logger::logerror(print_r($sql_errors, TRUE)); return FALSE; } $return = sqlsrv_execute($stmt); if ($return === FALSE) { $sql_errors = sqlsrv_errors(); Logger::logerror(print_r($sql_errors, TRUE)); return FALSE; } break; } } return $return; } } ?> <file_sep><?php class FileIO { static function DownloadImage($file) { $pathinfo = pathinfo($file); $fileOut = "tmp/" . $pathinfo["basename"]; unset($ch); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$file); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $data = curl_exec($ch); $cURL_Error = curl_error($ch); $cURL_ErrorN = curl_errno($ch); $cURL_Status_Response = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); unset($ch); if ($cURL_ErrorN > 0) { $errmsg = "HTTP response error ($cURL_Status_Response) for url($url) para o metodo POST em adicionar imagem , see the http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.\n"; $errmsg .= $cURL_Error . "\n"; $errmsg .= "Body: \n" . var_dump($file) . "\n"; Logger::logerror($errmsg); return FALSE; } if ($data) { $fh = fopen($fileOut,'w'); fwrite($fh,$data); fclose($fh); } else { $fileOut = FALSE; } return realpath($fileOut); } } ?><file_sep><?php class Logger { protected static $mail = "Email automatico enviado pelo sistema.\n\n Mensagem:\n %s.\n\nFavor não responder esse email"; public static function logerror($message) { Logger::FileTrashHolder("error.txt"); $level = SysProperties::getPropertyValue("logger.level"); $sendmail = SysProperties::getPropertyValue("logger.sendmail"); if (((int)$level) <= 3) { $errorheader = date("Y-m-d - H:i:s.u") . " - [ERROR ] - " . $message . PHP_EOL; error_log($errorheader, 3, "error.txt"); $to = SysProperties::getPropertyValue("logger.mailto"); if ($sendmail) { Logger::SendMail($message); } } } public static function loginfo($message) { Logger::FileTrashHolder("info.txt"); $level = SysProperties::getPropertyValue("logger.level"); $sendmail = SysProperties::getPropertyValue("logger.sendmail"); if (((int)$level) <= 1) { $errorheader = date("Y-m-d - H:i:s.u") . " - [INFO ] - " . $message . PHP_EOL; error_log($errorheader, 3, "info.txt"); } } public static function logwarn($message) { Logger::FileTrashHolder("error.txt"); $level = SysProperties::getPropertyValue("logger.level"); $sendmail = SysProperties::getPropertyValue("logger.sendmail"); if (((int)$level) <= 2) { $errorheader = date("Y-m-d - H:i:s.u") . " - [WARNING] - " . $message . PHP_EOL; error_log($errorheader, 3, "error.txt"); if ($sendmail) { Logger::SendMail($message); } } } public static function SendMail($message) { $logfile = "error.txt"; $errorheader = date("Y-m-d - H:i:s.u") . " - [INFO ] - " . $message . "\n"; $phpMailer = new PHPMailer(); $phpMailer->IsSMTP(); $phpMailer->Host = SysProperties::getPropertyValue("mail.host"); $phpMailer->Port = SysProperties::getPropertyValue("mail.port"); $phpMailer->SMTPAuth = true; $phpMailer->Username = SysProperties::getPropertyValue("mail.usuario"); $phpMailer->Password = SysProperties::<PASSWORD>("<PASSWORD>"); $phpMailer->SetFrom(SysProperties::getPropertyValue("mail.from")); $phpMailer->FromName = SysProperties::getPropertyValue("mail.from"); $mailTos = SysProperties::getPropertyValue("logger.mailto"); $mailTos = explode(",", $mailTos); for ($i=0; $i<count($mailTos); $i++) { $phpMailer->AddAddress($mailTos[$i], $mailTos[$i]); } $phpMailer->Subject = "Mesnagem do Sistema de Integra��o Quabarto"; $phpMailer->AltBody = sprintf(Logger::$mail , $message); $phpMailer->IsHTML(false); $phpMailer->Body = sprintf(Logger::$mail , $message); if(!$phpMailer->Send()) { error_log($errorheader, 3, $logfile); } } public static function FileTrashHolder($logfile) { if (file_exists($logfile)) { if (filesize($logfile) > 1048576) { copy($logfile, $logfile . "." . date("YmD_His") . ".bkp"); unlink($logfile); } } } } ?><file_sep><?php class xmlLoad { public $data; public function loadXML($urladdress) { libxml_use_internal_errors(true); $data = simplexml_load_file($urladdress); if (!$data) { $errors = libxml_get_errors(); foreach ($errors as $error) { Logger::logerror((string)$error->message); } libxml_clear_errors(); } return $data; } } ?><file_sep><?php mb_internal_encoding("ISO-8859-1"); require_once 'core/SysProperties.php'; require_once 'PHPMailer/class.smtp.php'; require_once 'PHPMailer/class.phpmailer.php'; require_once 'core/Logger.php'; require_once 'core/SessionCtrl.php'; require_once 'core/FileIO.php'; require_once 'core/xmlLoad.php'; require_once 'core/DBImpl.php'; require_once 'core/BancoDadosFactory.php'; require_once 'core/HTTPRequest.php'; SessionCtlr::StartLongSession(); echo "<pre>".PHP_EOL; $xmlload = new xmlLoad(); $arquivo = "./Carros-Na-Web.xml";# (string)$_POST['arquivo']; Logger::loginfo("lendo XML: $arquivo"); $xmldata = $xmlload->loadXML($arquivo); Logger::loginfo("Total de registro processados para o arquivo xml: ". count($xmldata)); $sys = new SysProperties(); $dbcon = array( "host" => (string)$sys->getPropertyValue("bancodados.servidor"), "usr" => (string)$sys->getPropertyValue("bancodados.usuario"), "pwd" => (string)$sys->getPropertyValue("<PASSWORD>"), "database" => (string)$sys->getPropertyValue("bancodados.basedados") ); $db = new DBImpl(); $conn = $db->db_connect($dbcon["host"], $dbcon["usr"], $dbcon["pwd"], $dbcon["database"]); if (!is_null($xmldata)) { $linha = 1; foreach ($xmldata as $noticia) { $data_tempo = new DateTime(); $data_tempo = $data_tempo->createFromFormat("d/m/Y", substr((string)$noticia->Data, 0, 10)); $sql = "exec [dbo].[InsereNoticia] " . "'".mb_convert_encoding((string)$noticia->Page_Title, "ISO-8859-1", "auto")."'," . "null," . "'".(string)$noticia->Imagem1."',". "'".(string)$noticia->Imagem2."',". "'".(string)$noticia->Imagem3."'," . "'".(string)$noticia->Imagem4."'," . "'".mb_convert_encoding((string)$noticia->NoticiaCompleta,"ISO-8859-1", "auto")."',". "0,". "'".$data_tempo->format('Y-m-d')."',". "'".(string)$noticia->Page_URL."',". "null," . "null"; $db->db_execute($sql, $conn); Logger::loginfo("registro (".$linha.") processado(".mb_convert_encoding((string)$noticia->Page_Title, "ISO-8859-1", "auto").")"); echo "registro (".$linha.") processado(".mb_convert_encoding((string)$noticia->Page_Title, "ISO-8859-1", "auto").")"; $linha++; } } $db->db_close($conn); echo "</pre>".PHP_EOL; exit(0); <file_sep><?php class HTTPRequest { public static function PostData($page, $postData) { $domain = $_SERVER['HTTP_HOST']; $prefix = 'http://'; #array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://'; $context = $_SERVER["REQUEST_URI"]; if (count(explode("/", $context)) > 1) { $contexts = explode("/", $context); $context = "/$contexts[1]/"; } else { $context = "/"; } $url = $prefix.$domain.$context.$page; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($curl) or Logger::logerror(curl_error($curl)) or Logger::logerror(curl_error($curl)); curl_close($curl); return $result; } public static function PostDataAssync($page, $postData) { $domain = $_SERVER['HTTP_HOST']; $prefix = 'http://'; #array_key_exists('HTTPS', $_SERVER) ? 'https://' : 'http://'; $context = $_SERVER["REQUEST_URI"]; if (count(explode("/", $context)) > 1) { $contexts = explode("/", $context); $context = "/$contexts[1]/"; } else { $context = "/"; } $url = $prefix.$domain.$context.$page; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_FRESH_CONNECT, TRUE); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($curl, CURLOPT_TIMEOUT, 1 ); $result = curl_exec($curl); curl_close($curl); return TRUE; } } ?><file_sep><?php class SysProperties { public static function getPropertyValue($propertyname) { $fileini = dirname($_SERVER['SCRIPT_FILENAME']) . "/sys.properties"; $inifile = parse_ini_file($fileini, FALSE); return $inifile[$propertyname]; } } ?> <file_sep><?php $string = base64_encode("<EMAIL>:Mccnmdsc01"); echo $string; ?>
00b6da5bc7a7293fbfb56fbaed8e642750ece452
[ "Markdown", "PHP", "INI" ]
13
PHP
mccaetano/CarregaNoticias
fb53afcc25b878e5246af2bb54113fdfb03fc7b2
840533d50d9b1aeb9284d417c7ee333b4ffc76fe
refs/heads/master
<repo_name>ankitlathia/COMP-6411<file_sep>/Assignment1/KruskalC/kruskalMST.c /** * *@author <NAME> ID : 27378327 * */ //Minimum Spanning Tree using Kruskal's Algorithm #include<stdio.h> #include<curses.h> #include<stdlib.h> #include<time.h> int a,b,i,j,k,u,v; int nodes,counter=1; int minVal; int minimumCost = 0; int adjacencyMatrix[10001][10001]; int weightedMatrix[10001]; FILE *input,*output; int findSet(int); int unionSet(int,int); int main() { clock_t startTime = clock(); printf("\nKruskal's algorithm\n"); printf("\nEnter the no. of Nodes:"); scanf("%d",&nodes); switch(nodes) { case 10: input=fopen("Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_10.txt","r"); output=fopen("Result_Graph_G_N_10.txt","w"); break; case 20: input=fopen("Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_20.txt","r"); output=fopen("Result_Graph_G_N_20.txt","w"); break; case 50: input=fopen("Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_50.txt","r"); output=fopen("Result_Graph_G_N_50.txt","w"); break; case 100: input=fopen("Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_100.txt","r"); output=fopen("Result_Graph_G_N_100.txt","w"); break; case 1000: input=fopen("Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_1000.txt","r"); output=fopen("Result_Graph_G_N_1000.txt","w"); break; case 10000: input=fopen("Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_10000.txt","r"); output=fopen("Result_Graph_G_N_10000.txt","w"); break; default: break; } for(i=1;i<=nodes;i++) { printf("\n"); for(j=1;j<=nodes;j++) { fscanf(input,"%d",&adjacencyMatrix[i][j]); printf("%d " ,adjacencyMatrix[i][j]); if(adjacencyMatrix[i][j]==0) adjacencyMatrix[i][j]=999; } } printf("\n"); fprintf(output, "Total number of nodes = %d\n", nodes); fprintf(output, "Total number of edges in the minimum spanning three = %d\n", nodes-1); while(counter < nodes) { for(i=1,minVal=999;i<=nodes;i++) { for(j=1;j <= nodes;j++) { if(adjacencyMatrix[i][j] < minVal) { minVal = adjacencyMatrix[i][j]; a=u=i; b=v=j; } } } u=findSet(u); v=findSet(v); if(unionSet(u,v)) { printf("%d edge (%d,%d) =%d\n",counter++,a,b,minVal); fprintf(output,"(%d,%d) edge cost =%d\n",a,b,minVal); minimumCost += minVal; } adjacencyMatrix[a][b]=adjacencyMatrix[b][a]=999; } fprintf(output,"Total cost of minimum spanning three is = %d\n",minimumCost); clock_t endTime = clock(); double totalTime = (double)(endTime - startTime) / CLOCKS_PER_SEC; fprintf(output,"Total Time required to compute = %f %s\n",totalTime, "Seconds"); fprintf(output ,"Memory usage in bytes = %ld \n", sizeof(adjacencyMatrix)); fprintf(output ,"Memory usage in megabytes = %ld ", (sizeof(adjacencyMatrix) / (1024 * 1024))); fclose(output); getch(); return(0); } int findSet(int i) { while(weightedMatrix[i]) i = weightedMatrix[i]; return i; } int unionSet(int i,int j) { if(i!=j) { weightedMatrix[j] = i; return 1; } return 0; }<file_sep>/Assignment1/spanningTreePHP.php <?php // the graph // $G = array( // 0 => array( 0, 4, 0, 0, 0, 0, 0, 0, 8), // 1 => array( 4, 0, 8, 0, 0, 0, 0, 0, 11), // 2 => array( 0, 8, 0, 7, 0, 4, 2, 0, 0), // 3 => array( 0, 0, 7, 0, 9, 14, 0, 0, 0), // 4 => array( 0, 0, 0, 9, 0, 10, 0, 0, 0), // 5 => array( 0, 0, 4, 14, 10, 0, 0, 2, 0), // 6 => array( 0, 0, 2, 0, 0, 0, 0, 6, 7), // 7 => array( 0, 0, 0, 0, 0, 2, 6, 0, 1), // 8 => array( 8, 11, 0, 0, 0, 0, 7, 1, 0), // ); $G = file('Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_10.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); function Kruskal(&$G) { $len = count($G); // 1. Make T the empty tree (we'll modify the array G to keep only MST $T = array(); // 2. Make a single node trees (sets) out of each vertex $S = array(); foreach (array_keys($G) as $k) { $S[$k] = array($k); } // 3. Sort the edges $weights = array(); for ($i = 0; $i < $len; $i++) { for ($j = 0; $j < $i; $j++) { if (!$G[$i][$j]) continue; $weights[$i . ' ' . $j] = $G[$i][$j]; } } asort($weights); foreach ($weights as $k => $w) { list($i, $j) = explode(' ', $k); $iSet = find_set($S, $i); $jSet = find_set($S, $j); if ($iSet != $jSet) { $T[] = "Edge: ($i, $j)"; union_sets($S, $iSet, $jSet); } } return $T; } function find_set(&$set, $index) { foreach ($set as $k => $v) { if (in_array($index, $v)) { return $k; } } return false; } function union_sets(&$set, $i, $j) { $a = $set[$i]; $b = $set[$j]; unset($set[$i], $set[$j]); $set[] = array_merge($a, $b); } $mst = Kruskal($G); //Edge: (8, 7) //Edge: (6, 2) //Edge: (7, 5) //Edge: (1, 0) //Edge: (5, 2) //Edge: (3, 2) //Edge: (2, 1) //Edge: (4, 3) foreach ($mst as $v) { //echo $v . PHP_EOL; file_put_contents('output.txt', $v . "\n", FILE_APPEND); } ?> <file_sep>/Assignment3/Ankit_Lathia_27378327_Assignment3/C/SemaphoresConcurrency.c /** * *@author <NAME> ID : 27378327 * */ #include <semaphore.h> #include <pthread.h> #include <unistd.h> #include <stdio.h> #include <curses.h> #include <stdlib.h> sem_t *s; int i, j, diceValue, sharedValue = 0; char SEM_NAME[]= "dice"; int rollDice(); void * concurrentReadWrite(void * arg) { sem_wait(s); for (j = 0; j < 4; j++) { diceValue = rollDice(); if (diceValue == 1) { printf("Thread %lu now is ready to Read the shared location \n",(unsigned long)pthread_self()); printf("Thread %lu now has finished reading the shared Location %d \n",(unsigned long)pthread_self(),sharedValue); } else { printf("Thread %lu now is ready to Write the shared location \n",(unsigned long)pthread_self()); sharedValue = sharedValue + 1; printf("Thread %lu now has finished Writing the shared Location %d \n",(unsigned long)pthread_self(),sharedValue); } } return 0; } int rollDice() { if (((rand() % 6) + 1) % 2 == 0) { return 1; } else { return 0; } } int main() { //named semaphore for osx and linux s = sem_open(SEM_NAME,O_CREAT,0777,1); if(s == SEM_FAILED) { perror("unable to create semaphore"); sem_unlink(SEM_NAME); exit(-1); } pthread_t * thread = malloc(sizeof(pthread_t)*7); pthread_t c; for(i = 0; i < 7; i++) { pthread_create(&thread[i], NULL, concurrentReadWrite, NULL); pthread_detach(*thread); } /* run each thread four times, releases lock and exit */ for (i = 0; i < (7 * 4); ++i) { sem_post(s); sleep(1); } //close (destroy semaphore) sem_close(s); //unlink name from semaphore sem_unlink(SEM_NAME); return 0; getch(); } <file_sep>/Assignment1/KruskalMST/src/KruskalMST.java import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.text.NumberFormat; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class KruskalMST { private List<Edge> edgesGraph; private int totalNumberOfVertices; public static final int MAXIMUM_VALUE = 10000; private int visitedNodes[]; private int MinSpanningTree[][]; public KruskalMST(int numberOfVerticesInGraph) { this.totalNumberOfVertices = numberOfVerticesInGraph; edgesGraph = new LinkedList<Edge>(); visitedNodes = new int[this.totalNumberOfVertices + 1]; MinSpanningTree = new int[numberOfVerticesInGraph + 1][numberOfVerticesInGraph + 1]; } public void kruskalCompute(int adjacencyMatrix[][], PrintWriter pWriter) { boolean isFinished = false; for (int source = 1; source <= totalNumberOfVertices; source++) { for (int destination = 1; destination <= totalNumberOfVertices; destination++) { if (adjacencyMatrix[source][destination] != MAXIMUM_VALUE && source != destination) { Edge edge = new Edge(); edge.sourceVertex = source; edge.destinationVertex = destination; edge.weights = adjacencyMatrix[source][destination]; adjacencyMatrix[destination][source] = MAXIMUM_VALUE; edgesGraph.add(edge); } } } Collections.sort(edgesGraph, new EdgeComparision()); CheckCycleInTree checkCycle = new CheckCycleInTree(); for (Edge edge : edgesGraph) { MinSpanningTree[edge.sourceVertex][edge.destinationVertex] = edge.weights; MinSpanningTree[edge.destinationVertex][edge.sourceVertex] = edge.weights; if (checkCycle.checkCycle(MinSpanningTree, edge.sourceVertex)) { MinSpanningTree[edge.sourceVertex][edge.destinationVertex] = 0; MinSpanningTree[edge.destinationVertex][edge.sourceVertex] = 0; edge.weights = -1; continue; } visitedNodes[edge.sourceVertex] = 1; visitedNodes[edge.destinationVertex] = 1; for (int i = 0; i < visitedNodes.length; i++) { if (visitedNodes[i] == 0) { isFinished = false; break; } else { isFinished = true; } } if (isFinished) break; } int count = 0; int tot = 0; for (int i = 1; i <= totalNumberOfVertices; i++) { for (int j = i; j <= totalNumberOfVertices; j++) { if (MinSpanningTree[i][j] != 0) { count ++; } } } pWriter.println("Total number of edges in the minimum spanning three = "+ count); pWriter.println("List of edges & their costs:"); for (int i = 1; i <= totalNumberOfVertices; i++) { for (int j = i; j <= totalNumberOfVertices; j++) { if (MinSpanningTree[i][j] != 0) { pWriter.println("("+i+","+j+") edge cost : "+MinSpanningTree[i][j]); tot += MinSpanningTree[i][j]; } } } pWriter.print("Total cost of minimum spanning three is = Sum of ("); for (int i = 1; i <= totalNumberOfVertices; i++) { for (int j = i; j <= totalNumberOfVertices; j++) { if (MinSpanningTree[i][j] != 0) { pWriter.print(MinSpanningTree[i][j]+"+"); } } } pWriter.println(") = "+tot); } @SuppressWarnings("resource") public static void main(String... arg) { int adjacencyMatrixFile[][]; int number_of_vertices_in_graph; Scanner scan = new Scanner(System.in); System.out.println("Enter the number of nodes (10, 20, 50, 100, 1000, 10000): "); number_of_vertices_in_graph = scan.nextInt(); double startTime = System.currentTimeMillis(); adjacencyMatrixFile = new int[number_of_vertices_in_graph + 1][number_of_vertices_in_graph + 1]; File file = null; switch(number_of_vertices_in_graph) { case 10: file = new File("/Users/ankit/Desktop/6411Assg1/Assignment1/KruskalMST/src/Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_10.txt"); break; case 20: file = new File("/Users/ankit/Desktop/6411Assg1/Assignment1/KruskalMST/src/Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_20.txt"); break; case 50: file = new File("/Users/ankit/Desktop/6411Assg1/Assignment1/KruskalMST/src/Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_50.txt"); break; case 100: file = new File("/Users/ankit/Desktop/6411Assg1/Assignment1/KruskalMST/src/Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_100.txt"); break; case 1000: file = new File("/Users/ankit/Desktop/6411Assg1/Assignment1/KruskalMST/src/Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_1000.txt"); break; case 10000: file = new File("/Users/ankit/Desktop/6411Assg1/Assignment1/KruskalMST/src/Data_for_assignment_no_1/AdjacencyMatrix_of_Graph_G_N_10000.txt"); break; default: break; } PrintWriter pWriter = null; try { switch(number_of_vertices_in_graph) { case 10: pWriter = new PrintWriter("Result_of_Graph_G_N_10.txt", "UTF-8"); break; case 20: pWriter = new PrintWriter("Result_of_Graph_G_N_20.txt", "UTF-8"); break; case 50: pWriter = new PrintWriter("Result_of_Graph_G_N_50.txt", "UTF-8"); break; case 100: pWriter = new PrintWriter("Result_of_Graph_G_N_100.txt", "UTF-8"); break; case 1000: pWriter = new PrintWriter("Result_of_Graph_G_N_1000.txt", "UTF-8"); break; case 10000: pWriter = new PrintWriter("Result_of_Graph_G_N_10000.txt", "UTF-8"); break; default: break; } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Scanner scanner = null; int size = number_of_vertices_in_graph; int xcord = 0; int ycord = 0; try { scanner = new Scanner(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 1; i <= number_of_vertices_in_graph; i++) { for (int j = 1; j <= number_of_vertices_in_graph; j++) { adjacencyMatrixFile[i][j] = scanner.nextInt(); if (i == j) { adjacencyMatrixFile[i][j] = 0; continue; } if (adjacencyMatrixFile[i][j] == 0) { adjacencyMatrixFile[i][j] = MAXIMUM_VALUE; } } } pWriter.println("Total number of nodes = "+number_of_vertices_in_graph); KruskalMST kruskal = new KruskalMST(number_of_vertices_in_graph); kruskal.kruskalCompute(adjacencyMatrixFile, pWriter); scanner.close(); Runtime runTime = Runtime.getRuntime(); runTime.gc(); double memoryRequirementForCode = runTime.totalMemory() - runTime.freeMemory(); pWriter.println("Memory usage in bytes: " + memoryRequirementForCode); pWriter.println("Memory usage in megabytes: " + (float)(memoryRequirementForCode / (1024 * 1024))); double endTime = System.currentTimeMillis(); pWriter.println("Total Time required to compute = "+(double)( (endTime - startTime) / 1000)+" Seconds"); pWriter.close(); } } class Edge { int sourceVertex; int destinationVertex; int weights; } class EdgeComparision implements Comparator<Edge> { @Override public int compare(Edge edge1, Edge edge2) { if (edge1.weights < edge2.weights) { return -1; } if (edge1.weights > edge2.weights) { return 1; } return 0; } } class CheckCycleInTree { private Stack<Integer> stackTree; private int adjacencyMatrixTree[][]; public CheckCycleInTree() { stackTree = new Stack<Integer>(); } public boolean checkCycle(int adjacent_Matrix[][], int sourceVertex) { boolean isCyclePresent = false; int numberOfNodes = adjacent_Matrix[sourceVertex].length - 1; adjacencyMatrixTree = new int[numberOfNodes + 1][numberOfNodes + 1]; for (int sourcevertices = 1; sourcevertices <= numberOfNodes; sourcevertices++) { for (int destinationVertex = 1; destinationVertex <= numberOfNodes; destinationVertex++) { adjacencyMatrixTree[sourcevertices][destinationVertex] = adjacent_Matrix[sourcevertices][destinationVertex]; } } int visitedNodes[] = new int[numberOfNodes + 1]; int element = sourceVertex; int i = sourceVertex; visitedNodes[sourceVertex] = 1; stackTree.push(sourceVertex); while (!stackTree.isEmpty()) { element = stackTree.peek(); i = element; while (i <= numberOfNodes) { if (adjacencyMatrixTree[element][i] >= 1 && visitedNodes[i] == 1) { if (stackTree.contains(i)) { isCyclePresent = true; return isCyclePresent; } } if (adjacencyMatrixTree[element][i] >= 1 && visitedNodes[i] == 0) { stackTree.push(i); visitedNodes[i] = 1; adjacencyMatrixTree[element][i] = 0;// mark as labelled; adjacencyMatrixTree[i][element] = 0; element = i; i = 1; continue; } i++; } stackTree.pop(); } return isCyclePresent; } }<file_sep>/Assignment2/Ankit_Lathia_27378327_Assignment2/php/spanningTree.php <?php session_start(); class Graph { //ini_set('display_errors',1); //public $start = microtime(true); public $len = 0; public $nodeCounter = 0; public $edgeCounter = 0; public $totalWeight = 0; public function __construct(){ ini_set('memory_limit', '2048M'); ini_set('max_execution_time', 300); ini_set('xdebug.max_nesting_level', 100000); $res = ""; $step = $_GET['step']; global $foutput; /** AdAdjacencyMatrix Data **/ $adj_info = fopen($_SESSION['matricsgraph'],'r'); $in = 0; while ($line = fgets($adj_info)) { $in++; if($in >= 10001) { break; } $G[] = explode(" ",trim($line)); } fclose($adj_info); $this->graph = $G; $this->len = count($this->graph); $foutput = fopen('output/AdjacencyMatrix_of_Graph_G_'. $this->len .'.txt','w'); $this->output = $foutput; $this->output_info = ""; $start_node = 0; $this->Kruskal($G); $final_output = $this->output_info; fwrite($foutput,"Total number of nodes = ". $this->len . "\n"); fwrite($foutput,"Total number of edges in Minimum spanning tree = ". $this->edgeCounter. "\n"); fwrite($foutput,"List of edges and their cost : \n"); foreach($final_output as $key=>$fot) { if($step != "") { //echo "for".$fot. "\n"; if($key < $step) { $this->algo_output[] = $fot; fwrite($foutput,$fot."\n"); // echo $fot."\n"; } } else { $this->algo_output[] = $fot; fwrite($foutput,$fot."\n"); //echo $fot."\n"; } } fwrite($foutput,"Total cost of minimum spanning three is = ". $this->totalWeight ." \n"); //$time_elapsed_secs = microtime(true) - $this->start; // fwrite($foutput,"Time required for execution = ". $this->time_elapsed_secs ." \n"); fclose($foutput); } function Kruskal(&$G) { $len = count($G); $T = array(); // Makeing single node trees (sets) out of each vertex $S = array(); foreach (array_keys($G) as $k) { $S[$k] = array($k); } //Sorting the edges $weights = array(); for ($i = 0; $i < $len; $i++) { for ($j = 0; $j < $i; $j++) { if (!$G[$i][$j]) continue; $weights[$i . ' ' . $j] = $G[$i][$j]; } } asort($weights); foreach ($weights as $k => $w) { list($i, $j) = explode(' ', $k); $iSet = find_set($S, $i); $jSet = find_set($S, $j); if ($iSet != $jSet) { $this->output_info[] = "Edge: ($j, $i) : $w"; $this->edgeCounter++; $this->totalWeight = $this->totalWeight + $w; union_sets($S, $iSet, $jSet); } } } } function find_set(&$set, $index) { foreach ($set as $k => $v) { if (in_array($index, $v)) { return $k; } } return false; } function union_sets(&$set, $i, $j) { $a = $set[$i]; $b = $set[$j]; unset($set[$i], $set[$j]); $set[] = array_merge($a, $b); } if(isset($_POST)) { $error_message = ""; $uploaddir = ''; if(isset($_FILES['matricsgraph']['name']) ) { if($_FILES['matricsgraph']['name'] != "") { $matricsgraph_file = $uploaddir . basename($_FILES['matricsgraph']['name']); $step_by = ""; if(isset($_POST['step_by'])) { $step_by = $_POST['step_by']; $argument = "?algo=kruskal&step=1&start=1"; header( 'Location: '.$argument ) ; } else { $argument = "?algo=kruskal&step=&start=1"; header( 'Location: '.$argument ) ; } $matricsgraph = false; if (move_uploaded_file($_FILES['matricsgraph']['tmp_name'], $matricsgraph_file)) { $matricsgraph = true; } else{ $matricsgraph = false; } if($matricsgraph) { $_SESSION = ""; $_SESSION['step_by'] = $step_by; $_SESSION['matricsgraph'] = $_FILES['matricsgraph']['name']; } else { $error_message = "File cannot be upload !"; session_destroy(); } } else { $error_message = "Please Select File"; } } } if(isset($_GET['algo']) && $_GET['algo'] != "") { $algo_output = new Graph(); $output_info = $algo_output->algo_output; $len = $algo_output->len; $edgeCounter = $algo_output->edgeCounter; $totalWeight = $algo_output->totalWeight; } ?> <html> <head> <title>Kruskal MST</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Josefin+Slab" /> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified JavaScript--> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script> </head> <style> .btn { background-color: #fff; border: 2px solid #000; color: #000; } .btn:hover { background-color: #000 !important; color: #fff; } .btn:focus { background-color: #000 !important; color: #fff; } button:focus { background-color: #000 !important; color: #fff; } .container { padding-top: 5%; } .navbar-header { font-size: 30px; font-family: "Josefin Slab"; } .navbar-right { font-family: "Josefin Slab"; } p label{ font-size: 1.5rem !important; } .switch label{ font-size: 1.5rem !important; } .labelme { font-size: 30px !important; font-family: "Josefin Slab" !important; color: #5F5E5E; margin-bottom: 5px; display: table; } .output_wrapper { font-family: "Josefin Slab" !important; font-size: 16px; float: left; text-align: left; } .nav li { padding-right: 10px; } .page_title { background-color: #26A69A; color: #FFF; text-align: center; margin-bottom: 0; padding: 8px; } .sendbtn { float: right; margin-right: 20px; } .ngfile { width: 60% !important; margin-left: 10px !important; } .mgfile { width: 100% !important; } body { background: #E5E5E5; font-family: "Josefin Slab"; } .card_title { text-align: center; font-size: 24px; } .btn i { font-size: 12px; } .error { color: #E60000; font-size: 14px; } .input_wrapper { min-height: 550px; } .ntxtbtn { float: right; font-size: 14px; } </style> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> Minimum Spanning Tree Kruskal PHP </div> <ul class="nav navbar-nav navbar-right"> <li> <NAME></li> <li> 27378327</li> </ul> </div> </nav> <div class="container"> <div class="row"> <div class="col s12 m6 content_wrapper"> <div class="card"> <div class="input_wrapper card-content"> <form action="" method="post" enctype="multipart/form-data"> <div class="card_title">Input</div> <?php if(isset($error_message) && $error_message != "") { echo "<div class='error'>".$error_message."</div>"; } if(isset($_GET['step']) && $_GET['step']!="") { $stepno = $_GET['step']; }else{$stepno = 1;} if(isset($_GET['start']) && $_GET['start']!="") { if($_GET['start'] == 1) { $step_on = ""; }else { $step_on = "checked"; } } ?> <div class="file-field input-field row"> <div class="btn"> <span>Matrics File</span> <input type="file" name="matricsgraph" /> </div> <input class="file-path validate mgfile" type="text" /> </div> <div class="row"> <label class="labelme">Algorithm used</label> <p> <label for="KMST">Kruskal Minimum Spanning Tree</label> </p> </div> <div class="row"> <label class="labelme">Run by Step</label> <div class="switch"> <label> No <input type="checkbox" name="step_by" <?php echo $step_on; ?>> <span class="lever"></span> Yes </label> </div> </div> <div class="row"> <p> <br /> <br /> <button class="btn waves-effect waves-light sendbtn" type="submit" name="action">Run <i class="material-icons right-align Tiny">send</i> </button> </p> </div> </form> </div> </div> </div> <div class="col s12 m6 card_wrapper"> <div class="card"> <div class="input_wrapper card-content"> <div class="card_title"> <div class="card_content"> Output <?php if(isset($_SESSION['step_by'])) { $step = $_GET['step']; $start_node = $_GET['start']; if($_SESSION['step_by'] == "on" && ($len > ($step+1))) { $nextargument = "?algo=kruskal&step=".($step+1)."&start=".$start_node; ?> <a href="<?php echo $nextargument; ?>" class="btn ntxtbtn" >Next &raquo;</a> <?php } if($_SESSION['step_by'] == "on" && ($step > 1)) { $preargument = "?algo=kruskal&step=".($step-1)."&start=".$start_node; ?> <a href="<?php echo $preargument; ?>" class="btn ntxtbtn" >&laquo;Pre </a> <?php } } ?> </div> <div class="row"> <div class="output_wrapper"> <?php if(isset($output_info) && is_array($output_info)) { echo "Total number of nodes = ". ($edgeCounter+ 1). "<br>"; echo "Total number of edges in Minimum spanning tree = ". $edgeCounter. "<br>"; echo "List of edges and their cost : <br>"; foreach($output_info as $line) { echo "<span>".$line."</span><br>"; } echo "Total cost of minimum spanning three is = ". $totalWeight ." <br>"; } ?> </div> </div> </div> </div> </div> </div> </div> </div> <script> jQuery(document).ready(function() { jQuery('select').material_select(); }); </script> </body> </html>
b72abba6b54a46c8afc619b910f42372b0094dfa
[ "Java", "C", "PHP" ]
5
C
ankitlathia/COMP-6411
57f6316bbb720a3e19b66ecc694d1922fc2b6301
e63bdc65c5b633d047bfc2de18c3d2e4aad934aa
refs/heads/master
<repo_name>starklm1402/FirstCalculator<file_sep>/calculator.java import java.awt.GridLayout; import java.lang.Math.*; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import java.awt.*; import javax.swing.*; public class calculator { int change; JFrame frame; JButton o1,o2,o3,o4,o5,o6,o7,o8,o9,o10,o11,o12,eqb; JButton b0,b1,b2,b3,b4,b5,b6,b7,b8,b9; JPanel panel1, panel11, panel12,panel2,panel3,panel4; String s,op; JTextArea ta; JRadioButton jr1, jr2; ButtonGroup group; static double a, b ,calc=0, result,rad; static int operator; public static void main(String[] args) { calculator play = new calculator(); play.go(); } public void go(){ frame= new JFrame(); panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); panel11 = new JPanel(); panel12 = new JPanel(); frame.setResizable(false); frame.setTitle("My First Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); ta = new JTextArea(2,20); ta.setEditable(false); panel11.add(ta); jr1 = new JRadioButton("Degree"); jr2 = new JRadioButton("Radian"); group = new ButtonGroup(); group.add(jr1); group.add(jr2); jr1.setSelected(true); jr1.setActionCommand("Degree"); jr2.setActionCommand("Radian"); jr1.addActionListener(new clicked()); jr2.addActionListener(new clicked()); panel12.add(jr1); panel12.add(jr2); panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS)); panel1.add(panel11); panel1.add(panel12); b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); b0 = new JButton("0"); o4 = new JButton("clear"); o5 = new JButton("/"); o6 = new JButton("sin"); o7 = new JButton("cos"); o8 = new JButton("tan"); o9 = new JButton("log"); eqb = new JButton("="); b0.addActionListener(new clicked()); b1.addActionListener(new clicked()); b2.addActionListener(new clicked()); b3.addActionListener(new clicked()); b4.addActionListener(new clicked()); b5.addActionListener(new clicked()); b6.addActionListener(new clicked()); b7.addActionListener(new clicked()); b8.addActionListener(new clicked()); b9.addActionListener(new clicked()); o4.addActionListener(new clicked()); o5.addActionListener(new clicked()); o6.addActionListener(new clicked()); o7.addActionListener(new clicked()); o8.addActionListener(new clicked()); o9.addActionListener(new clicked()); eqb.addActionListener(new clicked()); panel2.setLayout(new GridLayout(4,4)); panel2.add(o6); panel2.add(o7); panel2.add(o8); panel2.add(o9); panel2.add(b1); panel2.add(b2); panel2.add(b3); panel2.add(b4); panel2.add(b5); panel2.add(b6); panel2.add(b7); panel2.add(b8); panel2.add(b9); panel2.add(b0); panel2.add(o5); panel2.add(o4); o1 = new JButton("+"); o2 = new JButton("-"); o3 = new JButton("x"); o1.addActionListener(new clicked()); o2.addActionListener(new clicked()); o3.addActionListener(new clicked()); panel3.setLayout(new GridLayout(4,1)); panel3.add(o1); panel3.add(o2); panel3.add(o3); panel3.add(eqb); frame.getContentPane().add(BorderLayout.NORTH,panel1); frame.getContentPane().add(BorderLayout.EAST,panel3); frame.getContentPane().add(BorderLayout.CENTER, panel2); frame.setSize(300,400); frame.setVisible(true); } class clicked implements ActionListener{ public void actionPerformed(ActionEvent event) { if(event.getSource()==b1) ta.setText(ta.getText().concat("1")); if(event.getSource()==b2) ta.setText(ta.getText().concat("2")); if(event.getSource()==b3) ta.setText(ta.getText().concat("3")); if(event.getSource()==b4) ta.setText(ta.getText().concat("4")); if(event.getSource()==b5) ta.setText(ta.getText().concat("5")); if(event.getSource()==b6) ta.setText(ta.getText().concat("6")); if(event.getSource()==b7) ta.setText(ta.getText().concat("7")); if(event.getSource()==b8) ta.setText(ta.getText().concat("8")); if(event.getSource()==b9) ta.setText(ta.getText().concat("9")); if(event.getSource()==b0) ta.setText(ta.getText().concat("0")); if(event.getSource()==o1) { a=Double.parseDouble(ta.getText()); operator = 1; ta.setText(""); } if(event.getSource()==o2) { a=Double.parseDouble(ta.getText()); operator = 2; ta.setText(""); } if(event.getSource()==o3) { a=Double.parseDouble(ta.getText()); operator = 3; ta.setText(""); } if(event.getSource()==o4) { ta.setText(""); a=0; b=0; change=0; rad=0; } if(event.getSource()==o5) { a=Double.parseDouble(ta.getText()); operator = 4; ta.setText(""); } if(event.getActionCommand()=="DEGREE"){ta.setText("Degree selected hai");} if(event.getSource()==o6) { if(!ta.getText().isEmpty()) { ta.setText("Syntax Error"); } else { operator = 5; } } if(event.getSource()==o7) { if(!ta.getText().isEmpty()) { ta.setText("Syntax Error"); } else { operator = 6; } } if(event.getSource()==o8) { if(!ta.getText().isEmpty()) { ta.setText("Syntax Error"); } else { operator = 7; } } if(event.getSource()==o9) { if(!ta.getText().isEmpty()) { ta.setText("Syntax Error"); } else { operator = 8; } } if(event.getSource()==eqb){ if(ta.getText().isEmpty()) { ta.setText("Enter Value.. Try Again"); } else { b=Double.parseDouble(ta.getText()); switch(operator) { case 1: result=a+b;op=" + ";change=1; break; case 2: result=a-b;op=" - ";change=1; break; case 3: result=a*b;op=" * ";change=1; break; case 4: result=a/b;op=" / ";change=1; break; case 5: if(group.getSelection().getActionCommand()=="Degree") { rad = b*Math.PI/180; } else{rad=b;} result =Math.sin(rad);op="sin ";change=2; break; case 6: if(group.getSelection().getActionCommand()=="Degree") { rad = b*Math.PI/180; } else{rad=b;} result = Math.cos(rad);op="cos ";change=2; break; case 7: if(group.getSelection().getActionCommand()=="Degree") { rad = b*Math.PI/180; } else{rad=b;} result = Math.tan(rad);op="tan ";change=2; break; case 8: result = Math.log(b);op="log ";change=2; break; } if(change==1) {ta.setText(Double.toString(a)+op+Double.toString(b)+"\t = " +Double.toString(result));} if(change==2){ ta.setText(op+Double.toString(b)+" = " +Double.toString(result)); } } } } } }
a9c12f203893986fea45229ce5d48ebc1f83ea32
[ "Java" ]
1
Java
starklm1402/FirstCalculator
589ac45c7f7bd429de6053400ef63f5abfa52667
f65954cdadfa426fc3fa8df90cc00cdcb7044949
refs/heads/master
<repo_name>team-telnyx/erlang-dirent<file_sep>/c_src/dirent.c #include "erl_nif.h" #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/dir.h> #include <errno.h> // it might be weird, but this is how it works for now extern char* erl_errno_id(int error); static ERL_NIF_TERM am_ok; static ERL_NIF_TERM am_error; static ERL_NIF_TERM am_finished; static ERL_NIF_TERM am_not_owner; static ERL_NIF_TERM am_device; static ERL_NIF_TERM am_directory; static ERL_NIF_TERM am_other; static ERL_NIF_TERM am_regular; static ERL_NIF_TERM am_symlink; static ERL_NIF_TERM am_undefined; typedef struct { DIR *dir_stream; char *path; size_t path_length; ErlNifPid controlling_process; ErlNifMutex *controller_lock; } dir_context_t; static ErlNifResourceType* rtype_dir; static void gc_dir(ErlNifEnv *env, void* data); static int load(ErlNifEnv *env, void** priv_data, ERL_NIF_TERM load_info) { am_ok = enif_make_atom(env, "ok"); am_error = enif_make_atom(env, "error"); am_finished = enif_make_atom(env, "finished"); am_not_owner = enif_make_atom(env, "not_owner"); am_device = enif_make_atom(env, "device"); am_directory = enif_make_atom(env, "directory"); am_symlink = enif_make_atom(env, "symlink"); am_regular = enif_make_atom(env, "regular"); am_other = enif_make_atom(env, "other"); am_undefined = enif_make_atom(env, "undefined"); rtype_dir = enif_open_resource_type(env, NULL, "gc_dir", gc_dir, ERL_NIF_RT_CREATE, NULL); return 0; } static void gc_dir(ErlNifEnv *env, void* data) { dir_context_t *d = (dir_context_t*)data; free(d->path); if (d->dir_stream) closedir(d->dir_stream); (void)env; } static int process_check(ErlNifEnv *env, dir_context_t *d) { int is_controlling_process; ErlNifPid current_process; enif_self(env, &current_process); enif_mutex_lock(d->controller_lock); is_controlling_process = enif_is_identical( enif_make_pid(env, &current_process), enif_make_pid(env, &d->controlling_process)); enif_mutex_unlock(d->controller_lock); return is_controlling_process; } static ERL_NIF_TERM posix_error_to_tuple(ErlNifEnv *env, int posix_errno) { ERL_NIF_TERM error = enif_make_atom(env, erl_errno_id(posix_errno)); return enif_make_tuple2(env, am_error, error); } static int has_invalid_null_termination(const ErlNifBinary *path) { const char *null_pos, *end_pos; null_pos = memchr(path->data, '\0', path->size); end_pos = (const char*)&path->data[path->size] - 1; if (null_pos == NULL) { return 1; } /* prim_file:internal_name2native sometimes feeds us data that is "doubly" * NUL-terminated, so we'll accept any number of trailing NULs so long as * they aren't interrupted by anything else. */ while (null_pos < end_pos && (*null_pos) == '\0') { null_pos++; } return null_pos != end_pos; } static ERL_NIF_TERM open_dir(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result_term; ErlNifBinary path; dir_context_t *d; d = (dir_context_t *) enif_alloc_resource(rtype_dir, sizeof(dir_context_t)); memset(d, 0, sizeof(dir_context_t)); if (argc != 1 || !enif_inspect_binary(env, argv[0], &path)) { result_term = enif_make_badarg(env); goto err; } if (has_invalid_null_termination(&path)) { result_term = enif_make_badarg(env); goto err; } if ((d->path = malloc(path.size)) == NULL) { result_term = enif_raise_exception(env, am_error); goto err; } memcpy(d->path, path.data, path.size); d->path_length = path.size - 1; d->dir_stream = opendir(d->path); if (d->dir_stream == NULL) { result_term = posix_error_to_tuple(env, errno); goto err; } enif_self(env, &d->controlling_process); d->controller_lock = enif_mutex_create("dirent_controller_lock"); result_term = enif_make_tuple2(env, am_ok, enif_make_resource(env, d)); err: if (d) enif_release_resource(d); return result_term; } static int is_ignored_name(int name_length, const char *name) { if (name_length == 1 && name[0] == '.') { return 1; } else if(name_length == 2 && memcmp(name, "..", 2) == 0) { return 1; } return 0; } static ERL_NIF_TERM dtype2atom(unsigned char d_type) { switch (d_type) { case DT_REG: return am_regular; case DT_DIR: return am_directory; case DT_LNK: return am_symlink; case DT_BLK: case DT_CHR: return am_device; case DT_FIFO: case DT_SOCK: return am_other; } return am_undefined; } static int read_boolean(ErlNifEnv *env, ERL_NIF_TERM term, int *var) { char buf[6]; // max( len("true"), len("false")) + 1 if (!enif_get_atom(env, term, buf, sizeof(buf), ERL_NIF_LATIN1)) { return 0; } else if (strcmp(buf, "true") == 0) { *var = 1; return 1; } else if (strcmp(buf, "false") == 0) { *var = 0; return 1; } return 0; // some other atom, return error } static ERL_NIF_TERM read_dir(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { struct dirent *dir_entry; dir_context_t *d; int return_dtype = 0; if (argc != 2) { return enif_make_badarg(env); } else if (!enif_get_resource(env, argv[0], (ErlNifResourceType*)rtype_dir, (void**)&d)) { return enif_make_badarg(env); } else if (!read_boolean(env, argv[1], &return_dtype)) { return enif_make_badarg(env); } else if (!process_check(env, d)) { return enif_make_tuple2(env, am_error, am_not_owner); } while ((dir_entry = readdir(d->dir_stream)) != NULL) { int name_length = strlen(dir_entry->d_name); if (!is_ignored_name(name_length, dir_entry->d_name)) { unsigned char *name_bytes; ERL_NIF_TERM name_term; size_t fullpath_length = d->path_length + 1 + name_length; name_bytes = enif_make_new_binary(env, fullpath_length, &name_term); memcpy(name_bytes, d->path, d->path_length); name_bytes[d->path_length] = '/'; memcpy(name_bytes + d->path_length + 1, dir_entry->d_name, name_length); if (return_dtype) { return enif_make_tuple2(env, name_term, dtype2atom(dir_entry->d_type)); } else { return name_term; } } } return am_finished; } static ERL_NIF_TERM set_controller(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { dir_context_t *d; ErlNifPid new_owner; if (argc != 2) { return enif_make_badarg(env); } else if (!enif_get_resource(env, argv[0], (ErlNifResourceType*)rtype_dir, (void**)&d)) { return enif_make_badarg(env); } else if (!enif_get_local_pid(env, argv[1], &new_owner)) { return enif_make_badarg(env); } else if(!process_check(env, d)) { return enif_make_tuple2(env, am_error, am_not_owner); } enif_mutex_lock(d->controller_lock); d->controlling_process = new_owner; enif_mutex_unlock(d->controller_lock); return am_ok; } static ErlNifFunc nif_funcs[] = { {"opendir_nif", 1, open_dir}, {"readdir_nif", 2, read_dir}, {"set_controller_nif", 2, set_controller}, }; ERL_NIF_INIT(dirent, nif_funcs, load, NULL, NULL, NULL) <file_sep>/README.md # dirent - Iterative directory listing library Copyright (c) 2020 Telnyx LLC. __Version:__ 1.0.0 # dirent **dirent** is an iterative directory listing for Erlang. Erlang functions such as `filelib:fold_files/5`, `file:list_dir/1`, `c:ls/0,1`, etc return files from directories _after_ reading them from the filesystem. When you have an humongous number of files on a single folder, all these functions will block for a certain time. In these cases you may not be interested in returning the full list of files, but instead you may want to list them _iteratively_, returning each entry after the another to your process, at the moment they are taken from [_readdir_](http://man7.org/linux/man-pages/man3/readdir.3.html). ## Installation Download the sources from our [Github repository](http://github.com/team-telnyx/erlang-dirent) To build the application simply run `rebar3 compile`. Or add it to your rebar config add: ```erlang {deps, [ .... {dirent, ".*", {git, "git://github.com/team-telnyx/dirent.git", {branch, "master"}}} ]}. ``` ## Basic usage The most basic usage of `dirent` is: ``` > {ok, DirRef} = dirent:opendir("."). {ok,#Ref<0.1857889054.1430650882.66300>} > PrintDir = fun F(DirRef) -> > case dirent:readdir(DirRef) of > finished -> ok; > {error, Reason} -> {error, Reason}; > File -> io:format("~s~n", [File]), F(DirRef) > end > end. #Fun<erl_eval.31.126501267> > PrintDir(DirRef). ./LICENSE ./MAINTAINERS ./NOTICE ./README.md ./priv ./.gitignore ./c_src ./doc ./rebar.config ./src ok ``` In the example above the function `dirent:readdir/1` was used. But you can also use `dirent:readdir_type/1` and take the advantage that some well known filesystems has the capability to return the file type: ```erlang recurse_dir(Dir) -> {ok, DirRef} = dirent:opendir(Dir), list_files(DirRef). list_files(DirRef) -> case dirent:readdir_type(DirRef) of finished -> ok; {error, Reason} -> {error, Reason}; {Dir, directory} -> recurse_dir(Dir), list_files(DirRef); {File, _type} -> io:format("~s~n", [File]), list_files(DirRef) end. ``` In the example above, there is no need to make a second call to `file:read_file_info/1,2` which might add considerable overhead when you have too many files to list. If invalid unicode characters are found in the file names and the filesystem doesn't handle that correctly, they will be skipped or `{error, {no_translation, RawName}}` will be returned. That's the same behavior of Erlang's `file:list_dir/1`, and the behavior depends on the `+fn{u|a}{i|e|w}` emulator switches. For even more advanced usage, there is also `dirent:readdir_all/1` and `dirent:readdir_raw/1`. The main difference of these latter functions is regarding to invalid filenames. `dirent:readdir_all/1` will attempt to translate the filename to a charlist, but if not possible, the raw binary will be returned. `dirent:readdir_raw/1` will not even attempt to translate the filename, the raw binary representation is always returned.
d7856015903733143ed8e6359e8e45318465c4db
[ "Markdown", "C" ]
2
C
team-telnyx/erlang-dirent
a0ac780c4d2230e7ca6f169a117bad7665c36f73
3110ab74fbfa55888790883808969cdefb8bc1ca
refs/heads/master
<file_sep>all: hex hex: gcc -g -Wall -Werror -fsanitize=address -std=c11 hex.c -o hex clean: rm -rf hex <file_sep>## Project Description In this project I wrote code to solve a hexadoku puzzle, which is essentially 16x16 hexadecimal sudoku. My code currently only works for hexadoku puzzles that will always have a cell it can fill with 100% certainty. ### To Run In the project's directory, run these two commands in order: >make<br> ./hex \<hexadoku board filename\>.txt An example of a hexadoku board can be seen below, where -'s represent empty spaces in the board. E - 5 2 6 1 A B 3 7 D F - C 0 -<br> F 4 0 C 9 7 D 3 2 1 B 5 6 A 8 E<br> A 7 6 - 5 E F 4 8 - 0 C 2 - - B<br> \- 1 3 B 0 8 C 2 A 4 E - 7 5 F D<br> 4 0 - 9 B 3 8 - E - F A 1 6 7 2<br> B E 2 - 7 F 4 9 1 3 6 0 C 8 - -<br> 3 5 F 1 E - 6 - 7 8 C 2 B 4 9 A<br> \- 6 C 7 A 5 2 1 D B 4 9 F 3 E 0<br> C D 8 0 F B - E 9 6 A 4 - 7 - -<br> 7 A E 3 - 6 9 8 B C 5 D 0 F 4 1<br> 6 F 9 4 D - 3 5 0 2 - - - B - 8<br> 1 - B 5 C 4 7 0 F E 3 8 A D 6 9<br> ### Output The code will either output the solved hexadoku board to STDOUT, or it will alert the user that the provided board was unsolvable. <file_sep>#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* next; }; int** convertMatrix(char**); void freeIntMatrix(int**); int checkSanity(int**); void freeLL(struct node*); void solveBoard(int**); char** convertBackToHex(int**); int definiteSolvable(int*); int determineValue(int*); int* determineIndex(int*, int, int, int*); int checkSolved(int**); int main(int argc, char** argv){ char* file_name = argv[1]; FILE * file = fopen(file_name, "r"); if(file == NULL){ printf("File %s does not exist.", file_name); } char ** matrix; matrix = malloc(16 * sizeof(char*)); for(int i = 0; i < 16; i++){ matrix[i] = malloc(16 * sizeof(char)); } for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ char temp; char disposable; fscanf(file, "%c%c", &temp, &disposable); matrix[i][j] = temp; } } int** m = convertMatrix(matrix); int sane = checkSanity(m); if(sane == 0){ solveBoard(m); }else{ printf("no-solution"); } freeIntMatrix(m); for(int i = 0; i < 16; i++){ free(matrix[i]); } free(matrix); fclose(file); return 0; } int** convertMatrix(char** matrix){ int** result; result = malloc(16 * sizeof(int*)); for(int i = 0; i < 16; i++){ result[i] = malloc(16 * sizeof(int)); } for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ if(matrix[i][j] >= 48 && matrix[i][j]<= 57){ result[i][j] = (int)matrix[i][j] - 48; }else if(matrix[i][j] >= 65 && matrix[i][j] <= 70){ result[i][j] = (int)matrix[i][j] - 55; }else{ result[i][j] = -1; } } } return result; } void freeIntMatrix(int** matrix){ for(int i = 0; i < 16; i++){ free(matrix[i]); } free(matrix); } int checkSanity(int** matrix){ for(int i = 0; i < 16; i++){ struct node* head = malloc(sizeof(struct node)); head->data = matrix[i][0]; head->next = NULL; for(int j = 1; j < 16; j++){ struct node* temp = head; while(temp != NULL){ if(temp->data == matrix[i][j]){ if(matrix[i][j] != -1){ return 1; } } temp = temp->next; } struct node* temp2 = malloc(sizeof(struct node)); temp2->data = matrix[i][j]; temp2->next = head; head = temp2; } freeLL(head); } for(int i = 0; i < 16; i++){ struct node* head = malloc(sizeof(struct node)); head = NULL; for(int j = 0; j < 16; j++){ struct node* temp = head; while(temp != NULL){ if(temp->data == matrix[j][i]){ if(matrix[j][i] != -1){ return 1; } } temp = temp->next; } struct node* temp2 = malloc(sizeof(struct node)); temp2->data = matrix[j][i]; temp2->next = head; head = temp2; } freeLL(head); } for(int x = 0; x < 4; x++){ for(int y = 0; y < 4; y++){ struct node* head = malloc(sizeof(struct node)); head = NULL; for(int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ struct node* temp = head; while(temp != NULL){ if(temp->data == matrix[i + x * 4][j + y * 4]){ if(matrix[i + x * 4][j + y * 4] != -1){ return 1; } } temp = temp->next; } struct node*temp2 = malloc(sizeof(struct node)); temp2->data = matrix[i + x * 4][j + y * 4]; temp2->next = head; head = temp2; } } freeLL(head); } } return 0; } void freeLL(struct node* head){ while(head != NULL){ struct node* temp = head; head = head->next; free(temp); } } void solveBoard(int** matrix){ int solved = 0; while(solved == 0){ int** ditto; ditto = malloc(16 * sizeof(int*)); for(int i = 0; i < 16; i++){ ditto[i] = malloc(16 * sizeof(int)); } for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ ditto[i][j] = matrix[i][j]; } } for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ if(ditto[i][j] == -1){ int possibleSolutions[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int x = 0; x < 16; x++){ int value = ditto[i][x]; if(value != -1){ possibleSolutions[value] = 1; } } for(int x = 0; x < 16; x++){ int value = ditto[x][j]; if(value != -1){ possibleSolutions[value] = 1; } } for(int x = 0; x < 4; x++){ for(int y = 0; y < 4; y++){ int m = (i / 4) * 4; int n = (j / 4) * 4; int value = ditto[m + x][n + y]; if(value != -1){ possibleSolutions[value] = 1; } } } int possSol = 0; for(int x = 0; x < 16; x++){ if(possibleSolutions[x] == 0){ possSol++; } } if(possSol == 1){ int value = -1; for(int x = 0; x < 16; x++){ if(possibleSolutions[x] == 0){ value = x; } } ditto[i][j] = value; int sane = checkSanity(ditto); if(sane == 0){ continue; }else{ printf("no-solution"); return; } }else{ continue; } } } } int solved = checkSolved(ditto); if(solved == 0){ char** board = convertBackToHex(ditto); for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ printf("%c\t", board[i][j]); } printf("\n"); } return; } int sameBoard = 0; for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ if(matrix[i][j] != ditto[i][j]){ sameBoard = 1; } } } if(sameBoard == 0){ printf("not-solved"); return; } for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ matrix[i][j] = ditto[i][j]; } } freeIntMatrix(ditto); } } int checkSolved(int** matrix){ for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ if(matrix[i][j] == -1){ return 1; } } } return 0; } //sectionNumber represents what row/col/subgrid we are analyzing /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 4 5 6 7 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */ int* determineIndex(int* section, int type, int sectionNumber, int* temp){ if(type == 0){ for(int i = 0; i < 16; i++){ if(section[i] == -1){ temp[0] = sectionNumber; temp[1] = i; return temp; } } }else if(type == 1){ for(int i = 0; i < 16; i++){ if(section[i] == -1){ temp[0] = i; temp[1] = sectionNumber; return temp; } } }else{ for(int i = 0; i < 16; i++){ if(section[i] == -1){ int subRow = i % 4; int subCol = i - (i / 4) * 4; int row = subRow * (sectionNumber % 4); int col = subCol * (sectionNumber - (sectionNumber / 4) * 4); temp[0] = row; temp[1] = col; return temp; } } } return temp; } int determineValue(int* section){ int solutions[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int j = 0; j < 16; j++){ if(section[j] != -1){ solutions[section[j]] = 1; } } for(int j = 0; j < 16; j++){ if(solutions[j] == 0){ return j; } } return -1; } int definiteSolvable(int* section){ int openSpaces = 0; for(int i = 0; i < 16; i++){ if(section[i] == -1){ openSpaces++; } } return openSpaces; } char** convertBackToHex(int** matrix){ char** result; result = malloc(16 * sizeof(char*)); for(int i = 0; i < 16; i++){ result[i] = malloc(16 * sizeof(char)); } for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ if(matrix[i][j] >= 0 && matrix[i][j]<= 9){ result[i][j] = (char)matrix[i][j] + 48; }else{ result[i][j] = (char)matrix[i][j] + 55; } } } return result; } /* char** result = convertBackToHex(matrix); for(int i = 0; i < 16; i++){ for(int j = 0; j < 16; j++){ printf("%c\t", result[i][j]); } printf("\n"); } */
79968a8f0523612a28404c2173d4c9cebe15f7a5
[ "Markdown", "C", "Makefile" ]
3
Makefile
evanwire/HexadokuSolver
424cb1c95ab4e67fcc0298e55bcdba696c573d8d
62a3c79b496bd273278f17af6e6233d44dc5a557
refs/heads/master
<repo_name>friseon/c23423_a<file_sep>/src/components/game/game.js import { state } from './../data/state'; import GameObject from './__object/__object'; export default class Game { constructor(canvas, context) { this.canvas = canvas; this.context = context; state.changeExperience(0); } start = () => { const playerProps = { type: 'player', name: 'Я', color: '#28916E', }; const player = new GameObject(this.canvas, this.context, playerProps, null, null, 50, 50); // player.updatePosition(); console.log(player); // player.draw(); } upExp = () => { state.changeExperience(1); } } <file_sep>/src/components/utils.js const createElement = (template) => { const outer = document.createElement('div'); outer.innerHTML = template; return outer; }; const remove = () => {}; export { createElement, remove }; <file_sep>/src/components/data/options.js export default { canvas: { properties: { width: 800, height: 400, }, startPosition: { x: 50, y: 10, }, scale: (window.innerWidth / 800) * (window.innerHeight / 400), }, game: { gravity: 0.05, }, }; <file_sep>/src/components/template.js class Template { template = () => { throw new Error('You have to define template for Template'); } bind = () => { /* listeners */ } changeData = (data) => { this.template(data); }; } export default Template; <file_sep>/src/components/game/__header/__header-view.js import Template from './../../template'; class HeaderView extends Template { constructor(scope = {}) { super(); this.data = scope; } bind = (context, scope) => { const homeButton = context.element.querySelector('.header__button-home'); homeButton.onclick = () => { console.log('GO HOME!'); scope.goHome(); // scope.changeExp(); console.log(this.data); }; } template = () => (` <header class="header__wrapper"> <h1>Header</h1> <button class="header__button-home">GO HOME!</button> ${this.data.experience} </header> `).trim(); } export default HeaderView; <file_sep>/src/components/view.js class View { template = () => { throw new Error('You have to define template fo view'); } render = () => { const outer = document.createElement('div'); outer.className = 'view'; outer.innerHTML = this.template(); return outer; } bind = () => { /* listeners */ } getView = () => { if (!this.element) { this.element = this.render(); this.bind(); } return this.element; } update = () => { const main = document.getElementById('main'); main.innerHTML = ''; this.element = this.render(); this.bind(); main.appendChild(this.element); } changeView = (view) => { const main = document.getElementById('main'); main.innerHTML = ''; main.appendChild(view.getView()); }; } export default View; <file_sep>/src/components/welcome/welcome-view.js import View from './../view'; import GameView from './../game/game-view'; class WelcomeView extends View { bind = () => { const startButton = this.element.querySelector('.welcome__button-start'); startButton.onclick = () => { const gameView = new GameView(); this.changeView(gameView); }; } template = () => (` <div class="welcome__wrapper"> <h1>Hello World! This is THE GAME BLEД!</h1> <p>Your goal is live. Job and live! But jobbing is more important.</p> <button class="welcome__button-start">START this fucking game!</button> </div> `).trim(); } export default WelcomeView; <file_sep>/src/components/game/__object/__object.js import options from './../../data/options'; /** * Конструктор объекта в Canvas * @param {*} canvas * @param {*} context * @param {String} gameObject * @param {Number} width * @param {Number} height * @param {Number} x * @param {Number} y */ export default class GameObject { constructor(canvas, context, gameObject, width, height, x, y) { this.canvas = canvas; this.context = context; this.gameObject = gameObject; this.fontSize = 30 * options.canvas.scale > 60 ? 60 : 30; this.height = height || parseInt(this.fontSize, 10) + 10; this.width = width || context.measureText(gameObject.name).width + 10; this.x = x; this.y = y; this.speedX = 0; this.speedY = 0; this.gravitySpeed = 0; if (this.gameObject.type === 'player') { this.width = parseInt(this.fontSize, 10) + 10; this.height = parseInt(this.fontSize, 10) + 10; } this.draw(); } /** * Отрисовка объекта */ draw = () => { const context = this.context; console.log('draw'); if (this.gameObject.type === 'text') { context.fillStyle = this.gameObject.color; context.font = `${this.fontSize / 3}px Arial`; context.fillText(this.text, this.x, this.y); } else { context.font = `${this.fontSize}px Arial`; context.fillStyle = this.gameObject.color; context.fillRect(this.x, this.y, this.width, this.height); context.textBaseline = 'top'; context.fillStyle = 'white'; context.fillText(this.gameObject.name, this.x + 5, this.y); } }; /** * Обновить расположение */ updatePosition = () => { this.gravitySpeed += options.game.gravity; this.x += this.speedX; this.y += this.speedY + this.gravitySpeed; const borderBottom = this.canvas.height - this.height; if (this.y >= borderBottom) { this.y = borderBottom; this.gravitySpeed = 0; this.energy -= 1; } else if (this.y <= 0) { this.y = 0; this.gravitySpeed = 0; this.energy -= 1; } }; /** * Столкновение с другими объектами * * @param {*} otherobj */ strikeWith = (otherobj) => { const myleft = this.x; const myright = this.x + (this.width); const mytop = this.y; const mybottom = this.y + (this.height); const otherleft = otherobj.x; const otherright = otherobj.x + (otherobj.width); const othertop = otherobj.y; const otherbottom = otherobj.y + (otherobj.height); let isStrike = true; if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) { isStrike = false; } return isStrike; }; } <file_sep>/src/components/welcome/welcome.js import WelcomeView from './welcome-view'; export default class Welcome { showWelcome = () => { const welcome = new WelcomeView(); welcome.changeView(welcome); console.log('Welcome!'); } } <file_sep>/src/components/player/player.js class Player { constructor(state) { this.position = state.position; this.experience = state.experience; this.time = state.time; } } export default Player;
2bccd22814a55ab11574e4d9d2f2157c41d918ad
[ "JavaScript" ]
10
JavaScript
friseon/c23423_a
50843f278be3d209e3b1031f91e42789c0a1a22f
79ff44cbd3967ea457da44eba7b5235ea7c0eb66
refs/heads/master
<file_sep># O2 Sensor Simulator by hiruna - WIP This is a very basic prototype to bypass the factory installed O2 Sensor in a motorcycle/car and send custom sensor data to the ECU. The purpose of the prototype was to force the ECU to operate on a static fuel map, enabling the user to change to the prefered Air-fuel ratio. ### BEFORE YOU PERFORM ANY MODIFICATIONS TO YOUR VEHICLE, PLEASE NOTE THAT I AM NOT RESPONSIBLE FOR ANY DAMAGE CAUSED TO YOUR BIKE/CAR. ### Material list * Car/Bike with O2 Sensor * Breadboard/jumper wires * Arduino UNO R3 (or other arduino) * Potentiometer * SD Card module (optional) * 330 ohm resistor * Duct-tape or electrical tape Testing was performed on a 2014 Honda CBR500R. The O2 sensor consists of 4 wires that leads into the ECU. Two of the wires are known as "heater" wires (usually same color), and the other 2 wires sends a voltage reading to the ECU, 0.0v - 1.0v (narrowband). ### Prepping up the ECU plug * Make sure your car/bike is switched off. * The O2 sensor plug can be identified by examining where the the wire leads from the sensor. Once the plug has been found, unplug it. Obviously we will send data to the ECU and not the O2 sensor, so pick up the lead from the ECU and insert breadboard wires into the for pins to extend it. Bend the wires back and tape around the bend in order to secure it. * Heater wires can be easily identified by the colors on the wires, they are usually the same color. * Attach the 330 ohm resistor to the heater wires and secure it with tape. Attaching the resistor tricks the ECU into think that an O2 sensor is present. ### Arduino setup Grab your Arduino R3 (or other) and set up the I/O pins according to my sketch. * Without data logger - simple voltage output through pin 9 to ECU ```Potentiometer pin : 5``` ```Voltage out pin : 9``` * With data logger - voltage output through pin 9 + logging voltages set by user into a text file ```MOSI = Pin 11``` ```MISO = Pin 12``` ```SCLK = PIN 13``` ```Potentiometer pin : 5``` ```Voltage out pin : 9``` * Note that in both sketches, ```val = map(val, 0, 1023, 0, 50);``` can be modified to define the range of the output voltage. By simply using a multimeter, the output voltage of pin 9 can be determined. Then using the debug data from the Serial monitor, 0 and 50 can be changed into the desired values. ### ALWAYS MAKE SURE YOU TEST THE OUTPUT VOLTAGE USING A MULTIMETER BEFORE ATTACHING THE ```PIN 9``` WIRE TO THE ECU * Locate the ```ground wire``` of the sensor plug (from ECU) and attach it to the ```ground``` of the Arduino. The wire attached to ```pin 9``` connects to the remaining wire in the sensor plug (from ECU). To power up the arduino, I used a 4xAA battery pack. If everything was setup correctly, the check engine light should not be displayed. Make sure everything is secured well before testing out the vehicle. The user should be able to change the values by using the potentiometer on the go. I have only tested the voltages 0.40-0.64 volts. I did experince a sight increase in throttle response. This project is still WIP. Feel free to adapt the code and improve it <file_sep>/* O2 Sensor Simulator with Data Logger Code by <NAME> Last Modified: 231115 @ 1812 */ #include <SPI.h> #include <SD.h> /* Not required to initialize as and input or output This is predefined in the SD Library. MOSI = Pin 11 MISO = Pin 12 SCLK = PIN 13 */ int CSP = 10; int count = 0; int voltage = 0; void setup() { Serial.begin(9600); Serial.println("Initializing Card"); pinMode(CSP, OUTPUT); pinMode(8, OUTPUT); //to draw power to card digitalWrite(8, HIGH); pinMode(9,OUTPUT); //voltage out to the ECU pinMode(5,INPUT); //potentiometer pin if (!SD.begin(CSP)) { Serial.println("Error"); return; } Serial.println("OK"); } void loop() { File sensorLog = SD.open("log.txt", FILE_WRITE); if (sensorLog) { voltage = analogRead(5); Serial.println(voltage);//DEBUG voltage = map(voltage, 0, 1023, 0, 50); //value 0 and 50 can be changed according to the desired voltage output Serial.print("new voltage: "); Serial.println(voltage);//DEBUG analogWrite(9,voltage); sensorLog.print(count); sensorLog.print(","); sensorLog.println(voltage); sensorLog.close(); count++; /* SAMPLE OUTPUT TO FILE: 0,23 0,23 0,23 0,41 */ } else { Serial.println("File read error"); } delay(500); } <file_sep>/* O2 Sensor Simulator Code by <NAME> Last Modified: 231115 @ 1751 */ int val = 0; void setup() { pinMode(9,OUTPUT); //voltage out to the ECU pinMode(5,INPUT); //potentiometer pin Serial.begin(9600);//DEBUG } void loop() { val = analogRead(5); Serial.println(val);//DEBUG val = map(val, 0, 1023, 0, 50); //value 0 and 50 can be changed according to the desired voltage output Serial.print("new val: "); Serial.println(val);//DEBUG analogWrite(9,val); delay(1000); }
4749aa7ca19374567a79c64f4df1771ea278b53d
[ "Markdown", "C++" ]
3
Markdown
onurtatli/O2_sensor_simulator
3d6b68743675ae71fcb38b0fe6a047df078cedad
15a470a00888e5be003b0254230dcbd18f18b62c
refs/heads/master
<repo_name>virginieguemas/s2dverification<file_sep>/R/PlotStereoMap.R #'Maps A Two-Dimensional Variable On A Polar Stereographic Projection #' #'Map longitude-latitude array (on a regular rectangular or gaussian grid) on #'a polar stereographic world projection with coloured grid cells. Only the #'region within a specified latitude interval is displayed. A colour bar #'(legend) can be plotted and adjusted. It is possible to draw superimposed #'dots, symbols and boxes. A number of options is provided to adjust the #'position, size and colour of the components. This plot function is #'compatible with figure layouts if colour bar is disabled. #' #'@param var Array with the values at each cell of a grid on a regular #' rectangular or gaussian grid. The array is expected to have two dimensions: #' c(latitude, longitude). Longitudes can be in ascending or descending order #' and latitudes in any order. It can contain NA values (coloured with #' 'colNA'). Arrays with dimensions c(longitude, latitude) will also be #' accepted but 'lon' and 'lat' will be used to disambiguate so this #' alternative is not appropriate for square arrays. #'@param lon Numeric vector of longitude locations of the cell centers of the #' grid of 'var', in ascending or descending order (same as 'var'). Expected #' to be regularly spaced, within either of the ranges [-180, 180] or #' [0, 360]. Data for two adjacent regions split by the limits of the #' longitude range can also be provided, e.g. \code{lon = c(0:50, 300:360)} #' ('var' must be provided consitently). #'@param lat Numeric vector of latitude locations of the cell centers of the #' grid of 'var', in any order (same as 'var'). Expected to be from a regular #' rectangular or gaussian grid, within the range [-90, 90]. #'@param latlims Latitudinal limits of the figure.\cr #' Example : c(60, 90) for the North Pole\cr #' c(-90,-60) for the South Pole #'@param toptitle Top title of the figure, scalable with parameter #' 'title_scale'. #'@param sizetit Scale factor for the figure top title provided in parameter #' 'toptitle'. Deprecated. Use 'title_scale' instead. #'@param units Title at the top of the colour bar, most commonly the units of #' the variable provided in parameter 'var'. #'@param brks,cols,bar_limits,triangle_ends Usually only providing 'brks' is #' enough to generate the desired colour bar. These parameters allow to #' define n breaks that define n - 1 intervals to classify each of the values #' in 'var'. The corresponding grid cell of a given value in 'var' will be #' coloured in function of the interval it belongs to. These parameters are #' sent to \code{ColorBar()} to generate the breaks and colours. Additional #' colours for values beyond the limits of the colour bar are also generated #' and applied to the plot if 'bar_limits' or 'brks' and 'triangle_ends' are #' properly provided to do so. See ?ColorBar for a full explanation. #'@param col_inf,col_sup,colNA Colour identifiers to colour the values in #' 'var' that go beyond the extremes of the colour bar and to colour NA #' values, respectively. 'colNA' takes attr(cols, 'na_color') if available by #' default, where cols is the parameter 'cols' if provided or the vector of #' colors returned by 'color_fun'. If not available, it takes 'pink' by #' default. 'col_inf' and 'col_sup' will take the value of 'colNA' if not #' specified. See ?ColorBar for a full explanation on 'col_inf' and 'col_sup'. #'@param color_fun,subsampleg,bar_extra_labels,draw_bar_ticks,draw_separators,triangle_ends_scale,bar_label_digits,bar_label_scale,units_scale,bar_tick_scale,bar_extra_margin Set of parameters to control the visual #' aspect of the drawn colour bar. See ?ColorBar for a full explanation. #'@param filled.continents Colour to fill in drawn projected continents. Takes #' the value gray(0.5) by default. If set to FALSE, continents are not #' filled in. #'@param coast_color Colour of the coast line of the drawn projected #' continents. Takes the value gray(0.5) by default. #'@param coast_width Line width of the coast line of the drawn projected #' continents. Takes the value 1 by default. #'@param dots Array of same dimensions as 'var' or with dimensions #' c(n, dim(var)), where n is the number of dot/symbol layers to add to the #' plot. A value of TRUE at a grid cell will draw a dot/symbol on the #' corresponding square of the plot. By default all layers provided in 'dots' #' are plotted with dots, but a symbol can be specified for each of the #' layers via the parameter 'dot_symbol'. #'@param dot_symbol Single character/number or vector of characters/numbers #' that correspond to each of the symbol layers specified in parameter 'dots'. #' If a single value is specified, it will be applied to all the layers in #' 'dots'. Takes 15 (centered square) by default. See 'pch' in par() for #' additional accepted options. #'@param dot_size Scale factor for the dots/symbols to be plotted, specified #' in 'dots'. If a single value is specified, it will be applied to all #' layers in 'dots'. Takes 1 by default. #'@param intlat Interval between latitude lines (circles), in degrees. #' Defaults to 10. #'@param drawleg Whether to plot a color bar (legend, key) or not. #' Defaults to TRUE. #'@param boxlim Limits of a box to be added to the plot, in degrees: #' c(x1, y1, x2, y2). A list with multiple box specifications can also #' be provided. #'@param boxcol Colour of the box lines. A vector with a colour for each of #' the boxes is also accepted. Defaults to 'purple2'. #'@param boxlwd Line width of the box lines. A vector with a line width for #' each of the boxes is also accepted. Defaults to 5. #'@param margin_scale Scale factor for the margins to be added to the plot, #' with the format c(y1, x1, y2, x2). Defaults to rep(1, 4). If drawleg = TRUE, #' margin_scale[1] is subtracted 1 unit. #'@param title_scale Scale factor for the figure top title. Defaults to 1. #'@param numbfig Number of figures in the layout the plot will be put into. #' A higher numbfig will result in narrower margins and smaller labels, #' axe labels, ticks, thinner lines, ... Defaults to 1. #'@param fileout File where to save the plot. If not specified (default) a #' graphics device will pop up. Extensions allowed: eps/ps, jpeg, png, pdf, #' bmp and tiff. #'@param width File width, in the units specified in the parameter size_units #' (inches by default). Takes 8 by default. #'@param height File height, in the units specified in the parameter #' size_units (inches by default). Takes 5 by default. #'@param size_units Units of the size of the device (file or window) to plot #' in. Inches ('in') by default. See ?Devices and the creator function of #' the corresponding device. #'@param res Resolution of the device (file or window) to plot in. See #' ?Devices and the creator function of the corresponding device. #'@param \dots Arguments to be passed to the method. Only accepts the #' following graphical parameters:\cr #' adj ann ask bg bty cex.sub cin col.axis col.lab col.main col.sub cra crt #' csi cxy err family fg font font.axis font.lab font.main font.sub lend #' lheight ljoin lmitre mex mfcol mfrow mfg mkh omd omi page pch pin plt pty #' smo srt tcl usr xaxp xaxs xaxt xlog xpd yaxp yaxs yaxt ylbias ylog \cr #' For more information about the parameters see `par`. #' #'@return #'\item{brks}{ #' Breaks used for colouring the map (and legend if drawleg = TRUE). #'} #'\item{cols}{ #' Colours used for colouring the map (and legend if drawleg = TRUE). Always #' of length length(brks) - 1. #'} #'\item{col_inf}{ #' Colour used to draw the lower triangle end in the colour bar (NULL if not #' drawn at all). #'} #'\item{col_sup}{ #' Colour used to draw the upper triangle end in the colour bar (NULL if not #' drawn at all). #'} #' #'@keywords dynamic #'@author History:\cr #'1.0 - 2014-07 (<NAME>, \email{virginie.guemas@@ic3.cat}) - Original code\cr #'1.1 - 2015-12 (<NAME>, \email{<EMAIL>}) - Box(es) drawing\cr #'1.2 - 2016-08 (<NAME>, \email{<EMAIL>}) - Refacotred the function and #' merged in Jean-Philippe circle #' border and Constantin boxes. #'@examples #'data <- matrix(rnorm(100 * 50), 100, 50) #'x <- seq(from = 0, to = 360, length.out = 100) #'y <- seq(from = -90, to = 90, length.out = 50) #'PlotStereoMap(data, x, y, latlims = c(60, 90), brks = 50, #' toptitle = "This is the title") #'@import mapproj #'@importFrom grDevices dev.cur dev.new dev.off gray #'@importFrom stats median #'@export PlotStereoMap <- function(var, lon, lat, latlims = c(60, 90), toptitle = NULL, sizetit = NULL, units = NULL, brks = NULL, cols = NULL, bar_limits = NULL, triangle_ends = NULL, col_inf = NULL, col_sup = NULL, colNA = NULL, color_fun = clim.palette(), filled.continents = FALSE, coast_color = NULL, coast_width = 1, dots = NULL, dot_symbol = 4, dot_size = 0.8, intlat = 10, drawleg = TRUE, subsampleg = NULL, bar_extra_labels = NULL, draw_bar_ticks = TRUE, draw_separators = FALSE, triangle_ends_scale = 1, bar_label_digits = 4, bar_label_scale = 1, units_scale = 1, bar_tick_scale = 1, bar_extra_margin = rep(0, 4), boxlim = NULL, boxcol = "purple2", boxlwd = 5, margin_scale = rep(1, 4), title_scale = 1, numbfig = NULL, fileout = NULL, width = 6, height = 5, size_units = 'in', res = 100, ...) { # Process the user graphical parameters that may be passed in the call ## Graphical parameters to exclude excludedArgs <- c("cex", "cex.main", "col", "fin", "lab", "las", "lwd", "mai", "mar", "mgp", "new", "pch", "ps") userArgs <- .FilterUserGraphicArgs(excludedArgs, ...) # If there is any filenames to store the graphics, process them # to select the right device if (!is.null(fileout)) { deviceInfo <- .SelectDevice(fileout = fileout, width = width, height = height, units = size_units, res = res) saveToFile <- deviceInfo$fun fileout <- deviceInfo$files } # Preliminar check of dots, lon, lat if (!is.null(dots)) { if (!is.array(dots) || !(length(dim(dots)) %in% c(2, 3))) { stop("Parameter 'dots' must be a logical array with two or three dimensions.") } if (length(dim(dots)) == 2) { dim(dots) <- c(1, dim(dots)) } } if (!is.numeric(lon) || !is.numeric(lat)) { stop("Parameters 'lon' and 'lat' must be numeric vectors.") } # Check var if (!is.array(var)) { stop("Parameter 'var' must be a numeric array.") } if (length(dim(var)) > 2) { var <- drop(var) dim(var) <- head(c(dim(var), 1, 1), 2) } if (length(dim(var)) > 2) { stop("Parameter 'var' must be a numeric array with two dimensions. See PlotMultiMap() for multi-pannel maps or AnimateMap() for animated maps.") } else if (length(dim(var)) < 2) { stop("Parameter 'var' must be a numeric array with two dimensions.") } dims <- dim(var) # Transpose the input matrices because the base plot functions work directly # with dimensions c(lon, lat). if (dims[1] != length(lon) || dims[2] != length(lat)) { if (dims[1] == length(lat) && dims[2] == length(lon)) { var <- t(var) if (!is.null(dots)) dots <- aperm(dots, c(1, 3, 2)) dims <- dim(var) } } # Check lon if (length(lon) != dims[1]) { stop("Parameter 'lon' must have as many elements as the number of cells along longitudes in the input array 'var'.") } # Check lat if (length(lat) != dims[2]) { stop("Parameter 'lat' must have as many elements as the number of cells along longitudes in the input array 'var'.") } # Check latlims if (!is.numeric(latlims) || length(latlims) != 2) { stop("Parameter 'latlims' must be a numeric vector with two elements.") } latlims <- sort(latlims) center_at <- 90 * sign(latlims[which.max(abs(latlims))]) if (max(abs(latlims - center_at)) > 90 + 20) { stop("The range specified in 'latlims' is too wide. 110 degrees supported maximum.") } dlon <- median(lon[2:dims[1]] - lon[1:(dims[1] - 1)]) / 2 dlat <- median(lat[2:dims[2]] - lat[1:(dims[2] - 1)]) / 2 original_last_lat <- latlims[which.min(abs(latlims))] last_lat <- lat[which.min(abs(lat - original_last_lat))] - dlat * sign(center_at) latlims[which.min(abs(latlims))] <- last_lat # Check toptitle if (is.null(toptitle) || is.na(toptitle)) { toptitle <- '' } if (!is.character(toptitle)) { stop("Parameter 'toptitle' must be a character string.") } # Check sizetit if (!is.null(sizetit)) { .warning("Parameter 'sizetit' is obsolete. Use 'title_scale' instead.") if (!is.numeric(sizetit) || length(sizetit) != 1) { stop("Parameter 'sizetit' must be a single numeric value.") } title_scale <- sizetit } # Check: brks, cols, subsampleg, bar_limits, color_fun, bar_extra_labels, draw_bar_ticks # draw_separators, triangle_ends_scale, label_scale, units, units_scale, # bar_label_digits # Build: brks, cols, bar_limits, col_inf, col_sup var_limits <- c(min(var, na.rm = TRUE), max(var, na.rm = TRUE)) colorbar <- ColorBar(brks, cols, FALSE, subsampleg, bar_limits, var_limits, triangle_ends, col_inf, col_sup, color_fun, FALSE, extra_labels = bar_extra_labels, draw_ticks = draw_bar_ticks, draw_separators = draw_separators, triangle_ends_scale = triangle_ends_scale, label_scale = bar_label_scale, title = units, title_scale = units_scale, tick_scale = bar_tick_scale, extra_margin = bar_extra_margin, label_digits = bar_label_digits) brks <- colorbar$brks cols <- colorbar$cols col_inf <- colorbar$col_inf col_sup <- colorbar$col_sup bar_limits <- c(head(brks, 1), tail(brks, 1)) # Check colNA if (is.null(colNA)) { if ('na_color' %in% names(attributes(cols))) { colNA <- attr(cols, 'na_color') if (!.IsColor(colNA)) { stop("The 'na_color' provided as attribute of the colour vector must be a valid colour identifier.") } } else { colNA <- 'pink' } } else if (!.IsColor(colNA)) { stop("Parameter 'colNA' must be a valid colour identifier.") } # Check filled.continents if (!.IsColor(filled.continents) && !is.logical(filled.continents)) { stop("Parameter 'filled.continents' must be logical or a colour identifier.") } else if (!is.logical(filled.continents)) { continent_color <- filled.continents filled.continents <- TRUE } else if (filled.continents) { continent_color <- gray(0.5) } # Check coast_color if (is.null(coast_color)) { if (filled.continents) { coast_color <- continent_color } else { coast_color <- 'black' } } if (!.IsColor(coast_color)) { stop("Parameter 'coast_color' must be a valid colour identifier.") } # Check coast_width if (!is.numeric(coast_width)) { stop("Parameter 'coast_width' must be numeric.") } # Check dots, dot_symbol and dot_size if (!is.null(dots)) { if (dim(dots)[2] != dims[1] || dim(dots)[3] != dims[2]) { stop("Parameter 'dots' must have the same number of longitudes and latitudes as 'var'.") } if (!is.numeric(dot_symbol) && !is.character(dot_symbol)) { stop("Parameter 'dot_symbol' must be a numeric or character string vector.") } if (length(dot_symbol) == 1) { dot_symbol <- rep(dot_symbol, dim(dots)[1]) } else if (length(dot_symbol) < dim(dots)[1]) { stop("Parameter 'dot_symbol' does not contain enough symbols.") } if (!is.numeric(dot_size)) { stop("Parameter 'dot_size' must be numeric.") } if (length(dot_size) == 1) { dot_size <- rep(dot_size, dim(dots)[1]) } else if (length(dot_size) < dim(dots)[1]) { stop("Parameter 'dot_size' does not contain enough sizes.") } } # Check intlat if (!is.numeric(intlat)) { stop("Parameter 'intlat' must be numeric.") } # Check legend parameters if (!is.logical(drawleg)) { stop("Parameter 'drawleg' must be logical.") } # Check box parameters if (!is.null(boxlim)) { if (!is.list(boxlim)) { boxlim <- list(boxlim) } for (i in 1:length(boxlim)) { if (!is.numeric(boxlim[[i]]) || length(boxlim[[i]]) != 4) { stop("Parameter 'boxlim' must be a a numeric vector or a list of numeric vectors of length 4 (with W, S, E, N box limits).") } } if (!is.character(boxcol)) { stop("Parameter 'boxcol' must be a character string or a vector of character strings.") } else { if (length(boxlim) != length(boxcol)) { if (length(boxcol) == 1) { boxcol <- rep(boxcol, length(boxlim)) } else { stop("Parameter 'boxcol' must have a colour for each box in 'boxlim' or a single colour for all boxes.") } } } if (!is.numeric(boxlwd)) { stop("Parameter 'boxlwd' must be numeric.") } else { if (length(boxlim) != length(boxlwd)) { if (length(boxlwd) == 1) { boxlwd <- rep(boxlwd, length(boxlim)) } else { stop("Parameter 'boxlwd' must have a line width for each box in 'boxlim' or a single line width for all boxes.") } } } } # Check margin_scale if (!is.numeric(margin_scale) || length(margin_scale) != 4) { stop("Parameter 'margin_scale' must be a numeric vector of length 4.") } # Check title_scale if (!is.numeric(title_scale)) { stop("Parameter 'title_scale' must be numeric.") } # Check numbfig if (!is.null(numbfig)) { if (!is.numeric(numbfig)) { stop("Parameter 'numbfig' must be numeric.") } else { numbfig <- round(numbfig) scale <- 1 / numbfig ** 0.3 title_scale <- title_scale * scale margin_scale <- margin_scale * scale dot_size <- dot_size * scale } } # # Plotting the map # ~~~~~~~~~~~~~~~~~~ # # Open connection to graphical device if (!is.null(fileout)) { saveToFile(fileout) } else if (names(dev.cur()) == 'null device') { dev.new(units = size_units, res = res, width = width, height = height) } # # Defining the layout # ~~~~~~~~~~~~~~~~~~~~~ # if (drawleg) { margin_scale[1] <- margin_scale[1] - 1 } margins <- rep(0.2, 4) * margin_scale cex_title <- 2 * title_scale if (toptitle != '') { margins[3] <- margins[3] + cex_title + 1 } bar_extra_margin[1] <- bar_extra_margin[1] + margins[1] bar_extra_margin[3] <- bar_extra_margin[3] + margins[3] if (drawleg) { layout(matrix(1:2, ncol = 2, nrow = 1), widths = c(8, 2)) } # Load the user parameters par(userArgs) par(mar = margins, las = 0) coast <- map("world", interior = FALSE, projection = "stereographic", orientation = c(center_at, 0, 0), fill = filled.continents, xlim = c(-180,180), ylim = latlims, wrap = TRUE, plot = FALSE) # Compute the bounding circle limit <- abs(mapproj::mapproject(0, last_lat, projection = 'stereographic', orientation = c(center_at, 0, 0))$y) for (i in 1:length(coast$x)) { distance <- sqrt(coast$x[i]**2 + coast$y[i]**2) if (!is.na(distance)) { if (distance > limit) { coast$x[i] <- coast$x[i] / distance * limit coast$y[i] <- coast$y[i] / distance * limit } } } xcircle <- c() ycircle <- c() for (i in 0:500) { xcircle <- c(xcircle, sin(2 * pi / 500 * i) * limit) ycircle <- c(ycircle, cos(2 * pi / 500 * i) * limit) } circle <- list(x = xcircle, y = ycircle) # Plot circle to set up device plot(circle, type= 'l', axes = FALSE, lwd = 1, col = gray(0.2), asp = 1, xlab = '', ylab = '', main = toptitle, cex.main = cex_title) col_inf_image <- ifelse(is.null(col_inf), colNA, col_inf) col_sup_image <- ifelse(is.null(col_sup), colNA, col_sup) # Draw the data polygons for (jx in 1:dims[1]) { for (jy in 1:dims[2]) { if (lat[jy] >= latlims[1] && latlims[2] >= lat[jy]) { coord <- mapproj::mapproject(c(lon[jx] - dlon, lon[jx] + dlon, lon[jx] + dlon, lon[jx] - dlon), c(lat[jy] - dlat, lat[jy] - dlat, lat[jy] + dlat, lat[jy] + dlat)) if (is.na(var[jx, jy] > 0)) { col <- colNA } else if (var[jx, jy] <= brks[1]) { col <- col_inf_image } else if (var[jx, jy] >= tail(brks, 1)) { col <- col_sup_image } else { ind <- which(brks[-1] >= var[jx, jy] & var[jx, jy] > brks[-length(brks)]) col <- cols[ind] } polygon(coord, col = col, border = NA) } } } # Draw the dots if (!is.null(dots)) { numbfig <- 1 # for compatibility with PlotEquiMap code dots <- dots[, , which(lat >= latlims[1] & lat <= latlims[2]), drop = FALSE] data_avail <- !is.na(var[, which(lat >= latlims[1] & lat <= latlims[2]), drop = FALSE]) for (counter in 1:(dim(dots)[1])) { points <- which(dots[counter, , ] & data_avail, arr.ind = TRUE) points_proj <- mapproj::mapproject(lon[points[, 1]], lat[points[, 2]]) points(points_proj$x, points_proj$y, pch = dot_symbol[counter], cex = dot_size[counter] * 3 / sqrt(sqrt(sum(lat >= latlims[which.min(abs(latlims))]) * length(lon))), lwd = dot_size[counter] * 3 / sqrt(sqrt(sum(lat >= latlims[which.min(abs(latlims))]) * length(lon)))) } } # Draw the continents, grid and bounding circle if (filled.continents) { old_lwd <- par('lwd') par(lwd = coast_width) polygon(coast, col = continent_color, border = coast_color) par(lwd = old_lwd) } else { lines(coast, col = coast_color, lwd = coast_width) } mapproj::map.grid(lim = c(-180, 180, latlims), nx = 18, ny = ceiling((latlims[2] - latlims[1]) / intlat), col = 'lightgrey', labels = FALSE) polygon(circle, border = 'black') # Draw boxes on the map if (!is.null(boxlim)) { counter <- 1 for (box in boxlim) { if (box[1] > box[3]) { box[1] <- box[1] - 360 } if (length(box) != 4) { stop(paste("The", counter, "st box defined in the parameter 'boxlim' is ill defined.")) } else if (center_at == 90 && (box[2] < original_last_lat || box[4] > center_at) || center_at == -90 && (box[4] > original_last_lat || box[2] < center_at)) { stop(paste("The limits of the", counter, "st box defined in the parameter 'boxlim' are invalid.")) } else { mapproj::map.grid(lim = c(box[1], box[3], box[2], box[4]), nx = 2, ny = 2, pretty = FALSE, col = boxcol[counter], lty = "solid", lwd = boxlwd[counter], labels = FALSE) } counter <- counter + 1 } } # # Colorbar # ~~~~~~~~~~ # if (drawleg) { ColorBar(brks, cols, TRUE, subsampleg, bar_limits, var_limits, triangle_ends, col_inf = col_inf, col_sup = col_sup, extra_labels = bar_extra_labels, draw_ticks = draw_bar_ticks, draw_separators = draw_separators, title = units, title_scale = units_scale, triangle_ends_scale = triangle_ends_scale, label_scale = bar_label_scale, tick_scale = bar_tick_scale, extra_margin = bar_extra_margin, label_digits = bar_label_digits) } # If the graphic was saved to file, close the connection with the device if (!is.null(fileout)) dev.off() invisible(list(brks = brks, cols = cols, col_inf = col_inf, col_sup = col_sup)) } <file_sep>/tests/testthat/test-Composite.R context("Generic tests") test_that("Sanity checks", { expect_error( Composite(var = array(1:20, dim = c(2, 5, 2)), c(1, 1, 0)), "Temporal dimension of var is not equal to length of occ.") expect_warning( Composite(var = array(1:40, dim = c(2, 5, 4)), c(1, 2, 2, 2)), "Composite 1 has length 1 and pvalue is NA.") var <- array(rep(c(1, 3, 2, 1, 2), 8), dim = c(x = 2, y = 4, time = 5)) occ <- c(1, 2, 2, 2, 1) output <- c(x = 2, y = 4, 2) #dim(asd$composite) expect_equal( dim(Composite(var, occ)$composite), output ) output <- c(1.5, 2.0, 2.5, 2.0) expect_equal( Composite(var, occ)$composite[1, , 1], output ) var <- array(rep(c(1, 3, 2, 1, 2, 2), 8), dim = c(x = 2, y = 4, time = 6)) occ <- c(1, 1, 2, 2, 3, 3) output <- matrix(c(1.5, 2.5, 1.5, 2.0, 2.0, 1.5, 1.5, 2.5), 2, 4) expect_equivalent( Composite(var, occ)$composite[, , 2], output ) }) <file_sep>/tests/testthat.R library(testthat) library(s2dverification) test_check("s2dverification") <file_sep>/tests/testthat/test-Ano.R context("Generic tests") test_that("Sanity checks", { var <- array(rnorm(16), c(2, 2, 2, 2)) names(dim(var)) <- c("memb", "lon", "sdates", "lat") clim <- apply(var, c(1, 2, 4), mean) names(dim(clim)) <- NULL expect_error( Ano(var, clim), "Provide dimension names on parameter \'var\' and \'clim\' to avoid ambiguity." ) t <- array(rnorm(76), c(1, 3, 4, 3, 2, 2)) names(dim(t)) <- c("mod", "memb", "sdates", "ltime", "lon", "lat") c3 <- Clim(t, t, memb = TRUE)$clim_exp # Clim for each member c1 <- InsertDim(c3[, 1, ,, ], 1, 1) # clim as if memb=FALSE but identical to member 1 names(dim(c1)) <- c("mod", "ltime", "lon", "lat") identical(c1[, , , ], c3[, 1, , , ]) # results in TRUE a3 <- Ano(t, c3) # ano for each member individually a1 <- Ano(t, c1) # ano for first member expect_equal( a1[, 1, , , , ], a3[, 1, , , , ] ) })
8635394c945473c5e6d4e76ab9e57be496082ed1
[ "R" ]
4
R
virginieguemas/s2dverification
47e29959f94de06f6c8994885a3edaaa97d86496
a0300d2f105769626caefca74aef82a65078570a
refs/heads/master
<file_sep>package main import ( "fmt" "os" ) func Learn(csvFile [][]string) { var ( cardsToLearn []Card = CreateSliceOfCards(csvFile) cardsLearned []Card cardsNotLearned []Card card Card ) if len(cardsToLearn) < 5 { fmt.Println("Please, your CSV file must have at least 5 cards") os.Exit(1) } for len(cardsToLearn) > len(cardsLearned) { for i := range cardsToLearn { if card = cardsToLearn[i]; !IsCardInSliceOfCards(card, cardsLearned) { fmt.Printf("%s = ", card.frontFace) var answer string fmt.Scan(&answer) if answer == card.backFace { cardsLearned = append(cardsLearned, card) } else { cardsNotLearned = append(cardsNotLearned, card) } } } if cardsNotLearned != nil { fmt.Println("You still don't know some cards") fmt.Println("Let's try those cards again!") for i := range cardsNotLearned { card = cardsNotLearned[i] for IsCardInSliceOfCards(card, cardsNotLearned) && !IsCardInSliceOfCards(card, cardsLearned) { fmt.Printf("%s = ", card.frontFace) var answer string fmt.Scan(&answer) if answer == card.backFace { cardsLearned = append(cardsLearned, card) } else { fmt.Println("It's wrong, try again") } } } } } fmt.Println("You learned every cards in your deck!") os.Exit(1) } <file_sep># goCards CLI made with the Go standard library to practice flash cards with CSV files. Inspired by the Quiz App in [gophercises](https://gophercises.com/) and the idea from this repo of [app ideas](https://github.com/florinpop17/app-ideas/blob/master/Projects/FlashCards-App.md) ## Usage **Be sure you have Go properly installed.** 1. Get the repo: - ```go get github.com/rafa-leao/goCards``` 2. Check if ```$GOPATH/bin``` is in your path. If so you can use the app anywhere; 3. The command list: - To see the front and back face of your cards: ``` goCards --look file.csv ``` - To start practicing with your cards: ``` goCards --play file.csv ``` - To learn your cards: ``` goCards --learn file.csv ``` - And for help: ``` goCards --h --help ``` <file_sep>package main import ( "flag" "fmt" "os" ) var ( learnCSV = flag.String("learn", "", "Path for CSV file to learn your cards ") playCSV = flag.String("play", "", "Path for CSV file to start practicing ") lookCSV = flag.String("look", "", "Path for CSV file and see how the cards are organized ") ) func main() { flag.Parse() switch { case *learnCSV != "": openedCSV := ReadCSV(*learnCSV) Learn(openedCSV) case *playCSV != "": openedCSV := ReadCSV(*playCSV) Practice(openedCSV) case *lookCSV != "": for i := range ReadCSV(*lookCSV) { fmt.Println(ReadCSV(*lookCSV)[i]) } default: flag.Usage() os.Exit(1) } } <file_sep>package main import ( "fmt" "math/rand" "os" "time" ) func randomNumber(number int) int { return rand.New(rand.NewSource(time.Now().UnixNano())).Intn(number) } func Practice(csvFile [][]string) { var ( cardsToPractice []Card = CreateSliceOfCards(csvFile) cardsAnswered []Card card Card ) for totalOfCards := len(cardsToPractice); totalOfCards > len(cardsAnswered); { card = cardsToPractice[randomNumber(len(cardsToPractice))] if !IsCardInSliceOfCards(card, cardsAnswered) { fmt.Printf("%s = ", card.frontFace) var answer string fmt.Scan(&answer) if answer != card.backFace { fmt.Printf("Wrong answer. Do not give up! You made %d of %d.\n", len(cardsAnswered), len(cardsToPractice)) fmt.Println("Try again or learn your deck of cards with the '--learn' command!") os.Exit(1) } else { cardsAnswered = append(cardsAnswered, card) } } } fmt.Println("You got every thing!") os.Exit(1) } <file_sep>package main import ( "encoding/csv" "log" "os" ) func ReadCSV(fileName string) [][]string { csvFile, err := os.Open(fileName) if err != nil { log.Fatalln(err) } result, err := csv.NewReader(csvFile).ReadAll() if err != nil { log.Fatalln(err) } return result } <file_sep>package main // types type Card struct { frontFace string backFace string } // functions func CreateSliceOfCards(csvFile [][]string) (cardsToPractice []Card) { cardsToPractice = make([]Card, len(csvFile)) for i, card := range csvFile { cardsToPractice[i] = Card{ frontFace: card[0], backFace: card[1], } } return } func IsCardInSliceOfCards(card Card, cardsAnswered []Card) bool { for _, cardAnswered := range cardsAnswered { if card == cardAnswered { return true } } return false }
7c155ea7038869bbe76ae1f582130a4c957b385d
[ "Markdown", "Go" ]
6
Go
rafa-leao/cards
d0a5343f59b4829ff3c51446484fa3128f2704b0
84b914b3fc4f241414231bf52905b8d226c708f3
refs/heads/master
<file_sep>package cn.lhj.mvcproject.dao; import java.sql.Connection; import java.util.List; import cn.lhj.mvcproject.model.User; /** * 接口定义规则,只定义方法,不实现,UserDao,定义与Users数据表有关系的操作方法; * @author lihaijian * */ public interface UserDao { /** * 实现插入一条用户信息。 * @param user * @return */ public int save(User user); public int deleteUserById(int id); public int updateUserById(User user); public User get(int id); public User get(Connection conn,int id); public List<User> getListAll(); public int getCountByName(String username); /** * 实现模糊查询的方法 * @param username * @param address * @param phoneno * @return */ public List<User> query(String username, String address, String phoneno); /** * 用用户名和密码查询用户的方法。 * @param username * @param passwd */ public User getUserByUp(String username, String passwd); } <file_sep>package cn.lhj.mvcproject.filter; import java.io.IOException; import java.net.CookieStore; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.annotation.WebListener; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.lhj.mvcproject.model.Ponline; import cn.lhj.mvcproject.service.FactoryService; import cn.lhj.mvcproject.service.PonlineService; import cn.lhj.mvcproject.utils.CookieUtils; @WebListener public class AutoLoginFilter extends BaseFilter{ PonlineService ponlineService = FactoryService.getPonlineService(); @Override protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { System.out.println("AutoLoginFilter doFilter"); Cookie[] cookies = req.getCookies(); if(cookies!=null&&cookies.length!=0) { String username = null; String ssid = null; for(Cookie cookie:cookies) { if(cookie.getName().equals("userKey")) { username = cookie.getValue(); } if(cookie.getName().equals("ssid")) { ssid = cookie.getValue(); } } if(username!=null&&ssid!=null&&CookieUtils.md5Encrypt(username).equals(ssid)) { HttpSession session = req.getSession(); session.setAttribute("user", username); //自动登录时设置Traveller为username Ponline ponline = ponlineService.getOnlineBySsid(session.getId()); if(ponline!=null) { ponline.setUsername(username); ponlineService.updateOnline(ponline); } resp.sendRedirect(req.getContextPath()+"/index.jsp"); }else { chain.doFilter(req, resp); } }else { chain.doFilter(req, resp); } } } <file_sep>package cn.lhj.mvcproject.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.lhj.mvcproject.filter.BaseFilter; public class IsLoginFilter extends BaseFilter{ @Override protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { System.out.println("------------被IsLoginFilter拦截了"); FilterConfig filterConfig = getFilterConfig(); String[] names = filterConfig.getInitParameter("authority").split(","); String servletName = req.getServletPath().substring(1); //System.out.println("servletName="+servletName); HttpSession session = req.getSession(true); for(String name:names) { if(name.equals(servletName)) { //System.out.println("name="+name); //System.out.println("session user="+session.getAttribute("user")); if(session.getAttribute("user")==null) { //System.out.println("In redirect"); //System.out.println(req.getContextPath()+"/login.jsp"); resp.sendRedirect(req.getContextPath()+"/login.jsp"); return; }else { break; } } } //System.out.println("out"); chain.doFilter(req, resp); } } <file_sep>package cn.lhj.mvcproject.dao; import java.math.BigDecimal; import java.sql.Connection; import java.util.Date; import java.util.List; import cn.lhj.mvcproject.model.User; public class UserDaoImpl extends BaseDao<User> implements UserDao { @Override public int save(User user) { // TODO Auto-generated method stub String sql = "insert into people(username,passwd,phoneno,address,regdate) values(?,?,?,?,(select sysdate from dual))"; return super.update(sql, user.getUsername(),user.getPasswd(),user.getPhoneNo(),user.getAddress()); } @Override public int deleteUserById(int id) { String sql = "delete from people where id=?"; return super.update(sql, id); } @Override public int updateUserById(User user) { String sql = "update people set username=?,passwd=?,phoneno=?,address=?,regdate=(select sysdate from dual) where id=?"; return super.update(sql, user.getUsername(),user.getPasswd(),user.getPhoneNo(),user.getAddress(),user.getId()); } @Override public User get(int id) { String sql = "select id ,username,passwd,phoneno,address,regdate from people where id=?"; return super.get(sql, id); } @Override public User get(Connection conn, int id) { // TODO Auto-generated method stub String sql = "select id ,username,passwd,phoneno,address,regdate from people where id=?"; return super.get(conn,sql, id); } @Override public List<User> getListAll() { // TODO Auto-generated method stub String sql = "select * from people"; return super.getList(sql); } @Override public int getCountByName(String username) { // TODO Auto-generated method stub String sql = "select count(*) from people where username=?"; BigDecimal obj = (BigDecimal) super.getValue(sql, username); return obj.intValue(); } @Override public List<User> query(String username, String address, String phoneno) { // TODO Auto-generated method stub String sql="select id,username,passwd,address,phoneno,regdate from people where 1=1"; if(username!=null&&!username.equals("")) { sql=sql+" and username like '%"+username+"%'"; } if(address!=null&&!address.equals("")) { sql=sql+" and address like '%"+address+"%'"; } if(phoneno!=null&&!phoneno.equals("")) { sql=sql+" and phoneno like '%"+phoneno+"%'"; } System.out.println(sql); return super.getList(sql); } @Override public User getUserByUp(String username, String passwd) { String sql = "select id,username,passwd,address,phoneno,regdate from people where 1=1 and username=? and passwd=?"; return super.get(sql, username,passwd); } } <file_sep>package cn.lhj.mvcproject.listener; import java.sql.Timestamp; import java.util.Date; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import cn.lhj.mvcproject.model.Ponline; import cn.lhj.mvcproject.service.FactoryService; import cn.lhj.mvcproject.service.PonlineService; /** * 任何一个请求过来都会监听 * @author lihaijian * */ @WebListener public class OnlineRequestListener implements ServletRequestListener{ PonlineService ponlineService = FactoryService.getPonlineService(); @Override public void requestDestroyed(ServletRequestEvent sre) { // TODO Auto-generated method stub } @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("OnlineRequestListener requestInitialized"); HttpServletRequest httpServletRequest = (HttpServletRequest) sre.getServletRequest(); HttpSession session = httpServletRequest.getSession(); String ssid = session.getId(); String ip = httpServletRequest.getRemoteAddr(); String page = httpServletRequest.getRequestURI(); String username = (String) session.getAttribute("user"); //如果登录了应该有一个user的属性,否则就是游客,是游客就应该先登录才能做其他操作。 if(username==null) username = "Traveller"; Ponline ponline = ponlineService.getOnlineBySsid(ssid); //System.out.println(ponline); if(ponline==null) { Ponline ol = new Ponline(); ol.setSsid(ssid); ol.setUsername(username); ol.setIp(ip); ol.setPage(page); ol.setTime(new Timestamp(new Date().getTime())); ponlineService.insertOnline(ol); }else { ponline.setUsername(username); ponline.setPage(page); ponline.setTime(new Timestamp(new Date().getTime())); ponlineService.updateOnline(ponline); } } } <file_sep>package cn.lhj.mvcproject.listener; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class OnlineListener implements HttpSessionListener,HttpSessionAttributeListener{ @Override public void attributeAdded(HttpSessionBindingEvent event) { System.out.println("attributeAdded"); HttpSession session = event.getSession(); ServletContext application = session.getServletContext(); Map<String, String> online = (Map<String, String>) application.getAttribute("online"); if(online==null) { online = new HashMap<String, String>(); } //用户登录成功时会在session属性空间注入用户名,属性标识是user。 online.put(session.getId(),session.getAttribute("user").toString()); application.setAttribute("online", online); } @Override public void attributeRemoved(HttpSessionBindingEvent event) { // TODO Auto-generated method stub } @Override public void attributeReplaced(HttpSessionBindingEvent event) { // TODO Auto-generated method stub } @Override public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext application = session.getServletContext(); Map<String, String> online = (Map<String, String>) application.getAttribute("online"); if(online==null) { online = new HashMap<String, String>(); } String username = online.get(session.getId()); if(username==null) { username = "Traveler"; } online.put(session.getId(),username); application.setAttribute("online", online); } @Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext application = session.getServletContext(); Map<String, String> online = (Map<String, String>) application.getAttribute("online"); if(online!=null) { online.remove(session.getId()); application.setAttribute("online", online); } } } <file_sep>package cn.lhj.mvcproject.test; import static org.junit.jupiter.api.Assertions.*; import java.sql.Timestamp; import java.util.Date; import java.util.List; import org.junit.jupiter.api.Test; import cn.lhj.mvcproject.dao.PonlineDao; import cn.lhj.mvcproject.dao.PonlineImpl; import cn.lhj.mvcproject.model.Ponline; class PonlineImplTest { @Test void insertOnlineTest() { Ponline ponline = new Ponline(); ponline.setSsid("efg"); ponline.setUsername("lxj"); ponline.setIp("10.9.4.175"); ponline.setPage("login.jsp"); ponline.setTime(new Timestamp(new Date().getTime())); PonlineDao ponlineDao = new PonlineImpl(); System.out.println(ponlineDao.insertOnline(ponline)); } @Test void updateOnlineTest() { Ponline ponline = new Ponline(); ponline.setSsid("abc"); ponline.setUsername("lhj111"); ponline.setIp("10.9.4.174"); ponline.setPage("login.jsp"); ponline.setTime(new Timestamp(new Date().getTime())); PonlineDao ponlineDao = new PonlineImpl(); System.out.println(ponlineDao.updateOnline(ponline)); } @Test void getAllOnlineTest() { PonlineDao ponlineDao = new PonlineImpl(); List<Ponline> list = ponlineDao.getAllOnline(); System.out.println(list.size()); } @Test void deleteExpiresOnline() { PonlineDao ponlineDao = new PonlineImpl(); String ssid = "abc"; System.out.println(ponlineDao.deleteExpiresOnline(ssid)); } @Test void getOnlineBySsid() { PonlineDao ponlineDao = new PonlineImpl(); String ssid = "efg"; System.out.println(ponlineDao.deleteExpiresOnline(ssid)); }; } <file_sep>package cn.lhj.mvcproject.service; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import cn.lhj.mvcproject.dao.FactoryDao; import cn.lhj.mvcproject.dao.UserDao; import cn.lhj.mvcproject.dao.UserDaoImpl; import cn.lhj.mvcproject.model.User; import cn.lhj.mvcproject.utils.JdbcUtils; public class UserServiceImp implements UserService { UserDao userdao = FactoryDao.getUserDao(); @Override public int save(User user) { // TODO Auto-generated method stub return userdao.save(user); } @Override public int deleteUserById(int id) { // TODO Auto-generated method stub return userdao.deleteUserById(id); } @Override public int updateUserById(User user) { // TODO Auto-generated method stub return userdao.updateUserById(user); } @Override public User get(int id) { // TODO Auto-generated method stub return userdao.get(id); } @Override public User getTransaction(int id) { // TODO Auto-generated method stub Connection conn = null; User user = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); user = userdao.get(conn, id); conn.commit(); }catch (Exception e) { JdbcUtils.rollbackTransaction(conn); e.printStackTrace(); }finally { JdbcUtils.closeConn(conn); } return user; } @Override public List<User> getListAll() { // TODO Auto-generated method stub return userdao.getListAll(); } @Override public int getCountByName(String username) { // TODO Auto-generated method stub return userdao.getCountByName(username); } @Override public List<User> query(String username, String address, String phoneno) { return userdao.query(username,address,phoneno); } @Override public User login(String username, String passwd) { // TODO Auto-generated method stub return userdao.getUserByUp(username,passwd); } } <file_sep>package cn.lhj.mvcproject.dao; import java.util.List; import cn.lhj.mvcproject.model.Ponline; public interface PonlineDao { public List<Ponline> getAllOnline();//查 public int insertOnline(Ponline ponline);//增 public int updateOnline(Ponline ponline);//改 public int deleteExpiresOnline(String ssid);//删 public Ponline getOnlineBySsid(String ssid);//查 } <file_sep>package cn.lhj.mvcproject.dao; public class FactoryDao { public static UserDao getUserDao() { return new UserDaoImpl(); } public static PonlineDao getPonlineDao() { return new PonlineImpl(); } } <file_sep>package cn.lhj.mvcproject.service; import java.util.List; import cn.lhj.mvcproject.model.Ponline; public interface PonlineService { public List<Ponline> getAllOnline();//查 public int insertOnline(Ponline ponline);//增 public int updateOnline(Ponline ponline);//改 public Ponline getOnlineBySsid(String ssid);//查 public void deleteExpiresOnline(List<Ponline> oList);//删 } <file_sep>package cn.lhj.mvcproject.test; import static org.junit.jupiter.api.Assertions.*; import java.util.Date; import java.util.Iterator; import java.util.List; import org.junit.jupiter.api.Test; import cn.lhj.mvcproject.dao.UserDao; import cn.lhj.mvcproject.dao.UserDaoImpl; import cn.lhj.mvcproject.model.User; import cn.lhj.mvcproject.utils.JdbcUtils; import java.sql.Connection; import java.sql.Timestamp; class UserDaoImplTest { UserDao userDao = new UserDaoImpl(); @Test void testSave() { User user = new User("bb", "12221111", "3434347456", "guanyaojiaoyulu37"); System.out.println(userDao.save(user)); } @Test void testDeleteUserById() { System.out.println(userDao.deleteUserById(56)); } @Test void testUpdateUserById() { User user = new User("bb", "12221111", "3434347456", "guanyaojiaoyulu37"); user.setId(5); System.out.println(userDao.updateUserById(user)); } @Test void testGetInt() { User user = userDao.get(6); System.out.println(user); } @Test void testGetConnectionInt() { Connection conn = null; User user = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); user = userDao.get(conn, 7); conn.commit(); }catch (Exception e) { JdbcUtils.rollbackTransaction(conn); e.printStackTrace(); }finally { JdbcUtils.closeConn(conn); } System.out.println(user); } @Test void testGetListAll() { List<User> list = userDao.getListAll(); Iterator<User> iterator = list.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } } @Test void testGetCountByName() { int rows = userDao.getCountByName("lhj"); System.out.println(rows); } } <file_sep>package cn.lhj.mvcproject.dao; import java.util.List; import cn.lhj.mvcproject.model.Ponline; public class PonlineImpl extends BaseDao<Ponline> implements PonlineDao{ @Override public List<Ponline> getAllOnline() { String sql = "select * from ponline"; List<Ponline> list = super.getList(sql); return list; } @Override public int insertOnline(Ponline ponline) { String sql = "insert into ponline(ssid,username,page,ip,time) values(?,?,?,?,?)"; return super.update(sql, ponline.getSsid(),ponline.getUsername(),ponline.getPage(),ponline.getIp(),ponline.getTime()); } @Override public int updateOnline(Ponline ponline) { String sql = "update ponline set username=?,page=?,ip=?,time=? where ssid=?"; return super.update(sql, ponline.getUsername(),ponline.getPage(),ponline.getIp(),ponline.getTime(),ponline.getSsid()); } @Override public int deleteExpiresOnline(String ssid) { String sql = "delete from ponline where ssid=?"; return super.update(sql, ssid); } @Override public Ponline getOnlineBySsid(String ssid) { String sql = "select * from ponline where ssid=?"; return super.get(sql, ssid); } }
503f39bd731714aa960f498d8090cf47233ce1da
[ "Java" ]
13
Java
lihaijian/mvcProject
cf6361fab75df43710887e0d9f285539951fb6b3
e72158d27a94150e81264f8252ae2754afddc1f3
refs/heads/master
<repo_name>PeterMcCormick/leonium<file_sep>/src/main/sites/friendproject/pages/HomePage.java package main.sites.friendproject.pages; import org.openqa.selenium.By; import main.sites.PageObject; import main.sites.AbstractTrial; public class HomePage extends PageObject { public final By byInputEmail1 = By.xpath("(.//input[@name='email'])[1]"); public final By byInputPassword1 = By.xpath("(.//input[@name='password'])[1]"); public final By byButtonLogIn = By.cssSelector("input[value='Log In']"); public final By byInputFirstName = By.cssSelector("input[name='first_name']"); public final By byInputLastName = By.cssSelector("input[name='last_name']"); public final By byInputEmail2 = By.xpath("(.//input[@name='email'])[2]"); public final By byInputPassword2 = By.xpath("(.//input[@name='password'])[2]"); public final By byButtonSignUp = By.cssSelector("input[@value='Sign Up']"); public HomePage(AbstractTrial runner) { super(runner); } public void login(String username, String password) { web.sendKeys(byInputEmail1, "<EMAIL>"); web.sendKeys(byInputPassword1, "<PASSWORD>"); } public void signUp(String firstname, String lastname, String email, String password) { web.sendKeys(byInputFirstName, firstname); web.sendKeys(byInputLastName, lastname); web.sendKeys(byInputEmail2, email); web.sendKeys(byInputPassword2, password); } } <file_sep>/src/main/sites/mail/pages/SignUpPage.java package main.sites.mail.pages; import org.openqa.selenium.By; import main.sites.PageObject; import main.sites.AbstractTrial; import main.utils.Utils; import main.utils.browserutils.BrowserReports; public class SignUpPage extends PageObject { public By byInputFirstName = By.xpath("(.//input)[2]"); public By byInputLastName = By.xpath("(.//input)[3]"); public By byInputDesiredEmail = By.xpath("(.//input)[4]"); public By byInputPassword = By.xpath("(.//input)[5]"); public By byInputConfirmPassword = By.xpath("(.//input)[6]"); public By byInputContactEmail = By.xpath("(.//input)[7]"); public By byInputSecurityAnswer = By.xpath("(.//input)[9]"); public By byButtonCreateAccount = By.xpath("(.//input)[11]"); public By bySelectGender = By.xpath("(.//select)[1]"); public By bySelectDobMonth = By.cssSelector("(.//select)[2]"); public By bySelectDobDay = By.xpath("(.//select)[3]"); public By bySelectDobYear = By.xpath("(.//select)[4]"); public By bySelectCountry = By.xpath("(.//select)[5]"); public By bySelectSecurityQuestion = By.xpath("(.//select)[7]"); public By byCheckBoxRecaptcha = By.xpath("[class='recaptcha-checkbox-checkmark']"); public SignUpPage(AbstractTrial runner) { super(runner); } public void initSelectors() { String inputPath = "(.//input)[%s]"; int offset1 = 0, offset2 = -1; try { web.wait.forVisibility(xp(inputPath, 2), 5); } catch (Exception e) { offset1 = 1; offset2 = 0; } this.byInputFirstName = xp(inputPath, 2 + offset1); this.byInputLastName = xp(inputPath, 3 + offset1); this.byInputDesiredEmail = xp(inputPath, 5 + offset1); this.byInputPassword = xp(inputPath, 6 + offset1); this.byInputConfirmPassword = xp(inputPath, 7 + offset1); Utils.printFields(this); } public By xp(String query, Object... args) { return By.xpath(String.format(query, args)); } public void signUp(String firstName, String lastName, String gender, String birthMonth, String birthDay, String birthYear, String country, String desiredEmail, String password, String contactEmail, String securityQuestion, String securityAnswer) { web.sendKeys(byInputLastName, lastName); web.selectByVisibleText(bySelectGender, gender); web.selectByVisibleText(bySelectDobMonth, birthMonth); web.selectByVisibleText(bySelectDobDay, birthDay); web.selectByVisibleText(bySelectDobYear, birthYear); web.selectByVisibleText(bySelectCountry, country); web.sendKeys(byInputDesiredEmail, desiredEmail); web.sendKeys(byInputPassword, <PASSWORD>); web.sendKeys(byInputConfirmPassword, <PASSWORD>); web.sendKeys(byInputContactEmail, contactEmail); web.selectByVisibleText(bySelectSecurityQuestion, securityQuestion); web.sendKeys(byInputSecurityAnswer, securityAnswer); web.click(byButtonCreateAccount); } public void signUp(String firstName, String lastName, String desiredEmail, String password) { BrowserReports bl = web.reports; initSelectors(); bl.reportInfo("First name1"); web.sendKeys(byInputFirstName, firstName); bl.reportInfo("Last name"); web.sendKeys(byInputLastName, lastName); bl.reportInfo("Desired email"); web.sendKeys(byInputDesiredEmail, desiredEmail); bl.reportInfo("Password"); web.sendKeys(byInputPassword, password); bl.reportInfo("Confirm password"); web.sendKeys(byInputConfirmPassword, password); bl.reportInfo("Gender"); web.selectByRandomIndex(bySelectGender); bl.reportInfo("Month"); web.selectByRandomIndex(web.getElements(By.cssSelector("select")).get(1)); bl.reportInfo("Year"); web.selectByVisibleText(bySelectDobYear, "19" + Utils.randint(50, 90)); bl.reportInfo("Day"); web.selectByRandomIndex(bySelectDobDay); bl.reportInfo("Country"); web.selectByRandomIndex(bySelectCountry); bl.reportInfo("Security question"); web.selectByRandomIndex(bySelectSecurityQuestion); bl.reportInfo("Security answer"); web.sendKeys(byInputSecurityAnswer, "securityAnswer"); bl.reportInfo("Create account"); web.click(byButtonCreateAccount); } }<file_sep>/src/main/sites/PageObject.java package main.sites; import org.openqa.selenium.By; import main.utils.Utils; import main.utils.browserutils.BrowserHandler; public abstract class PageObject { protected AbstractTrial runner; protected BrowserHandler web; public PageObject(AbstractTrial runner) { this.runner = runner; this.web = runner.web; } public By[] getDeclaredBys() { return Utils.toArray(Utils.getFieldValues(this, By.class)); } public void highlightElements() { boolean defaultOption = web.options.continueOnNoSuchElement.getValue(); web.options.continueOnNoSuchElement.setValue(true); web.highlightElements(getDeclaredBys()); web.options.continueOnNoSuchElement.setValue(defaultOption); } } <file_sep>/src/main/utils/browserutils/BrowserBot.java package main.utils.browserutils; import java.awt.AWTException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.Command; import org.openqa.selenium.remote.DriverCommand; import org.openqa.selenium.remote.RemoteWebDriver; import com.sun.glass.events.KeyEvent; import main.utils.Utils; public class BrowserBot { public class UrlListener extends Thread { private WebDriver driver; public UrlListener(WebDriver driver) { this.driver = driver; } public void run() { try { String prevUrl = driver.getCurrentUrl(); while (true) { String currentUrl = driver.getCurrentUrl(); if (!currentUrl.equals(prevUrl)) { while (!web.getPageLoadState().equals("complete")) { continue; } logger.screenshotPage(); prevUrl = driver.getCurrentUrl(); } } } catch (Exception e) { } } } private final BrowserHandler web; private final BrowserReports logger; private final Actions actions; private final Robot robot; private final Runtime runtime; public BrowserBot(BrowserHandler web) { this.web = web; this.logger = web.reports; this.actions = new Actions(web.driver); this.robot = getRobot(); this.runtime = Runtime.getRuntime(); new UrlListener(web.driver).start(); } public File screenshotElement(WebElement we) { // TODO - TEST moveToElement(we); Point p = we.getLocation(); Dimension d = we.getSize(); activateScreen(); BufferedImage bi = robot.createScreenCapture(new Rectangle(p.getX(), p.getY(), d.getWidth(), d.getHeight())); String eleName = Utils.removeChars(web.webElementToString(we), "~!@#$&%^*':<>\\/()[]{}") + " - "; String fileName = eleName + System.currentTimeMillis() + ".png"; String directory = logger.getReportsPath(); File file = new File(directory + fileName); logger.reportInfo(logger.getTest().addScreenCapture(file.getName()) + logger.colorTag("green", file.getName())); try { ImageIO.write(bi, "png", file); } catch (IOException e) { logger.reportStackTrace(e); } return file; } public void screenshot() { // TODO - return File ? RemoteWebDriver rwd = ((RemoteWebDriver) web.driver); try { rwd.getCommandExecutor().execute(new Command(rwd.getSessionId(), DriverCommand.ELEMENT_SCREENSHOT)); } catch (IOException e) { logger.reportStackTrace(e); } } public void activateScreen() { // Store the current window handle String currentWindowHandle = web.driver.getWindowHandle(); // run your javascript and alert code ((JavascriptExecutor) web.driver).executeScript("alert('Test')"); web.switchTo.alert().accept(); // Switch back to to the window using the handle saved earlier web.switchTo.window(currentWindowHandle); } public Actions moveToElement(WebElement we) { return perform(actions.moveToElement(we)); } private Actions perform(Actions action) { action.build().perform(); return action; } private Robot getRobot() { try { return new Robot(); } catch (AWTException e) { return null; } } } <file_sep>/src/main/sites/runescape/pages/LandingPage.java package main.sites.runescape.pages; import org.openqa.selenium.By; import main.sites.PageObject; import main.sites.AbstractTrial; public class LandingPage extends PageObject { public final By byHeaderLinks = By.cssSelector(".primary>li>a"); public LandingPage(AbstractTrial runner) { super(runner); } } <file_sep>/src/main/utils/browserutils/browserwrappers/PhantomBrowser.java package main.utils.browserutils.browserwrappers; import java.util.ArrayList; import java.util.logging.Level; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.Augmenter; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import main.utils.Utils; public class PhantomBrowser extends PhantomJSDriver { static { String userAgent = "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.41 Safari/535.1"; System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "info"); System.setProperty("org.openqa.selenium.remote.RemoteWebDriver", "info"); System.setProperty("phantomjs.page.settings.userAgent", userAgent); } public PhantomBrowser(DesiredCapabilities caps) { super(DesiredCapabilities.phantomjs().merge(caps)); } public PhantomBrowser() { super(desiredCapabilities()); this.setLogLevel(Level.OFF); getErrorHandler().setIncludeServerErrors(false); } private static DesiredCapabilities desiredCapabilities() { DesiredCapabilities caps = new DesiredCapabilities(); ArrayList<String> cliArgsCap = new ArrayList<String>(); cliArgsCap.add("--webdriver-loglevel=NONE"); caps.setJavascriptEnabled(true); caps.setCapability("takesScreenshot", true); caps.setCapability("screen-resolution", "1280x1024"); caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "./resources/phantomjs.exe"); caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap); Utils.disableLogging(PhantomJSDriverService.class, RemoteWebDriver.class, Augmenter.class); return DesiredCapabilities.phantomjs().merge(caps); } }<file_sep>/src/main/MainDriver.java package main; import org.openqa.selenium.firefox.FirefoxDriver; import main.sites.AbstractTrial; import main.sites.addressgenerator.trials.AddressGeneratorDemo0; import main.sites.friendproject.trials.FPDemo1; import main.sites.hotnewhiphop.trials.HNHdemo1; import main.sites.instagram.trials.IGTdemo1; import main.sites.mail.trials.MailDemo1; import main.sites.mail.trials.MailDemo2; import main.sites.msn.trials.MsnDemo1; import main.sites.smartystreets.trials.SmartyStreetDemo0; import main.sites.twitter.trials.TwitterDemo0; import main.utils.Utils; public class MainDriver { public static void main(String[] args) { try { // twitterTest(); // mailTest2b(); // fpTest(); // hnhhTest(); smartyStreetTest(); // addressGeneratorTest(); // mailTest1(); // msnTest(); // igTest(); } catch (Exception e) { Utils.printStackTrace(e); } } public static void addressGeneratorTest() { new AddressGeneratorDemo0().run(); } public static void smartyStreetTest() { new SmartyStreetDemo0().run(); } public static void fpTest() { new FPDemo1("http://www.friendproject.net/").run(); } public static void hnhhTest() { new HNHdemo1().run(); } public static void igTest() { new IGTdemo1("https://www.instagram.com/").run(); } public static void msnTest() { new MsnDemo1("http://www.msn.com/").run(); } public static void twitterTest() { new TwitterDemo0("https://twitter.com/").run(); } public static void mailTest2a() { new MailDemo2("http://mail.com/").run(); } public static void mailTest2b() { String url = "https://service.mail.com/registration.html?edition=us&lang=en&#.7518-header-signup2-1"; AbstractTrial t = null; for (int i = 0; i < 1; i++) { t = new MailDemo2(url); t.start(); } while (t.isAlive()) { } Utils.openFile(t.getLoggerPath() + "/Result.html"); } public static void mailTest1() { new MailDemo1(new FirefoxDriver(), "https://www.google.com").run(); } } <file_sep>/src/main/sites/mail/pages/ContactInfoPage.java package main.sites.mail.pages; import org.openqa.selenium.By; import main.sites.PageObject; import main.sites.AbstractTrial; public class ContactInfoPage extends PageObject { public By contactEmail = By.id("id5a"); public By submit = By.id("id6c"); public By contactForm = By.id("#id85"); public ContactInfoPage(AbstractTrial runner) { super(runner); } } <file_sep>/src/main/utils/metadata/ActorMetaData.java package main.utils.metadata; public class ActorMetaData extends AbstractActorMetaData { public ActorMetaData(String firstName, String lastName, String email, String addressLine1, String addressLine2, String city, String state, String zipcode, int socialSecurityNumber) { super(firstName, lastName, email, addressLine1, addressLine2, city, state, zipcode, socialSecurityNumber); } } <file_sep>/src/main/sites/youtube/pages/HomePage.java package main.sites.youtube.pages; import main.sites.PageObject; import main.sites.AbstractTrial; public class HomePage extends PageObject { public HomePage(AbstractTrial runner) { super(runner); } } <file_sep>/src/main/sites/msn/trials/MsnDemo1.java package main.sites.msn.trials; import org.openqa.selenium.WebDriver; import main.sites.msn.AbstractMsnTrial; public class MsnDemo1 extends AbstractMsnTrial { public MsnDemo1(String url) { super(url); } public MsnDemo1(WebDriver driver, String url) { super(driver, url); } @Override protected void test() { web.navigateTo(url); web.sendKeys(landingPage.bySearchBar, "Hello world!"); web.click(landingPage.byButtonSearch); // web.wait.forPageLoad(30); // logger.screenshotPage(driver.getCurrentUrl()); } } <file_sep>/src/main/utils/browserutils/browserwrappers/ChromeBrowser.java package main.utils.browserutils.browserwrappers; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; public class ChromeBrowser extends ChromeDriver { private static String executablePath = "./resources/chromedriver.exe"; static { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "info"); System.setProperty("org.openqa.selenium.remote.RemoteWebDriver", "info"); System.setProperty("webdriver.chrome.driver", executablePath); } public ChromeBrowser() { this(defaultCapabilities()); } public ChromeBrowser(DesiredCapabilities caps) { super(caps); } private static DesiredCapabilities defaultCapabilities() { ChromeOptions options = new ChromeOptions(); DesiredCapabilities caps = new DesiredCapabilities(); options.addArguments("start-maximized"); caps.setJavascriptEnabled(true); caps.setCapability("takesScreenshot", true); caps.setCapability("screen-resolution", "1280x1024"); caps.setCapability(CapabilityType.TAKES_SCREENSHOT, true); caps.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true); caps.setCapability(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, executablePath); return caps; } }<file_sep>/src/main/sites/instagram/pages/UserPage.java package main.sites.instagram.pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import main.sites.PageObject; import main.sites.AbstractTrial; public class UserPage extends PageObject { public By followerList = By.xpath("//span[@id='react-root']/section/main/article/header/div[2]/ul/li[2]/a/span[3]"); public By followers = By.cssSelector("._jvpff._k2yal._csba8._k0ujq._nv5lf"); public UserPage(AbstractTrial runner) { super(runner); } public boolean viewUser(String username) { return web.navigateTo("instagram.com/" + username + "/"); } public void viewUserFollowers(String username) { viewUser(username); web.click(followerList); } public void followUserList() { List<WebElement> followButtons = web.getElements(followers); while (true) { for (WebElement followButton : followButtons) { try { String status = followButton.getText().toLowerCase(); if (status.equals("follow")) { web.click(followButton); } web.sendKeys(followButton, Keys.PAGE_DOWN.name()); followButtons = web.getElements(followers); } catch (Exception e) { runner.reports.reportStackTrace(e); } } } } }<file_sep>/src/main/sites/twitter/pages/LandingPage.java package main.sites.twitter.pages; import org.openqa.selenium.By; import main.sites.PageObject; import main.sites.AbstractTrial; public class LandingPage extends PageObject { public final By byButtonLogin0 = By.cssSelector(".Button.StreamsLogin.js-login"); public final By byButtonLogin1 = By.cssSelector(".submit.btn.primary-btn.js-submit"); public final By byInputUsername = By.cssSelector("[name='session[username_or_email]']"); public final By byInputPassword = By.cssSelector("[name='session[password]']"); public LandingPage(AbstractTrial runner) { super(runner); } public void login(String username, String password) { web.click(byButtonLogin0); web.sendKeys(byInputUsername, username); web.sendKeys(byInputPassword, <PASSWORD>); web.click(byButtonLogin1); } } <file_sep>/src/main/utils/browserutils/With.java package main.utils.browserutils; import org.openqa.selenium.By; /** * @purpose Mechanism to locate elements within a document */ public abstract class With { /** * @param text The value of the "text" to search for * @return a By which locates button elements by the value of the text */ public static By buttonText(String text) { return tagAndText("button", text); } /** * @param attribute the name of the attribute to search for * @param value the value of the attribute to search for * @return a By object which locates elements by the value of the attribute */ public static By attributeValue(String attribute, String value) { return By.xpath(String.format("(.//*[contains(@%s, '%s')])", attribute, value)); } /** * @param id the value of the "id" attribute to search for * @return a By object which locates elements by the value of the attribute. */ public static By attribute(String attribute) { return By.cssSelector(String.format("[%s]")); } /** * @param text The value of the "text" to search for * @return a By which locates elements by the value of the text */ public static By text(String text) { return tagAndText("*", text); } /** * @param tag The tag to search for * @param text The text-value to search for * @return a By which locates button elements by the tag and text-value */ public static By tagAndText(String tag, String text) { return By.xpath(String.format(".//%s[contains(text(), '%s')]", tag, text)); } /** * @param tag the tag to search for * @param attribute the name of the attribute to search for * @param value the value of the attribute to search for * @return a By object which locates elements with specified tag and value of the attribute */ public static By tagAttributeValue(String tag, String attribute, String value) { return By.xpath(String.format(".//%s[@%s='%s']", tag, attribute, value)); } /** * @param tag the tag to search for * @param attribute the name of the attribute to search for * @return a By object which locates elements with specified tag and attribute */ public static By tagAttribute(String tag, String attribute) { return By.xpath(String.format(".//%s['%s']", tag, attribute)); } }<file_sep>/src/main/utils/metadata/AbstractActorMetaData.java package main.utils.metadata; import main.utils.Utils; public abstract class AbstractActorMetaData { private String firstName; private String lastName; private String email; private String addressLine1; private String addressLine2; private String city; private String state; private String zipcode; private int socialSecurityNumber; public int getSocialSecurityNumber() { return socialSecurityNumber; } public AbstractActorMetaData(String firstName, String lastName, String email, String addressLine1, String addressLine2, String city, String state, String zipcode, int socialSecurityNumber) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; this.city = city; this.state = state; this.zipcode = zipcode; this.socialSecurityNumber = socialSecurityNumber; } @SuppressWarnings("unused") private AbstractActorMetaData() { } public String getAddressLine1() { return addressLine1; } public String getAddressLine2() { return addressLine2; } public String getCity() { return city; } public String getEmail() { return email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getState() { return state; } public String getZipcode() { return zipcode; } public static Integer createSocialSecurityNumber() { return Utils.randint(10000000, 999999999); } public static String createUniqueName() { String name = Utils.getColumnVal(System.nanoTime()); String firstChar = Character.toString(name.charAt(0)); return name.replaceFirst(firstChar, firstChar.toUpperCase()); } public static String createAddressLine() { return String.format("%s %s Rd", createUniqueName(), createUniqueName()); } public static String createEmailAddress(String firstName, String lastName) { String milliseed = Long.toString(System.currentTimeMillis()); return String.format("%s.<EMAIL>", firstName, lastName, milliseed); } }<file_sep>/src/main/sites/hotnewhiphop/AbstractHNHipHopTrial.java package main.sites.hotnewhiphop; import main.sites.AbstractTrial; import main.sites.hotnewhiphop.pages.HomePage; public abstract class AbstractHNHipHopTrial extends AbstractTrial { protected final HomePage homePage = new HomePage(this); public AbstractHNHipHopTrial() { super("http://www.hotnewhiphop.com/"); } } <file_sep>/src/main/sites/instagram/pages/LandingPage.java package main.sites.instagram.pages; import org.openqa.selenium.By; import main.sites.PageObject; import main.sites.instagram.AbstractInstagramTrial; public class LandingPage extends PageObject { public By login = By.linkText("Log in"); public By username = By.name("username"); public By password = By.name("<PASSWORD>"); public By signin = By.cssSelector("button"); public By loginerror = By.id("slfErrorAlert"); private String url; public LandingPage(AbstractInstagramTrial trial) { super(trial); this.url = trial.driver.getCurrentUrl(); } public void login() { login("insta.haq", "<PASSWORD>"); } public void login(String user, String pass) { forceLogin(user, pass, false); } public void forceLogin(String user, String pass, boolean isForced) { web.deleteAllCookies(); web.click(login); web.sendKeys(username, user); web.sendKeys(password, <PASSWORD>); web.click(signin); if (web.getElement(loginerror) != null && isForced) { web.navigateTo(url); forceLogin(user, pass, isForced); } } } <file_sep>/src/main/sites/hotnewhiphop/trials/HNHdemo1.java package main.sites.hotnewhiphop.trials; import main.sites.hotnewhiphop.AbstractHNHipHopTrial; public class HNHdemo1 extends AbstractHNHipHopTrial { public HNHdemo1() { super(); } @Override protected void setup() { } @Override protected void test() { web.click(homePage.byButtonMoreSongs); web.getTexts(homePage.bySongChart); } }<file_sep>/src/main/utils/browserutils/BrowserReports.java package main.utils.browserutils; import java.io.File; import java.util.Arrays; import java.util.Collections; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.Augmenter; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import main.sites.AbstractTrial; import main.utils.Utils; public class BrowserReports extends ExtentReports { private final TakesScreenshot browserCam; private final ExtentTest extentTest; private final String reportsPath; public BrowserReports(String reportsPath, Class<? extends AbstractTrial> trial, WebDriver driver) { super(reportsPath + "/Result.html", false); this.reportsPath = reportsPath; this.extentTest = startTest(getTrialName(trial)); this.browserCam = (TakesScreenshot) new Augmenter().augment(driver); Utils.createMissingDirectories(reportsPath); } public String colorTag(String color, String text) { return "<font color = \"" + color + "\">" + text + "</font>"; } public synchronized void endTest() { try { this.flush(); this.endTest(extentTest); } catch (Exception e) { Utils.printStackTrace(e); } } public String getReportsPath() { return reportsPath; } public ExtentTest getTest() { return extentTest; } public String getTestName() { return extentTest.getTest().getName(); } private String getTrialName(Class<? extends AbstractTrial> trial) { return Utils.removeChars(trial.getSimpleName(), "!@#$%^&*()_+:{}"); } private String klickable(StackTraceElement ste) { String className = ste.getClassName(); String methodName = ste.getMethodName(); className = className.substring(className.lastIndexOf('.') + 1); methodName = Utils.strsNotNull(methodName) ? methodName : "constructor"; return "(" + className + ".java:" + ste.getLineNumber() + ")." + methodName; } // @return = boolean success // @optional parameter: testName public boolean reportCriticalEvent(boolean success) { return reportCriticalEvent(success, getTestName()); } // @return = boolean success // @optional parameter: event description // wrapper method for reportCriticalEvent(success, pass, fail); public boolean reportCriticalEvent(boolean success, String event) { return reportCriticalEvent(success, event, event); } // @return = boolean success // reports outcome of critical-event // the outcome of this method call determines the success of the test public boolean reportCriticalEvent(boolean success, String pass, String fail) { if (success) { extentTest.log(LogStatus.PASS, colorTag("blue", pass)); } else { extentTest.log(LogStatus.FAIL, colorTag("red", "<strike>" + fail + "</strike>")); } Utils.printR(removeTags(pass.replace("<br>", "\n\t")) + " = " + success); return success; } // Specifically log data-retrieval & data-capture information public String reportDataRetrieval(String description) { return reportInfo(colorTag("purple", description)); } // Add log dialogue to report corresponding to specified exception public String reportStackTrace(Exception e) { StringBuilder result = new StringBuilder(); StackTraceElement ste = Utils.lastMethodCall(3); String exceptionName = colorTag("red", e.getClass().getSimpleName()); String header = exceptionName + " caught by " + klickable(ste); String tmessage = e.getMessage() == null ? "Exception Message = null" : e.getMessage(); String[] details = tmessage.split("\n"); String delimiter = "<br>"; String delimiter2 = delimiter + delimiter; String message = details[0]; String info = String.join("\n", Arrays.copyOfRange(details, 1, details.length)).replace("\n", "<br>"); result.append(message + delimiter2 + info + delimiter2); result.append("<b><u>Stacktrace:</b></u>"); StackTraceElement[] stes = e.getStackTrace(); Collections.reverse(Arrays.asList(stes)); for (int i = 1; i < stes.length; i++) { StackTraceElement sti = stes[i]; if (sti.getLineNumber() < 0) { continue; } result.append(delimiter + ">> " + klickable(sti)); } return reportInfo("<b><u>" + header + "<br></b></u>" + result.toString()); } // Log multiple details delimited by line break public String reportInfo(String baseString, Object... args) { String info = String.format(baseString, args); try { Utils.printR("\n\nLogging information..."); Utils.printR(removeTags(info.replace("<br>", "\n\t"))); info = Utils.removeStrings(info, " = false", " = true"); extentTest.log(LogStatus.INFO, info); } catch (Exception e) { } return info; } public boolean reportMinorEvent(boolean outcome, String passMessage) { String failMessage = colorTag("red", "<strike>" + passMessage + "</strike>") + " = " + outcome; return reportMinorEvent(outcome, passMessage, failMessage); } // log outcome of non-critical-event public boolean reportMinorEvent(boolean outcome, String passMessage, String failMessage) { if (outcome) { String description = colorTag("blue", passMessage); Utils.printR(removeTags(description.replace("<br>", "\n\t"))); description = description.replace(" = false", "").replace(" = true", ""); extentTest.log(LogStatus.PASS, description); } else { reportInfo(colorTag("red", failMessage)); } return outcome; } // remove HTML tags from specified string public String removeTags(String html) { return html.replaceAll("\\<[^>]*>", ""); } // Create screenshot file private File screenshot(String fileName) { try { fileName = Utils.removeChars(fileName, "~!@#$&%^*':<>\\/()[]{}") + "_" + System.currentTimeMillis(); File screenshot = browserCam.getScreenshotAs(OutputType.FILE); new File(reportsPath).mkdirs(); File f = new File(Utils.printR(reportsPath + "\\" + fileName + ".png")); FileUtils.copyFile(screenshot, f); return f; } catch (Exception e) { reportStackTrace(e); } return null; } public void screenshotPage() { screenshotPage(getTestName()); } public void screenshotPage(String testDescription) { try { reportInfo(extentTest.addScreenCapture(screenshot(testDescription).getName()) + testDescription); } catch (Exception e) { reportStackTrace(e); } } public boolean reportTextContains(String dynamicVal, String expectedVal) { String passMessage = "'" + dynamicVal + "' contains '" + expectedVal + "'"; String failMessage = "'" + dynamicVal + "' does not contain '" + expectedVal + "'"; return reportMinorEvent(expectedVal.contains(dynamicVal), passMessage, failMessage); } public boolean reportTextEquals(String dynamicVal, String expectedVal) { String passMessage = "'" + dynamicVal + "' matches '" + expectedVal + "'"; String failMessage = "'" + dynamicVal + "' does not match '" + expectedVal + "'"; return reportMinorEvent(expectedVal.equals(dynamicVal), passMessage, failMessage); } }
90b6003cf335100bfa93bf5623af150a9bc25e74
[ "Java" ]
20
Java
PeterMcCormick/leonium
080be69f9eb03ed0497d2b580a09a51fac6986a2
06d1532a9ffc1953991ccac739be3439dc7dc3a6
refs/heads/master
<repo_name>sumanthkumarps/ViewPageHolder<file_sep>/app/src/main/java/com/effone/viewpageholder/model/Items.java package com.effone.viewpageholder.model; import java.io.Serializable; import java.util.ArrayList; /** * Created by sumanth.peddinti on 5/10/2017. */ public class Items implements Serializable { private ArrayList<Content> content; private String name; public ArrayList<Content> getContent () { return content; } public void setContent (ArrayList<Content> content) { this.content = content; } public String getName () { return name; } public void setName (String name) { this.name = name; } } <file_sep>/app/src/main/java/com/effone/viewpageholder/common/URL.java package com.effone.viewpageholder.common; /** * Created by sumanth.peddinti on 5/12/2017. */ public class URL { public static final String menu_url="http://192.168.2.44/android_web_api/Sample.json"; public static final String place_order_url="http://192.168.2.44/android_web_api/include/PlaceOrder.php"; public static final String get_placed_order="http://192.168.2.44/android_web_api/include/getPlacedOrder.php?order_id="; } <file_sep>/app/src/main/java/com/effone/viewpageholder/model/Content.java package com.effone.viewpageholder.model; import java.io.Serializable; /** * Created by sumanth.peddinti on 5/10/2017. */ public class Content implements Serializable { private String ingredients; private int menu_item_id; private float price; private String name; public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } public int getMenu_item_id() { return menu_item_id; } public void setMenu_item_id(int menu_item_id) { this.menu_item_id = menu_item_id; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/app/src/main/java/com/effone/viewpageholder/model/Sample.java package com.effone.viewpageholder.model; /** * Created by sumanth.peddinti on 5/10/2017. */ public class Sample { private Menu Menu; public Menu getMenu () { return Menu; } public void setMenu (Menu Menu) { this.Menu = Menu; } } <file_sep>/app/src/main/java/com/effone/viewpageholder/model/Menu_type.java package com.effone.viewpageholder.model; /** * Created by sumanth.peddinti on 5/22/2017. */ public class Menu_type { private Categories[] categories; private String menu_cata_id; private String menu_cata_type; public Categories[] getCategories () { return categories; } public void setCategories (Categories[] categories) { this.categories = categories; } public String getMenu_cata_id () { return menu_cata_id; } public void setMenu_cata_id (String menu_cata_id) { this.menu_cata_id = menu_cata_id; } public String getMenu_cata_type () { return menu_cata_type; } public void setMenu_cata_type (String menu_cata_type) { this.menu_cata_type = menu_cata_type; } } <file_sep>/app/src/main/java/com/effone/viewpageholder/model/Categories.java package com.effone.viewpageholder.model; import java.util.ArrayList; /** * Created by sumanth.peddinti on 5/10/2017. */ public class Categories { private ArrayList<Items> Items; private String name; public ArrayList<Items> getItems () { return Items; } public void setItems ( ArrayList<Items> Items) { this.Items = Items; } public String getName () { return name; } public void setName (String name) { this.name = name; } } <file_sep>/app/src/main/java/com/effone/viewpageholder/model/Menu.java package com.effone.viewpageholder.model; /** * Created by sumanth.peddinti on 5/10/2017. */ public class Menu { private Menu_type[] menu_type; private String restaurant_id; private String location_id; public Menu_type[] getMenu_type () { return menu_type; } public void setMenu_type (Menu_type[] menu_type) { this.menu_type = menu_type; } public String getRestaurant_id () { return restaurant_id; } public void setRestaurant_id (String restaurant_id) { this.restaurant_id = restaurant_id; } public String getLocation_id () { return location_id; } public void setLocation_id (String location_id) { this.location_id = location_id; } }
4950d63358a563ada9617b897320898f3a3602b6
[ "Java" ]
7
Java
sumanthkumarps/ViewPageHolder
87e91570c85cd91f15f64184697dda1dd8226362
a16bc5e97f5a4877422ba13acafcfe4aea39d554
refs/heads/master
<repo_name>marcianobarros20/python4D<file_sep>/lib4d_sql/communication.c #include "fourd.h" #include "fourd_int.h" #ifdef WIN32 #define EINPROGRESS WSAEWOULDBLOCK #else #include <fcntl.h> #endif long frecv(SOCKET s,unsigned char *buf,int len,int flags) { int rec=0; long iResult=0; do{ iResult=recv(s,buf+rec,len-rec, 0); if(iResult<0){ return iResult; }else { rec+=iResult; } }while(rec<len); return rec; } int socket_connect(FOURD *cnx,const char *host,unsigned int port) { struct addrinfo *result = NULL, *ptr = NULL, hints; int iResult=0; char sport[50]; sprintf_s(sport,50,"%d",port); //initialize Hints ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port iResult = getaddrinfo(host, sport, &hints, &result); if ( iResult != 0 ) { if (VERBOSE == 1) Printf("getaddrinfo failed: %d : %s\n", iResult,gai_strerror(iResult)); cnx->error_code=-iResult; strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,gai_strerror(iResult),ERROR_STRING_LENGTH); return 1; } // Attempt to connect to the first address returned by // the call to getaddrinfo ptr=result; // Create a SOCKET for connecting to server cnx->socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (cnx->socket == INVALID_SOCKET) { if (VERBOSE == 1) Printf("Error at socket(): %ld\n", WSAGetLastError()); cnx->error_code=-WSAGetLastError(); strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Unable to create socket",ERROR_STRING_LENGTH); freeaddrinfo(result); return 1; } // Connect to server. iResult = connect( cnx->socket, ptr->ai_addr, (int)ptr->ai_addrlen); if (iResult == SOCKET_ERROR) { if (VERBOSE == 1) Printf("Error at socket(): %ld\n", WSAGetLastError()); cnx->error_code=-WSAGetLastError(); strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Unable to connect to server",ERROR_STRING_LENGTH); freeaddrinfo(result); closesocket(cnx->socket); cnx->socket = INVALID_SOCKET; return 1; } // Should really try the next address returned by getaddrinfo // if the connect call failed // But for this simple example we just free the resources // returned by getaddrinfo and print an error message freeaddrinfo(result); if (cnx->socket == INVALID_SOCKET) { if (VERBOSE == 1) Printf("Unable to connect to server!\n"); cnx->error_code=-1; strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Unable to connect to server",ERROR_STRING_LENGTH); return 1; } return 0; } void socket_disconnect(FOURD *cnx) { #ifdef WIN32 iResult = shutdown(cnx->socket, SD_SEND); if (iResult == SOCKET_ERROR) { if (VERBOSE == 1) Printf("Socket disconnect failed: %d\n", WSAGetLastError()); closesocket(cnx->socket); cnx->connected=0; return ; } #endif closesocket(cnx->socket); cnx->connected=0; } int socket_send(FOURD *cnx,const char*msg) { long iResult; if (VERBOSE == 1) Printf("Send:\n%s",msg); iResult = send( cnx->socket, msg, (int)strlen(msg), 0 ); if (iResult == SOCKET_ERROR) { if (VERBOSE == 1) Printf("Send failed: %d\n", WSAGetLastError()); socket_disconnect(cnx); return 1; } return 0; } int socket_send_data(FOURD *cnx,const char*msg,int len) { long iResult; if (VERBOSE == 1) { Printf("Send:%d bytes\n",len); PrintData(msg,len); Printf("\n"); } // Send an initial buffer iResult = send( cnx->socket, msg, len, 0 ); if (iResult == SOCKET_ERROR) { if (VERBOSE == 1) Printf("Send failed: %d\n", WSAGetLastError()); socket_disconnect(cnx); return 1; } return 0; } int socket_receiv_header(FOURD *cnx,FOURD_RESULT *state) { long iResult=0; int offset=0; int len=0; int crlf=0; int grow_size=HEADER_GROW_SIZE; int new_size=grow_size; //allocate some space to start with state->header=calloc(sizeof(char),new_size); //read the HEADER only do { offset+=iResult; iResult = recv(cnx->socket,state->header+offset,1, 0); len+=iResult; if(len>new_size-5){ //header storage nearly full. Allocate more. new_size=new_size+sizeof(char)*grow_size; state->header=realloc(state->header,new_size); } if(len>3) { if(state->header[offset-3]=='\r' &&state->header[offset-2]=='\n' &&state->header[offset-1]=='\r' &&state->header[offset ]=='\n') crlf=1; } }while(iResult>0 && !crlf); if(!crlf) { if (VERBOSE == 1) Printf("Error: Header-end not found\n"); return 1; } state->header[len]=0; state->header_size=len; if (VERBOSE == 1) Printf("Receive:\n%s",state->header); //there we must add reading data //before analyse header //see COLUMN-TYPES section return 0; } int socket_receiv_data(FOURD *cnx,FOURD_RESULT *state) { long iResult=0; int len=0; //int end_row=0; unsigned int nbCol=state->row_type.nbColumn; unsigned int nbRow=state->row_count_sent; unsigned int r,c; FOURD_TYPE *colType=NULL; FOURD_ELEMENT *pElmt=NULL; unsigned char status_code=0; //int elmt_size=0; int elmts_offset=0; if (VERBOSE == 1) Printf("---Debuging the socket_receiv_data\n"); colType=calloc(nbCol,sizeof(FOURD_TYPE)); //bufferize Column type for(c=0;c<state->row_type.nbColumn;c++) colType[c]=state->row_type.Column[c].type; if (VERBOSE == 1) Printf("nbCol*nbRow:%d\n",nbCol*nbRow); /* allocate nbElmt in state->elmt */ state->elmt=calloc(nbCol*nbRow,sizeof(FOURD_ELEMENT)); if (VERBOSE == 1){ Printf("Debut de socket_receiv_data\n"); Printf("state->row_count:%d\t\tstate->row_count_sent:%d\n",state->row_count,state->row_count_sent); Printf("NbRow to read: %d\n",nbRow); } /* read all rows */ for(r=0;r<nbRow;r++) { /* read status_code and row_id */ if(state->updateability) /* rowId is send only if row updateablisity */ { int row_id=0; status_code=0; iResult = frecv(cnx->socket,&status_code,sizeof(status_code), 0); if (VERBOSE == 1) Printf("status_code for row:0x%X\n",status_code); len+=iResult; switch(status_code) { case '0': break; case '1': /* pElmt->elmt=calloc(vk_sizeof(colType[0]),1); */ iResult = frecv(cnx->socket,(unsigned char*)&row_id,sizeof(row_id), 0); if (VERBOSE == 1) Printf("row_id:%d\n",row_id); len+=iResult; break; case '2': if (VERBOSE == 1) Printferr("Error during reading data\n"); frecv(cnx->socket,(unsigned char*)&(state->error_code),sizeof(state->error_code), 0); free(colType); //before returning, free coll type return 1; /* return on error */ default: if (VERBOSE == 1) Printferr("Status code 0x%X not supported in data at row %d column %d\n",status_code,(elmts_offset-c+1)/nbCol+1,c+1); free(colType); state->error_code=-1; sprintf_s(state->error_string,ERROR_STRING_LENGTH,"Status code not supported",ERROR_STRING_LENGTH); return 1; } } else { if (VERBOSE == 1) Printf("Not read rowid\n"); } /* read all columns */ for(c=0;c<nbCol;c++,elmts_offset++) { pElmt=&(state->elmt[elmts_offset]); pElmt->type=colType[c]; //read column status code status_code=0; iResult = frecv(cnx->socket,&status_code,1, 0); if (VERBOSE == 1) Printf("Status: %2X\n",status_code); len+=iResult; switch(status_code) { case '2'://error if (VERBOSE == 1) Printferr("Error during reading data\n"); frecv(cnx->socket,(unsigned char*)&(state->error_code),sizeof(state->error_code), 0); free(colType); return 1; case '0'://null value if (VERBOSE == 1) Printf("Read null value\n"); pElmt->null=1; break; case '1'://value pElmt->null=0; switch(colType[c]) { case VK_BOOLEAN: case VK_BYTE: case VK_WORD: case VK_LONG: case VK_LONG8: case VK_REAL: case VK_DURATION: pElmt->pValue=calloc(1,vk_sizeof(colType[c])); iResult = frecv(cnx->socket,(pElmt->pValue),vk_sizeof(colType[c]), 0); len+=iResult; if (VERBOSE == 1) Printf("Long: %d\n",*((int*)pElmt->pValue)); break; case VK_TIMESTAMP: { FOURD_TIMESTAMP *tmp; tmp=calloc(1,sizeof(FOURD_TIMESTAMP)); pElmt->pValue=tmp; iResult = frecv(cnx->socket,(unsigned char*)&(tmp->year),2, 0); if (VERBOSE == 1) Printf("year: %04X",tmp->year); len+=iResult; iResult = frecv(cnx->socket,(unsigned char*)&(tmp->mounth),1, 0); if (VERBOSE == 1) Printf(" mounth: %02X",tmp->mounth); len+=iResult; iResult = frecv(cnx->socket,(unsigned char*)&(tmp->day),1, 0); if (VERBOSE == 1) Printf(" day: %02X",tmp->day); len+=iResult; iResult = frecv(cnx->socket,(unsigned char*)&(tmp->milli),4, 0); if (VERBOSE == 1) Printf(" milli: %08X\n",tmp->milli); len+=iResult; } break; case VK_FLOAT: { //int exp;char sign;int data_length;void* data; FOURD_FLOAT *tmp; tmp=calloc(1,sizeof(FOURD_FLOAT)); pElmt->pValue=tmp; iResult = frecv(cnx->socket,(unsigned char*)&(tmp->exp),4, 0); len+=iResult; if (VERBOSE == 1) Printf("Exp: %X",tmp->exp); iResult = frecv(cnx->socket,(unsigned char*)&(tmp->sign),1, 0); len+=iResult; if (VERBOSE == 1) Printf(" sign: %X",tmp->exp); iResult = frecv(cnx->socket,(unsigned char*)&(tmp->data_length),4, 0); len+=iResult; if (VERBOSE == 1) Printf(" length: %X",tmp->exp); tmp->data=calloc(tmp->data_length,1); iResult = frecv(cnx->socket,(tmp->data),tmp->data_length, 0); if (VERBOSE == 1) Printf(" data: %X",tmp->data); len+=iResult; } break; case VK_STRING: { int data_length=0; FOURD_STRING *str; //read negative value of length of string str=calloc(1,sizeof(FOURD_STRING)); pElmt->pValue=str; iResult = frecv(cnx->socket,(unsigned char*)&data_length,4, 0); len+=iResult; if (VERBOSE == 1) Printf("String length: %08X\n",data_length); data_length=-data_length; str->length=data_length; str->data=calloc(data_length*2+2,1); if(data_length==0){ //correct read for empty string str->data[0]=0; str->data[1]=0; } else { iResult = frecv(cnx->socket,(str->data),(data_length*2), 0); str->data[data_length*2]=0; str->data[data_length*2+1]=0; len+=iResult; } } break; case VK_IMAGE: { int data_length=0; FOURD_IMAGE *blob; blob=calloc(1,sizeof(FOURD_IMAGE)); pElmt->pValue=blob; iResult = frecv(cnx->socket,(unsigned char*)&data_length,4, 0); if (VERBOSE == 1) Printf("Image length: %08X\n",data_length); len+=iResult; if(data_length==0){ blob->length=0; blob->data=NULL; pElmt->null=1; }else{ blob->length=data_length; blob->data=calloc(data_length,1); iResult = frecv(cnx->socket,blob->data,data_length, 0); len+=iResult; } if (VERBOSE == 1) Printf("Image: %d Bytes\n",data_length); } break; case VK_BLOB: { int data_length=0; FOURD_BLOB *blob; blob=calloc(1,sizeof(FOURD_BLOB)); pElmt->pValue=blob; iResult = frecv(cnx->socket,(unsigned char*)&data_length,4, 0); if (VERBOSE == 1) Printf("Blob length: %08X\n",data_length); len+=iResult; if(data_length==0){ blob->length=0; blob->data=NULL; pElmt->null=1; }else{ blob->length=data_length; blob->data=calloc(data_length,1); iResult = frecv(cnx->socket,blob->data,data_length, 0); len+=iResult; } if (VERBOSE == 1) Printf("Blob: %d Bytes\n",data_length); } break; default: if (VERBOSE == 1) Printferr("Type not supported (%s) at row %d column %d\n",stringFromType(colType[c]),(elmts_offset-c+1)/nbCol+1,c+1); break; } break; default: if (VERBOSE == 1) Printferr("Status code 0x%X not supported in data at row %d column %d\n",status_code,(elmts_offset-c+1)/nbCol+1,c+1); break; } } } if (VERBOSE == 1) Printf("---End of socket_receiv_data\n"); free(colType); return 0; } int socket_receiv_update_count(FOURD *cnx,FOURD_RESULT *state) { FOURD_LONG8 data=0; frecv(cnx->socket,(unsigned char*)&data,8, 0); if (VERBOSE == 1) Printf("Ox%X\n",data); cnx->updated_row=data; if (VERBOSE == 1) Printf("\n"); return 0; } int set_sock_blocking(int socketd, int block) { int ret = 0; int flags; int myflag = 0; #ifdef WIN32 /* with ioctlsocket, a non-zero sets nonblocking, a zero sets blocking */ flags = !block; if (ioctlsocket(socketd, FIONBIO, &flags) == SOCKET_ERROR) { ret = 1; } #else flags = fcntl(socketd, F_GETFL); #ifdef O_NONBLOCK myflag = O_NONBLOCK; /* POSIX version */ #elif defined(O_NDELAY) myflag = O_NDELAY; /* old non-POSIX version */ #endif if (!block) { flags |= myflag; } else { flags &= ~myflag; } fcntl(socketd, F_SETFL, flags); #endif return ret; } int socket_connect_timeout(FOURD *cnx,const char *host,unsigned int port,int timeout) { struct addrinfo *result = NULL, *ptr = NULL, hints; int iResult=0,valopt=0; struct timeval tv; fd_set myset; socklen_t lon; char sport[50]; sprintf_s(sport,50,"%d",port); /* initialize Hints */ ZeroMemory( &hints, sizeof(hints) ); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; /* Resolve the server address and port */ iResult = getaddrinfo(host, sport, &hints, &result); if ( iResult != 0 ) { if (VERBOSE == 1) Printf("getaddrinfo failed: %d : %s\n", iResult,gai_strerror(iResult)); cnx->error_code=-iResult; strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,gai_strerror(iResult),ERROR_STRING_LENGTH); return 1; } /*Attempt to connect to the first address returned by the call to getaddrinfo */ ptr=result; /* Create a SOCKET for connecting to server */ cnx->socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol); if (cnx->socket == INVALID_SOCKET) { if (VERBOSE == 1) Printf("Error at socket(): %ld\n", WSAGetLastError()); cnx->error_code=-WSAGetLastError(); strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Unable to create socket",ERROR_STRING_LENGTH); freeaddrinfo(result); return 1; } int flag=1; // if we get an error here, we can safely ignore it. The connection may be slower, but it should // still work. setsockopt(cnx->socket, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(int)); /*set Non blocking socket */ set_sock_blocking(cnx->socket,0); /* Connect to server. */ iResult = connect( cnx->socket, ptr->ai_addr, (int)ptr->ai_addrlen); if(iResult<0){ if (WSAGetLastError() == EINPROGRESS) { tv.tv_sec = timeout; tv.tv_usec = 0; FD_ZERO(&myset); FD_SET(cnx->socket, &myset); if (select(cnx->socket+1, NULL, &myset, NULL, &tv) > 0) { lon = sizeof(int); getsockopt(cnx->socket, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon); if (valopt) { if (VERBOSE == 1) Printf("Error in connection() %d - %s\n", valopt, strerror(valopt)); cnx->error_code=valopt; strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,strerror(valopt),ERROR_STRING_LENGTH); freeaddrinfo(result); closesocket(cnx->socket); cnx->socket = INVALID_SOCKET; return 1; } /*connection ok*/ } else { /*fprintf(stderr, "Timeout or error() %d - %s\n", valopt, strerror(valopt)); */ cnx->error_code=3011; strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Connect timed out",ERROR_STRING_LENGTH); freeaddrinfo(result); closesocket(cnx->socket); cnx->socket = INVALID_SOCKET; return 1; } } else { cnx->error_code=-WSAGetLastError(); strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Error connecting",ERROR_STRING_LENGTH); freeaddrinfo(result); closesocket(cnx->socket); cnx->socket = INVALID_SOCKET; return 1; } } /* Printf("Connexion ok\n"); */ /*set blocking socket */ set_sock_blocking(cnx->socket,1); /* Should really try the next address returned by getaddrinfo if the connect call failed But for this simple example we just free the resources returned by getaddrinfo and print an error message */ freeaddrinfo(result); if (cnx->socket == INVALID_SOCKET) { if (VERBOSE == 1) Printf("Unable to connect to server!\n"); cnx->error_code=-1; strncpy_s(cnx->error_string,ERROR_STRING_LENGTH,"Unable to connect to server",ERROR_STRING_LENGTH); return 1; } return 0; } <file_sep>/lib4d_sql/utils.c #include <string.h> #define isspace(x) (x==' ') char *strstrip(char *s) { size_t size; char *end; size = strlen(s); if (!size) return s; end = s + size - 1; while (end != s && isspace(*end)) end--; *(end + 1) = '\0'; while (*s && isspace(*s)) s++; return s; }<file_sep>/lib4d_sql/fourd_result.c #include "fourd.h" #include "fourd_int.h" FOURD_LONG8 fourd_num_rows(FOURD_RESULT *result) { return result->row_count; }<file_sep>/lib4d_sql/fourd_type.c #include <stdio.h> #include <string.h> extern int Printf(const char* format,...); extern int Printferr(const char* format,...); #include "fourd.h" FOURD_TYPE typeFromString(const char *type) { if(strcmp(type,"VK_BOOLEAN")==0) return VK_BOOLEAN; if(strcmp(type,"VK_BYTE")==0) return VK_BYTE; if(strcmp(type,"VK_WORD")==0) return VK_WORD; if(strcmp(type,"VK_LONG")==0) return VK_LONG; if(strcmp(type,"VK_LONG8")==0) return VK_LONG8; if(strcmp(type,"VK_REAL")==0) return VK_REAL; if(strcmp(type,"VK_FLOAT")==0) return VK_FLOAT; if(strcmp(type,"VK_TIMESTAMP")==0) return VK_TIMESTAMP; if(strcmp(type,"VK_TIME")==0) return VK_TIMESTAMP; if(strcmp(type,"VK_DURATION")==0) return VK_DURATION; if(strcmp(type,"VK_TEXT")==0) return VK_STRING; if(strcmp(type,"VK_STRING")==0) return VK_STRING; if(strcmp(type,"VK_BLOB")==0) return VK_BLOB; if(strcmp(type,"VK_IMAGE")==0) return VK_IMAGE; return VK_UNKNOW; } const char* stringFromType(FOURD_TYPE type) { switch(type) { case VK_BOOLEAN: return "VK_BOOLEAN"; case VK_BYTE: return "VK_BYTE"; case VK_WORD: return "VK_WORD"; case VK_LONG: return "VK_LONG"; case VK_LONG8: return "VK_LONG8"; case VK_REAL: return "VK_REAL"; case VK_FLOAT: return "VK_FLOAT"; case VK_TIMESTAMP: return "VK_TIMESTAMP"; case VK_TIME: return "VK_TIME"; case VK_DURATION: return "VK_DURATION"; case VK_STRING: return "VK_STRING"; case VK_BLOB: return "VK_BLOB"; case VK_IMAGE: return "VK_IMAGE"; default: return "VK_UNKNOW"; } } /******************************************************************/ /* vk_sizeof */ /******************************************************************/ /* return sizeof type or -1 if varying length or 0 if unknow type */ /******************************************************************/ int vk_sizeof(FOURD_TYPE type) { switch(type) { case VK_BOOLEAN: case VK_BYTE: case VK_WORD: return 2; case VK_LONG: return 4; case VK_LONG8: case VK_REAL: case VK_DURATION: return 8; case VK_FLOAT: //Varying length return -1; case VK_TIME: case VK_TIMESTAMP: return 8; case VK_TEXT: case VK_STRING: case VK_BLOB: case VK_IMAGE: //Varying length return -1; default: if (VERBOSE == 1) Printf("Error: Unknow type in vk_sizeof function\n"); return 0; } } FOURD_RESULT_TYPE resultTypeFromString(const char *type) { if(strcmp(type,"Update-Count")==0) return UPDATE_COUNT; if(strcmp(type,"Result-Set")==0) return RESULT_SET; return UNKNOW; } const char* stringFromResultType(FOURD_RESULT_TYPE type) { switch(type) { case UPDATE_COUNT: return "Update-Count"; case RESULT_SET: return "Result-Set"; default: return "Unknown"; } }<file_sep>/lib4d_sql/fourd.h #ifndef __FOURD__ #define __FOURD__ 1 /* * Sockets */ #ifdef WIN32 #include <winsock2.h> #include <ws2tcpip.h> #include <Wspiapi.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <unistd.h> /* close */ #include <errno.h> #include <netdb.h> /* gethostbyname */ #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define closesocket(s) close(s) typedef int SOCKET; typedef struct sockaddr_in SOCKADDR_IN; typedef struct sockaddr SOCKADDR; typedef struct in_addr IN_ADDR; #endif #define VERBOSE 0 #define SOCKET_TIMEOUT 15 #define MAX_COL_TYPES_LENGHT 4096 #define ERROR_STRING_LENGTH 2048 #define MAX_HEADER_SIZE 8192 #define HEADER_GROW_SIZE 1024 #define DEFAULT_IMAGE_TYPE "jpg" #define MAX_LENGTH_COLUMN_NAME 255 #define MAX_STRING_NUMBER 255 #define MAX_LENGTH_COLUMN_TYPE 255 #define FOURD_OK 0 #define FOURD_ERROR 1 #define STATEMENT_BASE64 1 #define LOGIN_BASE64 1 #define PROTOCOL_VERSION "12.0" #define PAGE_SIZE 100 #define OUTPUT_MODE "release" typedef enum { VK_UNKNOW=0, VK_BOOLEAN, VK_BYTE, VK_WORD, VK_LONG, VK_LONG8, VK_REAL, VK_FLOAT, VK_TIME, VK_TIMESTAMP, VK_DURATION, VK_TEXT, VK_STRING, VK_BLOB, VK_IMAGE }FOURD_TYPE; /******************************/ /* parse and format FOUR_TYPE */ /******************************/ FOURD_TYPE typeFromString(const char *type); const char* stringFromType(FOURD_TYPE type); /******************************************************************/ /* vk_sizeof */ /******************************************************************/ /* return sizeof type or -1 if varying length or 0 if unknow type */ /******************************************************************/ int vk_sizeof(FOURD_TYPE type); /***************/ /* Result-Type */ /***************/ typedef enum { UNKNOW=0, UPDATE_COUNT, RESULT_SET }FOURD_RESULT_TYPE; FOURD_RESULT_TYPE resultTypeFromString(const char *type); const char* stringFromResultType(FOURD_RESULT_TYPE type); /*********************/ /* Structure of VK_* */ /*********************/ typedef short FOURD_BOOLEAN; typedef short FOURD_BYTE; typedef short FOURD_WORD; typedef int FOURD_LONG; #ifdef WIN32 typedef __int64 FOURD_LONG8; #else typedef long long FOURD_LONG8; #endif typedef double FOURD_REAL; typedef struct{int exp;char sign;int data_length;void* data;}FOURD_FLOAT; typedef struct{short year;char mounth;char day;unsigned int milli;}FOURD_TIMESTAMP; #ifdef WIN32 typedef __int64 FOURD_DURATION;//in milliseconds #else typedef long long FOURD_DURATION;//in milliseconds #endif typedef struct{int length;unsigned char *data;}FOURD_STRING; typedef struct{int length;void *data;}FOURD_BLOB; typedef struct{int length;void *data;}FOURD_IMAGE; typedef struct{ /* Socket Win32 */ #ifdef WIN32 WSADATA wsaData; SOCKET socket; #else int socket; #endif int init; /*boolean*/ int connected; /*boolean*/ /* status */ int status;//1 OK, 0 KO FOURD_LONG8 error_code; char error_string[ERROR_STRING_LENGTH]; /* updated row */ FOURD_LONG8 updated_row; /*Command number used for*/ /* LOGIN, STATEMENT, ETC*/ unsigned int id_cnx; /* PREFERRED-IMAGE-TYPES */ char *preferred_image_types; int timeout; }FOURD; typedef struct{ FOURD_TYPE type; char null;//0 not null, 1 null void *pValue; }FOURD_ELEMENT; typedef struct{ char sType[MAX_LENGTH_COLUMN_TYPE]; FOURD_TYPE type; char sColumnName[MAX_LENGTH_COLUMN_NAME]; }FOURD_COLUMN; typedef struct{ unsigned int nbColumn; FOURD_COLUMN *Column; }FOURD_ROW_TYPE; typedef struct{ FOURD *cnx; char *header; unsigned int header_size; /*state of statement (OK or KO)*/ int status; /*FOURD_OK or FOURD_ERRROR*/ FOURD_LONG8 error_code; char error_string[ERROR_STRING_LENGTH]; /*result of parse header RESULT_SET for select UPDATE_COUNT for insert, update, delete*/ FOURD_RESULT_TYPE resultType; /*Id of statement used with 4D SQL-server*/ int id_statement; /*Id of command use for request */ int id_command; /*updateability is true or false */ int updateability; /*total of row count */ unsigned int row_count; /*row count in data buffer for little select, row_count_sent = row_count for big select, row_count_sent = 100 for the first result_set */ unsigned int row_count_sent; /*num of the first row for the first response in big select with default parametre on serveur : 0 */ unsigned int first_row; /* row_type of this statement containe column count, column name and column type*/ FOURD_ROW_TYPE row_type; /*data*/ FOURD_ELEMENT *elmt; /*current row index*/ int numRow; }FOURD_RESULT; typedef struct { FOURD *cnx; char *query; /*MAX_HEADER_SIZE is using because the query is insert into header*/ unsigned int nb_element; unsigned int nbAllocElement; FOURD_ELEMENT *elmt; /* PREFERRED-IMAGE-TYPES */ char *preferred_image_types; }FOURD_STATEMENT; FOURD* fourd_init(void); int fourd_connect(FOURD *cnx,const char *host,const char *user,const char *password,const char *base,unsigned int port); int fourd_close(FOURD *cnx); int fourd_exec(FOURD *cnx,const char *query); FOURD_LONG8 fourd_affected_rows(FOURD *cnx); int fourd_errno(FOURD *cnx); const char * fourd_error(FOURD *cnx); const char * fourd_sqlstate(FOURD *cnx); void fourd_free(FOURD* cnx); void fourd_free_statement(FOURD_STATEMENT *state); void fourd_timeout(FOURD* cnx,int timeout); FOURD_LONG8 fourd_num_rows(FOURD_RESULT *result); FOURD_RESULT *fourd_query(FOURD *cnx,const char *query); int fourd_close_statement(FOURD_RESULT *res); void fourd_free_result(FOURD_RESULT *res); FOURD_LONG * fourd_field_long(FOURD_RESULT *res,unsigned int numCol); FOURD_STRING * fourd_field_string(FOURD_RESULT *res,unsigned int numCol); void * fourd_field(FOURD_RESULT *res,unsigned int numCol); int fourd_next_row(FOURD_RESULT *res); const char * fourd_get_column_name(FOURD_RESULT *res,unsigned int numCol); FOURD_TYPE fourd_get_column_type(FOURD_RESULT *res,unsigned int numCol); int fourd_num_columns(FOURD_RESULT *res); int fourd_field_to_string(FOURD_RESULT *res,unsigned int numCol,char **value,size_t *len); FOURD_STATEMENT * fourd_prepare_statement(FOURD *cnx,const char *query); FOURD_STRING *fourd_create_string(char *param,int length); int fourd_bind_param(FOURD_STATEMENT *state,unsigned int numParam,FOURD_TYPE type, void *val); FOURD_RESULT *fourd_exec_statement(FOURD_STATEMENT *state, int res_size); void fourd_set_preferred_image_types(FOURD* cnx,const char *types); void fourd_set_statement_preferred_image_types(FOURD_STATEMENT *state,const char *types); const char* fourd_get_preferred_image_types(FOURD* cnx); const char* fourd_get_statement_preferred_image_types(FOURD_STATEMENT *state); #endif <file_sep>/lib4d_sql/base64.h #ifndef BASE64_H #define BASE64_H 1 unsigned char *base64_encode(const char *, size_t, int *); unsigned char *base64_decode_ex(const char *, size_t, int *, int); unsigned char *base64_decode(const char *, size_t, int *); #endif /* BASE64_H */ <file_sep>/lib4d_sql/fourd_int.h #ifndef __FOURD_INT__ #define __FOURD_INT__ 1 #include <stdlib.h> #include <stdio.h> #include <string.h> int Printf(const char* format,...); int Printferr(const char* format,...); /*******************/ /* communication.c */ /*******************/ int socket_connect(FOURD *cnx,const char *host,unsigned int port); void socket_disconnect(FOURD *cnx); int socket_send(FOURD *cnx,const char*msg); int socket_send_data(FOURD *cnx,const char*msg,int len); //int socket_receiv(FOURD *cnx); int socket_receiv_header(FOURD *cnx,FOURD_RESULT *state); int socket_receiv_data(FOURD *cnx,FOURD_RESULT *state); int socket_receiv_update_count(FOURD *cnx,FOURD_RESULT *state); int set_sock_blocking(int socketd, int block); int socket_connect_timeout(FOURD *cnx,const char *host,unsigned int port,int timeout); /*******************/ /* fourd_interne.c */ /*******************/ //return 0 for OK et -1 for no readable header and error_code int dblogin(FOURD *cnx,unsigned int id_cnx,const char *user,const char*pwd,const char*image_type); int dblogout(FOURD *cnx,unsigned int id_cnx); int quit(FOURD *cnx,unsigned int id_cnx); //return 0 for OK et -1 for no readable header and error_code int _query(FOURD *cnx,unsigned int id_cnx,const char *request,FOURD_RESULT *result,const char*image_type, int res_size); int __fetch_result(FOURD *cnx,unsigned int id_cnx,int statement_id,int command_index,unsigned int first_row,unsigned int last_row,FOURD_RESULT *result); int _fetch_result(FOURD_RESULT *res,unsigned int id_cnx); int get(const char* msg,const char* section,char *value,int max_length); //FOURD_LONG8 get_status(FOURD* cnx); //int traite_header_reponse(FOURD* cnx); int traite_header_response(FOURD_RESULT* cnx); FOURD_LONG8 _get_status(const char *header,int *status,FOURD_LONG8 *error_code,char *error_string); int receiv_check(FOURD *cnx,FOURD_RESULT *state); void _free_data_result(FOURD_RESULT *res); //clear connection attribut void _clear_atrr_cnx(FOURD *cnx); int close_statement(FOURD_RESULT *res,unsigned int id_cnx); int _prepare_statement(FOURD *cnx,unsigned int id_cnx,const char *request); int _query_param(FOURD *cnx,unsigned int id_cnx, const char *request,unsigned int nbParam, const FOURD_ELEMENT *param,FOURD_RESULT *result,const char*image_type, int res_size); int _is_multi_query(const char *request); int _valid_query(FOURD *cnx,const char *request); /*********************/ /* Memory Allocation */ /*********************/ void *_copy(FOURD_TYPE type,void *org); char *_serialize(char *data,unsigned int *size, FOURD_TYPE type, void *pObj); void Free(void *p); void FreeFloat(FOURD_FLOAT *p); void FreeString(FOURD_STRING *p); void FreeBlob(FOURD_BLOB *p); void FreeImage(FOURD_IMAGE *p); void PrintData(const void *data,unsigned int size); #ifndef WIN32 void ZeroMemory (void *s, size_t n); #define WSAGetLastError() errno #define strtok_s(a,b,c) strtok(a,b) #define strcpy_s(s,size,cs) strncpy(s,cs,size) #define strncpy_s(s,ms,cs,size) strncpy(s,cs,size) int sprintf_s(char *buff,size_t size,const char* format,...); int _snprintf_s(char *buff, size_t size, size_t count, const char *format,...); #endif #endif <file_sep>/python4D/__init__.py from .python4D import *
afc9de292370f987cb40f47f046622f733c8828b
[ "C", "Python" ]
8
C
marcianobarros20/python4D
34b8fc09ee286ef4dbeaf3e2058587b224430ddf
f693adeb83423b8a44489ee46bace409f88a1ae5
refs/heads/master
<file_sep>class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validate :wedding_date_cannot_be_in_the_past require 'securerandom' has_many :checklist_items belongs_to :wedding_checklist after_create :create_list def wedding_date_cannot_be_in_the_past errors.add(:wedding_date, "can't be in the past.") if !wedding_date.blank? and wedding_date < Date.today end def create_list if self.code_entered != "" @checklist = WeddingChecklist.find_by(code: self.code_entered) self.update(wedding_checklist_id: @checklist.id) else @checklist = WeddingChecklist.create(wedding_date: self.wedding_date, code: SecureRandom.hex(5)) self.update(wedding_checklist_id: @checklist.id, owner: true, wedding_date: "") end end end <file_sep>class WeddingChecklistsController < ApplicationController before_action :find_wedding_checklist, only: [:show, :edit, :update] def new @wedding_checklist = WeddingChecklist.new end # GET /join_checklist def join_checklist @code_entered = params[:q] @wedding_checklist = WeddingChecklist.find_by(code: @code_entered) if @wedding_checklist redirect_to new_user_registration_path(q: params[:q]) else flash[:alert] = "Please enter a valid checklist code." redirect_to root_path end end def create @wedding_checklist = WeddingChecklist.create(wedding_checklist_params) redirect_to @wedding_checklist end def show end def edit end def update @wedding_checklist.update(wedding_checklist_params) redirect_to root_path end private def find_wedding_checklist @wedding_checklist = WeddingChecklist.find(params[:id]) end def wedding_checklist_params params.require(:wedding_checklist).permit(:wedding_date, :code) end end <file_sep>class AddCodeEnteredToUsers < ActiveRecord::Migration def change add_column :users, :code_entered, :string end end <file_sep>include Warden::Test::Helpers Warden.test_mode! Given(/^I am a user$/) do FactoryGirl.create :user end When(/^I click sign up$/) do visit root_path click_button('Sign Up') expect(page).to have_content('Welcome') end And(/^I choose to start a new checklist$/) do click_link('Start a New Checklist') expect(page).to have_content('Email') end And(/^I register/) do fill_in "sign_up_email", with: "<EMAIL>" fill_in "sign_up_password", with: "<PASSWORD>" fill_in "sign_up_password_confirm", with: "<PASSWORD>" click_button "Sign up" end And(/^I visit the root path$/) do visit root_path end Then(/^I should see a pre\-populated checklist$/) do expect(page).to have_content("Set wedding budget") end Given(/^I am an unregistered user$/) do expect(User.count).to eq(0) end And(/^I enter a valid checklist code$/) do click_link('Start a New Checklist') fill_in "q", with: "fa2a4e12b2" click_button "Sign up" expect(page).to have_content("Email") end And(/^I register with the code/) do fill_in "sign_up_email", with: "<EMAIL>" fill_in "sign_up_password", with: "<PASSWORD>" fill_in "sign_up_password_confirm", with: "<PASSWORD>" fill_in "sign_up_code", with: "fa2a4e12b2" click_button "Sign up" end Then(/^I should see the previously created checklist$/) do save_and_open_page expect(page).to have_content("Order flowers") end Given(/^I am a signed in user$/) do user = FactoryGirl.create :user, email: "<EMAIL>" login_as(user, :scope => :user) end And(/^I create a new task$/) do pending # express the regexp above with the code you wish you had end Then(/^I should see my new task added to the my checklist$/) do pending # express the regexp above with the code you wish you had end <file_sep># WedList WedList allows you to build your own checklist for wedding planning. You can either create your own checklist or join an exist one with a valid code. ### Technologies Used * Ruby 2.1.5 * Rails 4.1.8 * [CanCanCan](https://github.com/CanCanCommunity/cancancan) * [WiceGrid](https://github.com/leikind/wice_grid) gem * [jQuery](http://jquery.com/) * [Cucumber](http://cukes.info/)<file_sep>class ChecklistItemsController < ApplicationController load_and_authorize_resource before_action :find_checklist_item, only: [:edit, :update, :show, :destroy] def new @checklist_item = ChecklistItem.new end def create @checklist_item = ChecklistItem.create(checklist_item_params) @checklist_item.update(wedding_checklist_id: current_user.wedding_checklist_id) redirect_to root_path end def show end def edit end def update @checklist_item.update(checklist_item_params) redirect_to root_path end def destroy @checklist_item.destroy respond_to do |format| format.html { redirect_to root_path, notice: 'Task item was successfully deleted.' } format.json { head :no_content } end end private def find_checklist_item @checklist_item = ChecklistItem.find(params[:id]) end def checklist_item_params params.require(:checklist_item).permit(:wedding_checklist_id, :description, :due_date, :completed, :user_id) end end <file_sep>class WeddingChecklist < ActiveRecord::Base has_many :checklist_items, dependent: :destroy has_many :users accepts_nested_attributes_for :checklist_items after_create :create_checklist_items def create_checklist_items tasks = { "Set wedding budget" => 300, "Create wedding website" => 285, "Finalize guest list" => 250, "Book reception venue" => 200, "Set up gift registry" => 175, "Send out Save the Dates" => 150, "Book photographer" => 120, "Mail out invitations" => 115, "Book caterer" => 75, "Order wedding cake" => 60 } tasks.each do |key, value| ChecklistItem.create(wedding_checklist_id: self.id, description: key, due_date: (self.wedding_date - value)) end end end <file_sep>class CreateWeddingChecklists < ActiveRecord::Migration def change create_table :wedding_checklists do |t| t.date :wedding_date t.string :code t.timestamps end end end <file_sep>FactoryGirl.define do factory :wedding_checklist do |f| f.wedding_date Date.new(2015, 7, 1) f.code "randomcode" end trait :with_items do after :create do |wedding_checklist| FactoryGirl.create :checklist_item, wedding_checklists: wedding_checklist end end end<file_sep>FactoryGirl.define do factory :checklist_item do |f| f.wedding_checklist_id 1 f.description "Set wedding budget" f.due_date Date.new(2015, 2, 1) f.completed false f.user_id 1 end end<file_sep>class AddChecklistRefToUsers < ActiveRecord::Migration def change add_reference :users, :wedding_checklist, index: true end end <file_sep>class ChecklistItem < ActiveRecord::Base belongs_to :wedding_checklist belongs_to :user validates :wedding_checklist, presence: true end <file_sep>class WelcomeController < ApplicationController def index if current_user && current_user.owner @checklist = WeddingChecklist.find(current_user.wedding_checklist_id) @checklist_items = ChecklistItem.where(wedding_checklist_id: @checklist.id) @tasks_grid = initialize_grid(ChecklistItem.where(wedding_checklist_id: @checklist.id)) elsif current_user && current_user.code_entered @checklist = WeddingChecklist.find_by(code: current_user.code_entered) @checklist_items = ChecklistItem.where(wedding_checklist_id: @checklist.id) @tasks_grid = initialize_grid(ChecklistItem.where(wedding_checklist_id: @checklist.id)) end end end
601f0e5985690df258375f1cfd15c2acfef07b7e
[ "Markdown", "Ruby" ]
13
Ruby
ef718/checklist
f7906ff5fddbff3dad73585bd73e144cd8d5718d
5c70458a5d565880579dd7698ddedc4c5a6ec9f4
refs/heads/master
<repo_name>ZiRanGe-Jason/AutoAir<file_sep>/aair-wordlist.py import os if __name__ == "__main__": while(True): print("==================================") print(''' 输入数字编号 1.添加密码字典 2.显示所有字典 3.设置默认密码字典 4.安装wpa-dictionary字典 5.安装kali的rockyou字典 6.清空字典 7.返回 ''') try: ret1=int(input("配置密码字典>")) except ValueError: continue else: if(ret1==1): print("请将字典复制到AutoAir根目录下的wordlists文件夹中") elif(ret1==2): os.system("ls wordlists/") elif(ret1==3): os.system("ls wordlists/") print("开发中") elif(ret1==4): print("wpa-dictionary由conwnet制作") ret=os.system("git --version") if(ret!=0): print("Git Error\nGit未安装") else: ret=os.system("git clone https://github.com.cnpmjs.org/conwnet/wpa-dictionary.git") if(ret!=0): print("Git获取wpa-dictionary失败") else: os.system("rm wpa-dictionary/normalize.py") os.system("rm wpa-dictionary/README.md") os.system("mv wpa-dictionary/* wordlists/") os.system("rm -r wpa-dictionary/") print("wpa-dictionary安装完成") elif(ret1==5): os.system("sh aair-down-rockyou.sh") os.system("gzip -d rockyou.txt.gz") os.system("mv rockyou.txt wordlists/") elif(ret1==6): ret1=input("注意,将删除所有的密码字典,是否继续?[y/n]") if(ret1=="y"): os.system("rm -r wordlists/*") elif(ret1==7): exit() <file_sep>/autoair.py import os def start(): print(r''' _____ __ _____ .__ / _ \ __ ___/ |_ ____ / _ \ |__|______ / /_\ \| | \ __\/ _ \ / /_\ \| \_ __ \ / | \ | /| | ( <_> ) | \ || | \/ \____|__ /____/ |__| \____/\____|__ /__||__| \/ \/ ''') #print("==================================") print("AutoAir 0.01") print("By ZiRanGe_Jason") if __name__ == "__main__": pass start() while(True): print("==================================") print(''' 输入数字编号 1.使用Aircrack-ng破解WIFI 2.配置密码字典 3.介绍 ''') try: ret1=int(input(">")) except ValueError: continue except KeyboardInterrupt: print("\nGoodbye!See you next time!") exit() else: if(ret1==3): print("==================================") start() print("这是一个半自动化的WIFI破解程序") elif(ret1==1): os.system("python3 aair-aircrack.py") elif(ret1==2): os.system("python3 aair-wordlist.py") <file_sep>/autoair.sh sudo chmod +x ./* python3 -h if [ $? -ne 0 ] then echo "AutoAir[ERROR]:Python3未安装" exit fi aircrack-ng ai=$? git --version gi=$? clear if [ $ai -ne 0 ] then echo "AutoAir[WARNING]:Aircrack-ng未安装" fi if [ $gi -ne 0 ] then echo "AutoAir[WARNING]:Git未安装" fi sudo python3 autoair.py if [ $? -ne 0 ] then echo "AutoAir[ERROR]:AutoAir未启动成功" exit fi exit<file_sep>/README.md # AutoAir AutoAir,一个适合新手的半自动化WIFI破解工具,用于Linux <file_sep>/aair-aircrack.py import os if __name__ == "__main__": print("==================================") os.system("iwconfig") wlaname=input("(注意,网卡将被调整至监听模式,您将无法正常上网)\n请输入无线网卡名: ") ret=os.system("airmon-ng start "+wlaname) if(ret!=0): print("Airmon-ng Error\n也许你没有使用root权限启动本程序") exit() print("==================================") os.system("iwconfig") monname=input("请输入监听网卡名(一般以mon结尾): ") print("将会显示WIFI列表,按CTRL+C结束") os.system("airodump-ng "+monname) #path=input("请抓包存储的路径: ") CH=input("请输入WIFI的信道频率(即CH): ") BSSID=input("请输入WIFI的BSSID: ") print("注意,将清除caps文件夹下的所有包!") os.system("rm -rf caps/*") print("请等待抓包完成,当出现handshake请按CTRL+C") os.system("airodump-ng --bssid "+BSSID+" -c "+CH+" -w ./caps/wifi "+monname) print("抓包完成") os.system("ls wordlists/") wordlist=input("请输入要选择的密码字典名: ") print("即将开始字典破解") os.system("aircrack-ng -w wordlists/"+wordlist+" caps/wifi-01.cap") print("破解结束,密码在上方KEY FOUNG一栏中,网卡的监听模式将自动解除") os.system("airmon-ng stop "+monname)
c4a239a245ff69cafaa3d74b73f0c82ac248184a
[ "Markdown", "Python", "Shell" ]
5
Python
ZiRanGe-Jason/AutoAir
6922249a06a45a747be9cd1c6c70d86b21b27898
b64651290df250552f7ddd55d85d81e5b608e7e5
refs/heads/master
<file_sep>import cv2 import numpy import time import HandTrackingModule cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) pTime = 0 detector = HandTrackingModule.handDetector(maxHands=2) while True: success, img = cap.read() img = cv2.flip(img, 1) img = detector.findHands(img) lmList, bbox = detector.findPosition(img) cTime = time.time() fps = 1 / (cTime-pTime) pTime = cTime cv2.putText(img, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3) cv2.imshow("Image", img) cv2.waitKey(1) <file_sep># VirtualMouse
e367c63ee8baafdfba818bbd3793e1170bfc626c
[ "Markdown", "Python" ]
2
Python
Harsh-Upadhayay/VirtualMouse
fd62432c023d2f717c6abf751b188f728860b9f0
0a83fff37638582e88cd4bcf5b98695833fa06e7
refs/heads/master
<repo_name>431910864/miyou.tv<file_sep>/electron-wrapper.sh #!/bin/sh exec "$(cd $(dirname $0) && pwd)/miyoutv-bin" --no-sandbox "$@" <file_sep>/src/modules/viewer/saga.web.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { all, put, select, takeLatest, take } from "redux-saga/effects"; import { AnyAction } from "redux"; import Toast from "react-native-root-toast"; import { NavigationActions } from "react-navigation"; import { remote, BrowserWindow, BrowserView } from "electron"; import { VIEWER_INIT, VIEWER_READY, VIEWER_OPEN, VIEWER_CLOSE, VIEWER_DOCK, VIEWER_UNDOCK, VIEWER_SEARCH, VIEWER_RESIZE, VIEWER_UPDATE, ViewerActions } from "./actions"; import { ProgramActions } from "../program"; import { ServiceActions, ServiceState } from "../service"; import { SettingActions, SettingState, SETTING_UPDATE } from "../setting"; import { WindowActions } from "../window"; import { toastOptions } from "../../config/constants"; import { ViewerState } from "."; function getViewerView() { const win = remote.getCurrentWindow(); const viewerView = win.getBrowserView(); return viewerView; } function getViewerWindow() { const [viewerWindow = null] = remote.BrowserWindow.getAllWindows() .sort(({ id: a }, { id: b }) => a - b) .slice(1) .filter(({ isDestroyed }) => !isDestroyed()); return viewerWindow; } function dispatchMain(action: AnyAction) { try { const [win] = remote.BrowserWindow.getAllWindows().sort( ({ id: a }, { id: b }) => a - b ); const data = JSON.stringify(action); win.webContents.send("dispatch", data); } catch (e) { Toast.show(e.message || JSON.stringify(e, null, 2), { ...toastOptions, duration: Toast.durations.SHORT }); } } function dispatchViewer(child: BrowserWindow | BrowserView, action: AnyAction) { try { const data = JSON.stringify(action); child.webContents.send("dispatch", data); } catch (e) { Toast.show(e.message || JSON.stringify(e, null, 2), { ...toastOptions, duration: Toast.durations.SHORT }); } } let powerSaveBlockerId: number | undefined; function startPowerSaveBlocker() { const { powerSaveBlocker } = remote; powerSaveBlockerId = powerSaveBlocker.start("prevent-display-sleep"); } function stopPowerSaveBlocker() { const { powerSaveBlocker } = remote; if ( powerSaveBlockerId != null && powerSaveBlocker.isStarted(powerSaveBlockerId) ) { powerSaveBlocker.stop(powerSaveBlockerId); } } function* initSaga() { const { mode }: ViewerState = yield select(({ viewer }) => viewer); if (mode !== "stack") { dispatchMain(ViewerActions.ready()); } } function* openSaga(action: AnyAction) { const { mode }: ViewerState = yield select(({ viewer }) => viewer); if (mode === "stack") { const setting: SettingState = yield select(({ setting }) => setting); const { commentChannels }: ServiceState = yield select( ({ service }) => service ); const { docking = true } = setting; const { programs, index, layout }: ViewerState = yield select( ({ viewer }) => viewer ); const viewerView = getViewerView(); let viewerWindow = getViewerWindow(); if (docking) { if (viewerWindow) { viewerWindow.destroy(); } if (viewerView) { viewerView.setBounds(layout); dispatchViewer(viewerView, SettingActions.restore(setting)); dispatchViewer( viewerView, ServiceActions.commentReady(commentChannels) ); dispatchViewer(viewerView, ViewerActions.update({ programs, index })); } } else { if (viewerView) { viewerView.setBounds({ x: 0, y: 0, width: 0, height: 0 }); } if (!viewerWindow || viewerWindow.isDestroyed()) { viewerWindow = new remote.BrowserWindow({ width: 800, height: 600, minWidth: 320, minHeight: 480, frame: false, show: false, webPreferences: { nodeIntegration: true, plugins: true } }); viewerWindow.on("close", () => { dispatchMain(ViewerActions.close()); }); viewerWindow.loadURL(`${location.href}#child`); yield take(VIEWER_READY); } if (!viewerWindow.isVisible()) { viewerWindow.show(); } dispatchViewer(viewerWindow, SettingActions.restore(setting)); dispatchViewer( viewerWindow, ServiceActions.commentReady(commentChannels) ); dispatchViewer(viewerWindow, ViewerActions.update({ programs, index })); } } else { dispatchMain(action); } } function* closeSaga(action: AnyAction) { const { mode }: ViewerState = yield select(({ viewer }) => viewer); if (mode === "stack") { const viewerView = getViewerView(); const viewerWindow = getViewerWindow(); if (viewerView) { viewerView.setBounds({ x: 0, y: 0, width: 0, height: 0 }); dispatchViewer(viewerView, ViewerActions.update({ playing: false })); } if (viewerWindow) { viewerWindow.destroy(); } stopPowerSaveBlocker(); } else { dispatchMain(action); } } function* dockSaga(action: AnyAction) { const { mode }: ViewerState = yield select(({ viewer }) => viewer); if (mode === "stack") { yield put(SettingActions.update("docking", true)); yield openSaga(action); } else { dispatchMain(action); } } function* undockSaga(action: AnyAction) { const { mode }: ViewerState = yield select(({ viewer }) => viewer); if (mode === "stack") { const viewerView = getViewerView(); if (viewerView) { dispatchViewer(viewerView, ViewerActions.update({ playing: false })); } yield put(SettingActions.update("docking", false)); yield openSaga(action); } else { dispatchMain(action); } } function* searchSaga(action: AnyAction) { const viewer: ViewerState = yield select(({ viewer }) => viewer); const { mode } = viewer; if (mode === "stack") { const { query = "" } = action; yield put(ProgramActions.update("list", { query, page: 1 })); yield put(NavigationActions.navigate({ routeName: "List" })); const { docking = true }: SettingState = yield select( ({ setting }) => setting ); const { isOpened, stacking } = viewer; if (docking && isOpened && stacking) { yield put(ViewerActions.close()); } } else { dispatchMain(action); } } function* resizeSaga() { const { mode }: ViewerState = yield select(({ viewer }) => viewer); if (mode === "stack") { const { docking = true }: SettingState = yield select( ({ setting }) => setting ); const { isOpened, layout }: ViewerState = yield select( ({ viewer }) => viewer ); if (docking && isOpened) { const viewerView = getViewerView(); if (viewerView) { viewerView.setBounds(layout); } } } } function* updateSaga(action: AnyAction) { const viewer: ViewerState = yield select(({ viewer }) => viewer); const { mode, playing } = viewer; if (mode === "stack") { if (playing) { startPowerSaveBlocker(); } else { stopPowerSaveBlocker(); } } else { dispatchMain(action); if (mode === "child") { const { programs, index } = viewer; const program = programs[index]; if (program) { yield put(WindowActions.setTitle(program.title)); } } } } function* settingSaga() { const setting: SettingState = yield select(({ setting }) => setting); const viewer: ViewerState = yield select(({ viewer }) => viewer); const { mode } = viewer; if (mode === "stack") { const viewerView = getViewerView(); const viewerWindow = getViewerWindow(); if (viewerView) { dispatchViewer(viewerView, SettingActions.restore(setting)); } if (viewerWindow) { dispatchViewer(viewerWindow, SettingActions.restore(setting)); } } else { dispatchMain(SettingActions.restore(setting)); } } export function* viewerSaga() { yield all([ takeLatest(VIEWER_INIT, initSaga), takeLatest(VIEWER_OPEN, openSaga), takeLatest(VIEWER_CLOSE, closeSaga), takeLatest(VIEWER_DOCK, dockSaga), takeLatest(VIEWER_UNDOCK, undockSaga), takeLatest(VIEWER_SEARCH, searchSaga), takeLatest(VIEWER_RESIZE, resizeSaga), takeLatest(VIEWER_UPDATE, updateSaga), takeLatest(SETTING_UPDATE, settingSaga) ]); } <file_sep>/src/utils/init/index.web.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Store, AnyAction } from "redux"; import { remote, ipcRenderer } from "electron"; import Toast from "react-native-root-toast"; import Mousetrap from "mousetrap"; import fs from "fs"; import { FileActions } from "../../modules/file"; import { ServiceActions } from "../../modules/service"; import { SettingActions } from "../../modules/setting"; import { ViewerActions } from "../../modules/viewer"; import { WindowActions } from "../../modules/window"; import { toastOptions } from "../../config/constants"; import common from "./common"; export default function init(store: Store) { let mode: "stack" | "view" | "child"; let boundsSettingName = ""; document.addEventListener("dragover", e => e.preventDefault()); document.body.addEventListener("drop", dropFileDispatcher); if (location.hash.indexOf("view") >= 0) { mode = "view"; } else if (location.hash.indexOf("child") >= 0) { mode = "child"; boundsSettingName = "childBounds"; } else { mode = "stack"; boundsSettingName = "bounds"; window.addEventListener("beforeunload", () => { const win = remote.getCurrentWindow(); win.removeAllListeners(); const view = win.getBrowserView(); if (view) { view.setBounds({ x: 0, y: 0, width: 0, height: 0 }); view.webContents.reload(); } remote.BrowserWindow.getAllWindows() .sort(({ id: a }, { id: b }) => a - b) .slice(1) .forEach(({ isDestroyed, close }) => { !isDestroyed() && close(); }); }); Mousetrap.bind("mod+r", () => { store.dispatch(ServiceActions.backendInit()); store.dispatch(ServiceActions.commentInit()); return false; }); const { argv }: { argv: string[] } = remote.process; const paths = argv.slice(1).filter(a => a !== "." && fs.existsSync(a)); if (paths.length > 0) { store.dispatch(FileActions.add(paths.map(path => `file://${path}`))); } common(store); } store.dispatch(ViewerActions.init(mode)); const win = remote.getCurrentWindow(); const windowStateDispatcher = () => { store.dispatch( WindowActions.update({ alwaysOnTop: win.isAlwaysOnTop(), fullScreen: win.isFullScreen(), maximized: win.isMaximized(), minimized: win.isMinimized() }) ); }; win .on("maximize", windowStateDispatcher) .on("unmaximize", windowStateDispatcher) .on("minimize", windowStateDispatcher) .on("restore", windowStateDispatcher) .on("enter-full-screen", windowStateDispatcher) .on("leave-full-screen", windowStateDispatcher) .on("always-on-top-changed", windowStateDispatcher); windowStateDispatcher(); if (boundsSettingName) { const { setting } = store.getState(); let boundsDispatcherId: number; const windowBoundsDispatcher = () => { if (boundsDispatcherId != null) { clearTimeout(boundsDispatcherId); } if (!win.isFullScreen() && !win.isMaximized()) { boundsDispatcherId = setTimeout( () => store.dispatch( SettingActions.update(boundsSettingName, win.getBounds()) ), 500 ); } }; win.on("resize", windowBoundsDispatcher).on("move", windowBoundsDispatcher); const bounds = setting[boundsSettingName] || {}; win.setBounds({ ...win.getBounds(), ...bounds }); } ipcRenderer.on("dispatch", ({}, data: string) => { const action = JSON.parse(data); store.dispatch(action); }); Mousetrap.bind("esc", () => { dispatchWindow(WindowActions.setFullScreen(false)); }); Mousetrap.bind("mod+I", () => { win.webContents.toggleDevTools(); return false; }); } function dispatchWindow(action: AnyAction) { try { const win = remote.getCurrentWindow(); const data = JSON.stringify(action); win.webContents.send("dispatch", data); } catch (e) { Toast.show(e.message || JSON.stringify(e, null, 2), { ...toastOptions, duration: Toast.durations.SHORT }); } } function dropFileDispatcher({ dataTransfer }: DragEvent) { if (dataTransfer) { const { files } = dataTransfer; const uris = []; for (let i = 0; i < files.length; i++) { const file = files.item(i); if (file) { uris.push(`file://${file.path}`); } } dispatchWindow(FileActions.add(uris)); } } <file_sep>/src/utils/init/common.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Store } from "redux"; import { StackActions } from "react-navigation"; import { ServiceActions } from "../../modules/service"; export default function common(store: Store) { const { setting } = store.getState(); const { isConfigured } = setting; store.dispatch(StackActions.popToTop({})); if (!isConfigured) { store.dispatch(StackActions.push({ routeName: "Setup" })); } else { store.dispatch(ServiceActions.backendInit()); store.dispatch(ServiceActions.commentInit()); } } <file_sep>/src/utils/searchNavRoute.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { NavigationState } from "react-navigation"; export default function searchNavRoute( route: NavigationState & { routeName?: string }, routeName = "" ) { while (route.index != null) { route = route.routes[route.index] as NavigationState & { routeName: string; }; if (route.routeName === routeName) { return route; } } if (routeName) { return null; } return route; } <file_sep>/src/styles/color.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { StyleSheet } from "react-native"; export const white = "#ffffff"; export const light = "#e2e2e2"; export const gray = "#808080"; export const grayDark = "#3a3a3a"; export const dark = "#262626"; export const black = "#1a1a1a"; export const active = "#9991ff"; const colorStyle = StyleSheet.create({ while: { color: white }, light: { color: light }, grayDark: { color: grayDark }, gray: { color: gray }, dark: { color: dark }, black: { color: black }, active: { color: active }, bgWhite: { backgroundColor: white }, bgLight: { backgroundColor: light }, bgGrayDark: { backgroundColor: grayDark }, bgGray: { backgroundColor: gray }, bgDark: { backgroundColor: dark }, bgBlack: { backgroundColor: black }, bgTransparent: { backgroundColor: "transparent" }, bgActive: { backgroundColor: active }, borderWhite: { borderColor: white }, borderLight: { borderColor: light }, borderGrayDark: { borderColor: grayDark }, borderGray: { borderColor: gray }, borderDark: { borderColor: dark }, borderBlack: { borderColor: black }, borderTransparent: { borderColor: "transparent" }, borderActive: { borderColor: active } }); export default colorStyle; <file_sep>/src/utils/fileSelector/index.android.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import FilePickerManager from "react-native-file-picker"; export default async function fileSelector({ title, buttonLabel: chooseFileButtonTitle }: { title?: string; buttonLabel?: string; type?: any[]; multiSelections?: boolean; }) { const { path, uri, didCancel, error } = await new Promise<any>(resolve => { FilePickerManager.showFilePicker({ title, chooseFileButtonTitle }, resolve); }); if (error) { throw error; } if (didCancel) { return; } return [path ? `file://${path}` : uri]; } <file_sep>/src/modules/viewer/saga.ts /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { all, put, select, takeLatest } from "redux-saga/effects"; import { AnyAction } from "redux"; import { NavigationActions, StackActions } from "react-navigation"; import { VIEWER_OPEN, VIEWER_CLOSE, VIEWER_SEARCH } from "./actions"; import { ProgramActions } from "../program"; import searchNavRoute from "../../utils/searchNavRoute"; function* openSaga() { const { nav } = yield select(({ nav }) => ({ nav })); const current = searchNavRoute(nav, "Viewer"); if (!current) { yield put(StackActions.push({ routeName: "Viewer" })); } } function* closeSaga() { yield put(StackActions.pop({})); } function* searchSaga(action: AnyAction) { const { query = "" } = action; yield put(StackActions.popToTop({})); yield put(ProgramActions.update("list", { query })); yield put(NavigationActions.navigate({ routeName: "List" })); } export function* viewerSaga() { yield all([ takeLatest(VIEWER_OPEN, openSaga), takeLatest(VIEWER_CLOSE, closeSaga), takeLatest(VIEWER_SEARCH, searchSaga) ]); } <file_sep>/src/utils/moment-with-locale.js /*! Copyright 2016-2019 Brazil Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { Platform, NativeModules } from "react-native"; import m from "moment"; const moment = m; switch (Platform.OS) { case "android": moment.locale(NativeModules.I18nManager.localeIdentifier); break; case "ios": moment.locale(NativeModules.SettingsManager.settings.AppleLocale); break; case "web": moment.locale(window.navigator.language); break; default: moment.locale("ja"); } export default moment;
b9107ea9fb9ba6f98e72f2de7bd42d38a866ae52
[ "JavaScript", "TypeScript", "Shell" ]
9
Shell
431910864/miyou.tv
0620775f41e4064d73368dab0570e1ed033bbd5c
c08ac43a94106919b9a8e2b20c814ee499e4b0f3