code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
=begin = TeamDecorator - version: 6.002 - author: Leega Decorator for the Team model. Contains all presentation-logic centered methods. =end class TeamDecorator < Draper::Decorator delegate_all include Rails.application.routes.url_helpers # Retrieves the team complete name # with link to team radiography # def get_linked_name h.link_to( get_full_name, team_radio_path(id: team.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('radiography.team_radio_tab_tooltip') } ) end #-- ------------------------------------------------------------------------- # Retrieves the team complete name # with link to team meeting results # def get_linked_to_results_name(meeting) h.link_to( get_full_name, meeting_show_team_results_path(id: meeting.id, team_id: team.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_team_results_tooltip') } ) end #-- ------------------------------------------------------------------------- # Returns the list of season types the teams was affiliate # def get_season_type_list() season_types ? season_types.uniq.map{ |row| row.get_full_name }.join(', ') : I18n.t('none') end #-- -------------------------------------------------------------------------- # Returns the formatted list of contacts # TODO Add the link to email address # def get_contacts() contacts = [] contacts.append(contact_name) if contact_name contacts.append("#{I18n.t('mobile')} #{phone_mobile}") if phone_mobile contacts.append("#{I18n.t('phone')} #{phone_number}") if phone_number contacts.append("#{I18n.t('fax')} #{fax_number}") if fax_number contacts.append("#{I18n.t('email')} " + h.mail_to(e_mail)) if e_mail contacts.join(', ') end #-- -------------------------------------------------------------------------- # Returns the complete team address with address, city, country # def get_complete_address() "#{address} #{city ? ' - ' + city.get_full_name + ' - ' + city.country : ''}" end #-- -------------------------------------------------------------------------- # Returns the Team's home site if present # def get_home_site() home_page_url ? h.link_to( home_page_url, home_page_url, { target: "blank", 'data-toggle' => 'tooltip', title: I18n.t('team.visit_home_page') } ) : I18n.t('unknown') end #-- -------------------------------------------------------------------------- # Returns the Team's last meeting name (and header date) # def get_first_meeting_name() meeting = meetings.sort_by_date(:asc).first meeting ? h.link_to( meeting.get_full_name, meeting_show_full_path( id: meeting.id, team_id: id ), { 'data-toggle' => 'tooltip', title: I18n.t('meeting.show_team_results_tooltip') + "\r\n(#{ meeting.get_full_name })" } ) : I18n.t('none') end #-- -------------------------------------------------------------------------- # Returns the Team's last meeting name (and header date) # def get_last_meeting_name() meeting = meetings.sort_by_date(:desc).first meeting ? h.link_to( meeting.get_full_name, meeting_show_full_path( id: meeting.id, team_id: id ), { 'data-toggle' => 'tooltip', title: I18n.t('meeting.show_team_results_tooltip') + "\r\n(#{ meeting.get_full_name })" } ) : I18n.t('none') end #-- -------------------------------------------------------------------------- # Returns the current goggle cup name if present # def get_current_goggle_cup_name_at( evaluation_date = Date.today ) goggle_cup = get_current_goggle_cup_at( evaluation_date ) goggle_cup ? goggle_cup.get_full_name : I18n.t('radiography.goggle_cup_tab') end #-- -------------------------------------------------------------------------- end
steveoro/goggles
app/decorators/team_decorator.rb
Ruby
mit
3,732
using System; using System.Runtime.InteropServices; using System.Text; namespace Akkomation.TelldusCore.Utils { internal enum MarshalDirection { In, Out } internal class TelldusUtf8Marshaler : ICustomMarshaler { private static readonly TelldusUtf8Marshaler InputInstance = new TelldusUtf8Marshaler(MarshalDirection.In); private static readonly TelldusUtf8Marshaler OutputInstance = new TelldusUtf8Marshaler(MarshalDirection.Out); private readonly MarshalDirection _direction; /// <summary> /// Initializes a new instance of the <see cref="TelldusUtf8Marshaler"/> class. /// </summary> /// <param name="direction"> /// if set to <c>true</c> the marshaler will free strings using Telldus API. /// Use this for marshallers that receive strings from the API. If false the /// strings will</param> public TelldusUtf8Marshaler(MarshalDirection direction) { _direction = direction; } public static ICustomMarshaler GetInstance(string cookie) { if (String.Equals(cookie, "in", StringComparison.OrdinalIgnoreCase)) return InputInstance; if (String.Equals(cookie, "out", StringComparison.OrdinalIgnoreCase)) return OutputInstance; throw new ArgumentException("Support cookie values are 'in' or 'out'. See MarshalDirection enum"); } public void CleanUpManagedData(object managedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { if (_direction == MarshalDirection.In) Marshal.FreeHGlobal(pNativeData); else NativeMethods.tdReleaseString(pNativeData); } public int GetNativeDataSize() { return -1; } public IntPtr MarshalManagedToNative(object managedObj) { if (_direction == MarshalDirection.Out) throw new InvalidOperationException("Marshaler is used in output mode, can't marshal managed to native"); if (managedObj == null) return IntPtr.Zero; var str = managedObj as string; if (str == null) throw new InvalidOperationException("TelldusUtf8Marshaler only supports marshalling strings"); return FromManaged(str); } public object MarshalNativeToManaged(IntPtr pNativeData) { if (_direction == MarshalDirection.In) throw new InvalidOperationException("Marshaler is used in input mode, can't marshal managed to native"); return FromNative(pNativeData); } internal static IntPtr FromManaged(string value) { if (value == null) return IntPtr.Zero; var buf = Encoding.UTF8.GetBytes(value + '\0'); var ptr = Marshal.AllocHGlobal(buf.Length); Marshal.Copy(buf, 0, ptr, buf.Length); return ptr; } internal static string FromNative(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) return null; int length = 0; while (Marshal.ReadByte(pNativeData, length) != 0) length++; var buf = new byte[length]; Marshal.Copy(pNativeData, buf, 0, length); return Encoding.UTF8.GetString(buf); } } }
johanclasson/TellCore
Source/Akkomation.TelldusCore/Utils/TelldusUtf8Marshaler.cs
C#
mit
3,510
<?php namespace MicroCMS\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Request; use MicroCMS\Domain\Article; use MicroCMS\Domain\Experience; use MicroCMS\Domain\User; use MicroCMS\Domain\Perso; use MicroCMS\Domain\Portfolio; use MicroCMS\Domain\Loisir; use MicroCMS\Form\Type\ArticleType; use MicroCMS\Form\Type\LoisirType; use MicroCMS\Form\Type\ExperienceType; use MicroCMS\Form\Type\PersoType; use MicroCMS\Form\Type\PortfolioType; use MicroCMS\Form\Type\CommentType; use MicroCMS\Form\Type\UserType; use MicroCMS\Form\Type\ExperienceController; class AdminController { /** * Admin home page controller. * * @param Application $app Silex application */ public function indexAction(Application $app) { $articles = $app['dao.article']->findAll(); $comments = $app['dao.comment']->findAll(); $users = $app['dao.user']->findAll(); $experiences = $app['dao.experience']->findAll(); $loisirs = $app['dao.loisir']->findAll(); $persos = $app['dao.perso']->findAll(); $portfolios = $app['dao.portfolio']->findAll(); // $experiences = $app['dao.experiences']->findAll(); return $app['twig']->render('admin.html.twig', array( 'articles' => $articles, 'comments' => $comments, 'users' => $users, 'experiences' => $experiences, 'loisirs' => $loisirs, 'persos' => $persos, 'portfolios' => $portfolios )); } /** * Add article controller. * * @param Request $request Incoming request * @param Application $app Silex application */ public function addArticleAction(Request $request, Application $app) { $article = new Article(); $articleForm = $app['form.factory']->create(ArticleType::class, $article); $articleForm->handleRequest($request); if ($articleForm->isSubmitted() && $articleForm->isValid()) { $app['dao.article']->save($article); $app['session']->getFlashBag()->add('success', 'The article was successfully created.'); } return $app['twig']->render('article_form.html.twig', array( 'title' => 'New article', 'articleForm' => $articleForm->createView())); } /** * Add loisir controller. * * @param Request $request Incoming request * @param Application $app Silex application */ public function addLoisirAction(Request $request, Application $app) { $loisir = new Loisir(); $loisirForm = $app['form.factory']->create(LoisirType::class, $loisir); $loisirForm->handleRequest($request); if ($loisirForm->isSubmitted() && $loisirForm->isValid()) { $app['dao.loisir']->save($loisir); $app['session']->getFlashBag()->add('success', 'The article was successfully created.'); } return $app['twig']->render('article_form.html.twig', array( 'title' => 'Nouveau Loisir', 'articleForm' => $loisirForm->createView())); } /** * Edit article controller. * * @param integer $id Article id * @param Request $request Incoming request * @param Application $app Silex application */ public function editLoisirAction($id, Request $request, Application $app) { $loisir = $app['dao.loisir']->find($id); $loisirForm = $app['form.factory']->create(LoisirType::class, $loisir); $loisirForm->handleRequest($request); if ( $loisirForm->isSubmitted() && $loisirForm->isValid() ) { $app['dao.loisir']->save($loisir); $app['session']->getFlashBag()->add('success', 'Votre loisir à été enregistré avec succé.'); } return $app['twig']->render('loisir_form.html.twig', array( 'title' => 'Editer votre loisir', 'loisirForm' => $loisirForm->createView())); } /** * Delete article controller. * * @param integer $id Article id * @param Application $app Silex application */ public function deleteLoisirAction( $id, Application $app ) { // Delete the article $app['dao.loisir']->delete($id); $app['session']->getFlashBag()->add('success', 'Ce loisir à été supprimé avec succé !'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } /** * Edit article controller. * * @param integer $id Article id * @param Request $request Incoming request * @param Application $app Silex application */ public function editArticleAction($id, Request $request, Application $app) { $article = $app['dao.article']->find($id); $articleForm = $app['form.factory']->create(ArticleType::class, $article); $articleForm->handleRequest($request); if ($articleForm->isSubmitted() && $articleForm->isValid()) { $app['dao.article']->save($article); $app['session']->getFlashBag()->add('success', 'The article was successfully updated.'); } return $app['twig']->render('article_form.html.twig', array( 'title' => 'Edit article', 'articleForm' => $articleForm->createView() )); } /** * Delete article controller. * * @param integer $id Article id * @param Application $app Silex application */ public function deleteArticleAction($id, Application $app) { // Delete all associated comments $app['dao.comment']->deleteAllByArticle($id); // Delete the article $app['dao.article']->delete($id); $app['session']->getFlashBag()->add('success', 'The article was successfully removed.'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } /** * Add perso controller. * * @param Request $request Incoming request * @param Application $app Silex application */ public function addPersoAction(Request $request, Application $app) { $perso = new Perso(); $persoForm = $app['form.factory']->create(PersoType::class, $perso); $persoForm->handleRequest($request); if ($persoForm->isSubmitted() && $persoForm->isValid()) { $app['dao.perso']->save($perso); $app['session']->getFlashBag()->add('success', 'The article was successfully created.'); } return $app['twig']->render('perso_form.html.twig', array( 'title' => 'Nouvelles informations personnels', 'persoForm' => $persoForm->createView())); } /** * Edit article controller. * * @param integer $id Article id * @param Request $request Incoming request * @param Application $app Silex application */ public function editPersoAction($id, Request $request, Application $app) { $perso = $app['dao.perso']->find($id); $persoForm = $app['form.factory']->create(PersoType::class, $perso); $persoForm->handleRequest($request); if ($persoForm->isSubmitted() && $persoForm->isValid()) { $app['dao.perso']->save($perso); $app['session']->getFlashBag()->add('success', 'The personnels was successfully updated.'); } return $app['twig']->render('perso_form.html.twig', array( 'title' => 'Editer ces informations personnels', 'persoForm' => $persoForm->createView() )); } /** * Delete article controller. * * @param integer $id Article id * @param Application $app Silex application */ public function deletePersoAction($id, Application $app) { // Delete the article $app['dao.perso']->delete($id); $app['session']->getFlashBag()->add('success', 'Ces information personnels ont été supprimé.'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } /** * Edit comment controller. * * @param integer $id Comment id * @param Request $request Incoming request * @param Application $app Silex application */ public function editCommentAction($id, Request $request, Application $app) { $comment = $app['dao.comment']->find($id); $commentForm = $app['form.factory']->create(CommentType::class, $comment); $commentForm->handleRequest($request); if ($commentForm->isSubmitted() && $commentForm->isValid()) { $app['dao.comment']->save($comment); $app['session']->getFlashBag()->add('success', 'The comment was successfully updated.'); } return $app['twig']->render('comment_form.html.twig', array( 'title' => 'Edit comment', 'commentForm' => $commentForm->createView())); } public function addPortfolioAction(Request $request, Application $app) { $portfolio = new Portfolio(); $portfolioForm = $app['form.factory']->create(PortfolioType::class, $portfolio); $portfolioForm->handleRequest($request); if ($portfolioForm->isSubmitted() && $portfolioForm->isValid()) { $app['dao.portfolio']->save($portfolio); $app['session']->getFlashBag()->add('success', 'The article was successfully created.'); } return $app['twig']->render('portfolio_form.html.twig', array( 'title' => 'Nouvelles informations portfolionnels', 'portfolioForm' => $portfolioForm->createView())); } /** * Edit article controller. * * @param integer $id Article id * @param Request $request Incoming request * @param Application $app Silex application */ public function editPortfolioAction($id, Request $request, Application $app) { $portfolio = $app['dao.portfolio']->find($id); $portfolioForm = $app['form.factory']->create(PortfolioType::class, $portfolio); $portfolioForm->handleRequest($request); if ($portfolioForm->isSubmitted() && $portfolioForm->isValid()) { $app['dao.portfolio']->save($portfolio); $app['session']->getFlashBag()->add('success', 'Vous avez édité cette element avec succés.'); } return $app['twig']->render('portfolio_form.html.twig', array( 'title' => 'Editer ces informations portfolionnels', 'portfolioForm' => $portfolioForm->createView() )); } /** * Delete article controller. * * @param integer $id Article id * @param Application $app Silex application */ public function deletePortfolioAction($id, Application $app) { // Delete the article $app['dao.portfolio']->delete($id); $app['session']->getFlashBag()->add('success', 'Ces information personnels ont été supprimé.'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } /** * Delete comment controller. * * @param integer $id Comment id * @param Application $app Silex application */ public function deleteCommentAction($id, Application $app) { $app['dao.comment']->delete($id); $app['session']->getFlashBag()->add('success', 'The comment was successfully removed.'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } /** * Add user controller. * * @param Request $request Incoming request * @param Application $app Silex application */ public function addUserAction(Request $request, Application $app) { $user = new User(); $userForm = $app['form.factory']->create(UserType::class, $user); $userForm->handleRequest($request); if ($userForm->isSubmitted() && $userForm->isValid()) { // generate a random salt value $salt = substr(md5(time()), 0, 23); $user->setSalt($salt); $plainPassword = $user->getPassword(); // find the default encoder $encoder = $app['security.encoder.bcrypt']; // compute the encoded password $password = $encoder->encodePassword($plainPassword, $user->getSalt()); $user->setPassword($password); $app['dao.user']->save($user); $app['session']->getFlashBag()->add('success', 'The user was successfully created.'); } return $app['twig']->render('user_form.html.twig', array( 'title' => 'New user', 'userForm' => $userForm->createView())); } /** * Edit user controller. * * @param integer $id User id * @param Request $request Incoming request * @param Application $app Silex application */ public function editUserAction($id, Request $request, Application $app) { $user = $app['dao.user']->find($id); $userForm = $app['form.factory']->create(UserType::class, $user); $userForm->handleRequest($request); if ($userForm->isSubmitted() && $userForm->isValid()) { $plainPassword = $user->getPassword(); // find the encoder for the user $encoder = $app['security.encoder_factory']->getEncoder($user); // compute the encoded password $password = $encoder->encodePassword($plainPassword, $user->getSalt()); $user->setPassword($password); $app['dao.user']->save($user); $app['session']->getFlashBag()->add('success', 'The user was successfully updated.'); } return $app['twig']->render('user_form.html.twig', array( 'title' => 'Edit user', 'userForm' => $userForm->createView())); } /** * Delete user controller. * * @param integer $id User id * @param Application $app Silex application */ public function deleteUserAction($id, Application $app) { // Delete all associated comments $app['dao.comment']->deleteAllByUser($id); // Delete the user $app['dao.user']->delete($id); $app['session']->getFlashBag()->add('success', 'The user was successfully removed.'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } // CUSTOM CLASS /** * Add article controller. * * @param Request $request Incoming request * @param Application $app Silex application */ public function addExperienceAction(Request $request, Application $app) { $experience = new Experience(); $experienceForm = $app['form.factory']->create(ExperienceType::class, $experience); $experienceForm->handleRequest($request); if ($experienceForm->isSubmitted() && $experienceForm->isValid()) { $app['dao.experience']->save($experience); $app['session']->getFlashBag()->add('success', 'Vous avez créé une nouvelle experience.'); } return $app['twig']->render('experience_form.html.twig', array( 'title' => 'Nouvelle Experience', 'experienceForm' => $experienceForm->createView())); } /** * Edit article controller. * * @param integer $id Article id * @param Request $request Incoming request * @param Application $app Silex application */ public function editExperienceAction($id, Request $request, Application $app) { $experience = $app['dao.experience']->find($id); $experienceForm = $app['form.factory']->create(ExperienceType::class, $experience); $experienceForm->handleRequest($request); if ( $experienceForm->isSubmitted() && $experienceForm->isValid() ) { $app['dao.experience']->save($experience); $app['session']->getFlashBag()->add('success', 'Votre experience à été enregistré avec succé.'); } return $app['twig']->render('experience_form.html.twig', array( 'title' => 'Editer votre experience', 'experienceForm' => $experienceForm->createView())); } /** * Delete article controller. * * @param integer $id Article id * @param Application $app Silex application */ public function deleteExperienceAction($id, Application $app) { // Delete the article $app['dao.experience']->delete($id); $app['session']->getFlashBag()->add('success', 'Cette experience à été supprimé avec succé !'); // Redirect to admin home page return $app->redirect($app['url_generator']->generate('admin')); } }
RudyMrb/SiteCV_Silex
src/Controller/AdminController.php
PHP
mit
16,728
# encoding: utf-8 require 'test_helper' require 'earth_tools' require 'earth_tools/result/time_zone' require 'mock_lookup' ## # Tests for Time Zone lookups. class TimeZoneTest < MiniTest::Unit::TestCase def setup @result = EarthTools.time_zone(40.71417, -74.00639) @result2 = EarthTools.time_zone(40.71655, -12.12318) @result3 = EarthTools.time_zone(50.21655, -54.87656) end def test_time_zone_returns_result assert_instance_of EarthTools::Result::TimeZone, @result end def test_iso_time iso_time = @result.iso_time assert_instance_of Time, iso_time assert_equal Time.new(2012, 6, 14, 13, 29, 6, '-05:00'), iso_time end def test_local_time local_time = @result.local_time assert_instance_of Time, local_time assert_equal Time.new(2012, 6, 14, 13, 29, 6, '-05:00'), local_time end def test_suffix suffix = @result.suffix assert_instance_of String, suffix assert_equal 'R', suffix end def test_utc_offset utc_offset = @result.utc_offset assert_kind_of Integer, utc_offset assert_equal -5, utc_offset end def test_utc_time utc_time = @result.utc_time assert_instance_of Time, utc_time assert_equal Time.utc(2012, 6, 14, 18, 29, 6), utc_time end def test_dst_as_true assert_equal 'True', @result2.dst assert @result2.dst? end def test_dst_as_false assert_equal 'False', @result3.dst refute @result3.dst? end def test_dst_as_unknown assert_equal 'Unknown', @result.dst assert_nil @result.dst? end end
mckramer/earth_tools
test/time_zone_test.rb
Ruby
mit
1,670
/** * Angular Paginate * @homepage https://github.com/darthwade/angular-paginate * @author Vadym Petrychenko https://github.com/darthwade * @license The MIT License (http://www.opensource.org/licenses/mit-license.php) * @copyright 2014 Vadym Petrychenko */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD define(['angular'], factory); } else if (typeof exports === 'object') { // CommonJS factory(require('angular')); } else { // Browser globals factory(window.angular) } }(function (angular) { 'use strict'; angular.module('darthwade.paginate', []) .provider('$paginate', function () { var provider = this; provider.templateUrl = 'angular-paginate.html'; provider.options = { perPage: 10, // Items count per page. range: 5, // Number of pages neighbouring the current page which will be displayed. boundaryLinks: true, // Whether to display First / Last buttons. directionLinks: true, // Whether to display Previous / Next buttons. rotate: true, // Whether to keep current page in the middle of the visible ones. paramName: 'page', previousText: 'Previous', // Text for previous button nextText: 'Next', // Text for next button moreText: '...' // Text for more button }; provider.$get = function() { var wrapper = function(options) { return new Paginator(options); }; wrapper.getDefaultOptions = function() { return provider.options; }; wrapper.getTemplateUrl = function() { return provider.templateUrl; }; return wrapper; }; /** * Overrides default options * @param {Object} options */ provider.setDefaultOptions = function (options) { angular.extend(provider.options, options); }; provider.setTemplateUrl = function (templateUrl) { provider.templateUrl = templateUrl; }; var Paginator = function(options) { var self = this; var defaultOptions = { $page: 1, $objects: [], $totalCount: 0, $startIndex: 0, $endIndex: 0, $totalPages: 0, onPageChange: angular.noop }; self.page = function (page) { if (self.$page === page) { return; } self.$page = page; calculate(); if (self.onPageChange) { self.onPageChange.call(self); } }; self.options = function (options) { angular.extend(self, options); }; self.previous = function () { if (self.hasPrevious()) { self.page(self.$page - 1); } }; self.next = function () { if (self.hasNext()) { self.page(self.$page + 1); } }; self.hasPrevious = function () { return self.$page > 1; }; self.hasNext = function () { return self.$page < self.$totalPages; }; // Create page object used in template var makePage = function (number, text, active) { return { number: number, text: text, active: active }; }; var getPages = function () { var pages = []; // Default page limits var startPage = 1, endPage = self.$totalPages; var isRanged = self.range < self.$totalPages; // recompute if maxSize if (isRanged) { if (self.rotate) { // Current page is displayed in the middle of the visible ones startPage = Math.max(self.$page - Math.floor(self.range / 2), 1); endPage = startPage + self.range - 1; // Adjust if limit is exceeded if (endPage > self.$totalPages) { endPage = self.$totalPages; startPage = endPage - self.range + 1; } } else { // Visible pages are paginated with maxSize startPage = ((Math.ceil(self.$page / self.range) - 1) * self.range) + 1; // Adjust last page if limit is exceeded endPage = Math.min(startPage + self.range - 1, self.$totalPages); } } // Add page number links for (var number = startPage; number <= endPage; number++) { var page = makePage(number, number, number === self.$page); pages.push(page); } // Add links to move between page sets if (isRanged) { // && !self.rotate var margin = self.boundaryLinks ? 1 : 0; if (startPage - margin > 1) { var previousPageSet = makePage(startPage - 1, self.moreText, false); pages.unshift(previousPageSet); } if (endPage + margin < self.$totalPages) { var nextPageSet = makePage(endPage + 1, self.moreText, false); pages.push(nextPageSet); } } // Add boundary links if needed if (self.boundaryLinks) { if (startPage > 1) { var firstPage = makePage(1, 1, false); pages.unshift(firstPage); } if (endPage < self.$totalPages) { var lastPage = makePage(self.$totalPages, self.$totalPages, false); pages.push(lastPage); } } return pages; }; var calculate = function() { self.$page = parseInt(self.$page) || 1; self.$objects = self.$objects || []; self.$totalCount = parseInt(self.$totalCount) || 0; self.$totalPages = Math.ceil(self.$totalCount / self.perPage); self.$startIndex = (self.$page - 1) * self.perPage; self.$endIndex = self.$startIndex + self.$objects.length; if (self.$endIndex) { self.$startIndex += 1; } self.$pages = getPages(); }; angular.extend(self, provider.options, defaultOptions, options); calculate(); }; return provider; }) .directive('dwPaginate', ['$paginate', function ($paginate) { return { restrict: 'EA', scope: { paginator: '=dwPaginate' }, replace: true, templateUrl: $paginate.getTemplateUrl(), link: function (scope, element, attrs) { } }; }]); }));
darthwade/angular-paginate
angular-paginate.js
JavaScript
mit
6,581
<?php namespace InoOicClient\Oic\Authorization\State\Exception; class StateMismatchException extends \RuntimeException { }
Yusuke-KOMIYAMA/aiv
binder/app/Vendor/ivan-novakov/php-openid-connect-client/src/InoOicClient/Oic/Authorization/State/Exception/StateMismatchException.php
PHP
mit
132
<?php umask(0000); // Définit une permission 0777 use Symfony\Component\ClassLoader\ApcClassLoader; use Symfony\Component\HttpFoundation\Request; $loader = require_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new ApcClassLoader(sha1(__FILE__), $loader); $loader->unregister(); $apcLoader->register(true); */ require_once __DIR__.'/../app/AppKernel.php'; //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel->loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
KartographerZ/web_app
web/app.php
PHP
mit
1,058
<?php namespace PlaygroundDesign\Service; use PlaygroundDesign\Entity\Theme as ThemeEntity; use Laminas\Form\Form; use Laminas\ServiceManager\ServiceManager; use Laminas\Validator\NotEmpty; use Laminas\EventManager\EventManagerAwareTrait; use PlaygroundDesign\Options\ModuleOptions; use DoctrineModule\Validator\NoObjectExists as NoObjectExistsValidator; use Laminas\Stdlib\ErrorHandler; use Laminas\ServiceManager\ServiceLocatorInterface; class Theme { use EventManagerAwareTrait; /** * @var themeMapperInterface */ protected $themeMapper; /** * @var ServiceManager */ protected $serviceManager; /** * @var UserServiceOptionsInterface */ protected $options; public static $files = array('assets.php', 'layout.php', 'theme.php'); public function __construct(ServiceLocatorInterface $locator) { $this->serviceManager = $locator; } /** * * This service is ready for create a theme * * @param array $data * @param string $formClass * * @return \PlaygroundPartnership\Entity\Theme */ public function create(array $data, $formClass) { $valid = new NotEmpty(); if (!$valid->isValid($data['title'])) { return false; } $theme = new ThemeEntity; $form = $this->getServiceManager()->get($formClass); $form->bind($theme); $theme->setImage('tmp'); $form->setData($data); if (!$form->isValid()) { return false; } if (!$this->checkDirectoryTheme($theme, $data)) { mkdir($theme->getBasePath().'/'.$data['area'].'/'.$data['package'].'/'.$data['theme'], 0777, true); } $this->createFiles($theme, $data); $themeMapper = $this->getThemeMapper(); $theme = $themeMapper->insert($theme); $this->uploadImage($theme, $data); $theme = $themeMapper->update($theme); return $theme; } /** * * This service is ready for edit a theme * * @param array $data * @param string $theme * @param string $formClass * * @return \PlaygroundDesignEntity\Theme */ public function edit(array $data, $theme, $formClass) { $valid = new NotEmpty(); if (!$valid->isValid($data['title'])) { return false; } $entityManager = $this->getServiceManager()->get('playgrounddesign_doctrine_em'); $form = $this->getServiceManager()->get($formClass); $form->bind($theme); $form->setData($data); if (!$form->isValid() || !$this->checkDirectoryTheme($theme, $data)) { return false; } $this->uploadImage($theme, $data); $theme = $this->getThemeMapper()->update($theme); return $theme; } public function uploadImage($theme, $data) { if (!empty($data['uploadImage']['tmp_name'])) { $path = $this->getOptions()->getMediaPath() . $data['area'] . DIRECTORY_SEPARATOR . $data['package'] . DIRECTORY_SEPARATOR . $data['theme'] . '/assets/images/screenshots/'; if (!is_dir($path)) { mkdir($path, 0777, true); } $media_url = $this->getOptions()->getMediaUrl() . '/'; move_uploaded_file($data['uploadImage']['tmp_name'], $path . $theme->getId() . "-" . $data['uploadImage']['name']); $theme->setImage($media_url . $theme->getId() . "-" . $data['uploadImage']['name']); } return $theme; } /** * * Check if the directory theme exist * * @param \PlaygroundPartnership\Entity\Theme $theme * @param array $data * * @return bool $bool */ public function checkDirectoryTheme($theme, $data) { $newUrlTheme = $theme->getBasePath().'/'.$data['area'].'/'.$data['package'].'/'.$data['theme']; if (!is_dir($newUrlTheme)) { return false; } return true; } public function createFiles($theme, $data) { foreach (self::$files as $file) { if (file_exists($theme->getBasePath().$data['area'].'/'.$data['package'].'/'.$data['theme'].'/'.$file)) { continue; } $contentAssets = file_get_contents(__DIR__.'/../Templates/'.$file); $contentAssets = str_replace(array('{{area}}', '{{package}}', '{{theme}}', '{{title}}'), array($data['area'], $data['package'], $data['theme'], $data['title']), $contentAssets); file_put_contents($theme->getBasePath().$data['area'].'/'.$data['package'].'/'.$data['theme'].'/'.$file, $contentAssets); } } /** * findById : recupere l'entite en fonction de son id * @param int $id id du theme * * @return PlaygroundDesign\Entity\Theme $theme */ public function findById($id) { return $this->getThemeMapper()->findById($id); } /** * insert : insert en base une entité theme * @param PlaygroundDesign\Entity\Theme $entity theme * * @return PlaygroundDesign\Entity\Theme $theme */ public function insert($entity) { return $this->getThemeMapper()->insert($entity); } /** * insert : met a jour en base une entité theme * @param PlaygroundDesign\Entity\Theme $entity theme * * @return PlaygroundDesign\Entity\Theme $theme */ public function update($entity) { return $this->getThemeMapper()->update($entity); } /** * remove : supprimer une entite theme * @param PlaygroundDesign\Entity\Theme $entity theme * */ public function remove($entity) { $this->getThemeMapper()->remove($entity); } /** * findActiveTheme : recupere des entites en fonction du filtre active * @param boolean $active valeur du champ active * * @return collection $themes collection de PlaygroundDesign\Entity\Theme */ public function findActiveTheme($active = true) { return $this->getThemeMapper()->findActiveTheme($active); } /** * findActiveThemeByArea : recupere des entites active en fonction du filtre Area * @param string $area area du theme * @param boolean $active valeur du champ active * * @return collection $themes collection de PlaygroundDesign\Entity\Theme */ public function findActiveThemeByArea($area, $active = true) { return $this->getThemeMapper()->findActiveThemeByArea($area, $active); } /** * findThemeByAreaPackageAndBase : recupere des entites en fonction des filtre Area, Package et Theme * @param string $area area du theme * @param string $package package du theme * @param string $base base du theme * * @return collection $themes collection de PlaygroundDesign\Entity\Theme */ public function findThemeByAreaPackageAndBase($area, $package, $base) { return $this->getThemeMapper()->findThemeByAreaPackageAndBase($area, $package, $base); } /** * getThemeMapper * * @return ThemeMapperInterface */ public function getThemeMapper() { if (null === $this->themeMapper) { $this->themeMapper = $this->getServiceManager()->get('playgrounddesign_theme_mapper'); } return $this->themeMapper; } /** * setThemeMapper * @param ThemeMapperInterface $themeMapper * * @return PlaygroundPartnership\Entity\Theme Theme */ public function setThemeMapper($themeMapper) { $this->themeMapper = $themeMapper; return $this; } /** * setOptions * @param ModuleOptions $options * * @return PlaygroundDesign\Service\Theme $this */ public function setOptions(ModuleOptions $options) { $this->options = $options; return $this; } /** * getOptions * * @return ModuleOptions $optins */ public function getOptions() { if (!$this->options instanceof ModuleOptions) { $this->setOptions($this->getServiceManager()->get('playgrounddesign_module_options')); } return $this->options; } /** * Retrieve service manager instance * * @return ServiceManager */ public function getServiceManager() { return $this->serviceManager; } }
gregorybesson/PlaygroundDesign
src/Service/Theme.php
PHP
mit
8,422
var express = require('express') var braintree = require('braintree') var router = express.Router() // eslint-disable-line new-cap var gateway = require('../lib/gateway') var TRANSACTION_SUCCESS_STATUSES = [ braintree.Transaction.Status.Authorizing, braintree.Transaction.Status.Authorized, braintree.Transaction.Status.Settled, braintree.Transaction.Status.Settling, braintree.Transaction.Status.SettlementConfirmed, braintree.Transaction.Status.SettlementPending, braintree.Transaction.Status.SubmittedForSettlement ] function formatErrors(errors) { var formattedErrors = '' for (var i in errors) { // eslint-disable-line no-inner-declarations, vars-on-top if (errors.hasOwnProperty(i)) { formattedErrors += 'Error: ' + errors[i].code + ': ' + errors[i].message + '\n' } } return formattedErrors } function createResultObject(transaction) { var result var status = transaction.status if (TRANSACTION_SUCCESS_STATUSES.indexOf(status) !== -1) { result = { header: 'Sweet Success!', icon: 'success', message: 'Your test transaction has been successfully processed. See the Braintree API response and try again.' } } else { result = { header: 'Transaction Failed', icon: 'fail', message: 'Your test transaction has a status of ' + status + '. See the Braintree API response and try again.' } } return result } router.get('/', function (req, res) { res.redirect('/checkouts/new') }) router.get('/checkouts/new', function (req, res) { gateway.clientToken.generate({}, function (err, response) { res.render('checkouts/new', {clientToken: response.clientToken, messages: req.flash('error')}) }) }) router.get('/checkouts/:id', function (req, res) { var result var transactionId = req.params.id gateway.transaction.find(transactionId, function (err, transaction) { result = createResultObject(transaction) res.render('checkouts/show', {transaction: transaction, result: result}) }) }) router.post('/checkouts', function (req, res) { var transactionErrors var amount = req.body.amount // In production you should not take amounts directly from clients var nonce = req.body.payment_method_nonce gateway.transaction.sale({ amount: amount, paymentMethodNonce: nonce, customer: { firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email }, options: { submitForSettlement: true, storeInVaultOnSuccess: true } }, function (err, result) { if (result.success || result.transaction) { res.redirect('checkouts/' + result.transaction.id) } else { transactionErrors = result.errors.deepErrors() req.flash('error', {msg: formatErrors(transactionErrors)}) res.redirect('checkouts/new') } }) }) module.exports = router
alexanderalmstrom/alexanderalmstrom
app/routes/checkout.js
JavaScript
mit
2,862
/** * */ package com.kant.datastructure.stacks; import com.kant.sortingnsearching.MyUtil; /** * http://www.geeksforgeeks.org/the-stock-span-problem/ <br/> * * * The stock span problem is a financial problem where we have a series of n * daily price quotes for a stock and we need to calculate span of stock’s price * for all n days. The span Si of the stock’s price on a given day i is defined * as the maximum number of consecutive days just before the given day, for * which the price of the stock on the current day is less than or equal to its * price on the given day. For example, if an array of 7 days prices is given as * {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days * are {1, 1, 1, 2, 1, 4, 6} * * @author shaskant * */ public class StockSpanProblem { int[] stockData;// prices /** * */ public StockSpanProblem(int[] stockData) { this.stockData = stockData; } /** * General approach. TESTED * * @return */ public int[] getStackSpan() { int[] result = new int[stockData.length]; for (int i = 0; i < stockData.length; i++) { result[i] = 1; for (int j = i - 1; j > 0; j--) { if (stockData[i] > stockData[j]) result[i]++; } } return result; } /** * TESTED * * @return */ public int[] getStackSpanOptimal() { int[] result = new int[stockData.length]; result[0] = 1; // store indexes Stack<Integer> stack = new StackListImplementation<>(false); stack.push(0); for (int i = 1; i < stockData.length; i++) { // pop as long as top element is lesser. while (!stack.isEmpty() && stockData[stack.peek().intValue()] <= stockData[i]) { stack.pop(); } // if stack is empty , current stock price is greater than all // before it , else index difference between current and index of // greater element at top of stack result[i] = (stack.isEmpty()) ? (i + 1) : (i - stack.peek()); stack.push(i); } return result; } /** * * @param args */ public static void main(String[] args) { StockSpanProblem stockSpan = new StockSpanProblem(new int[] { 100, 80, 60, 70, 60, 75, 85 }); int[] result = stockSpan.getStackSpanOptimal(); MyUtil.printArrayInt(result); } }
thekant/myCodeRepo
src/com/kant/datastructure/stacks/StockSpanProblem.java
Java
mit
2,329
<?php namespace Eggbe\Helper; use \Eggbe\Helper\Abstractions\AHelper; class Hash extends AHelper { /** * @param int $length * @return string * @throws \Exception */ public final static function solt($length){ if ((int)$length > 62){ throw new \Exception('Max solt length can not be more that 62 characters!'); } return substr(str_shuffle(implode(array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9')))), 0, $length); } /** * @const int */ const HASH_TYPE_MD5 = 1; /** * @param int $type * @param string $value * @return bool * @throws \Exception */ public final static function make($type, $value){ switch((int)$type){ case self::HASH_TYPE_MD5: return md5(implode(Arr::simplify(array_slice(func_get_args(), 1)))); } throw new \Exception('Unknown validation type "' . $type . '"!'); } /** * @param string $value * @param int $type * @return bool * @throws \Exception */ public final static function validate($value, $type){ switch((int)$type){ case self::HASH_TYPE_MD5: return strlen(($value = strtolower(trim($value)))) == 32 && ctype_xdigit($value); } throw new \Exception('Unknown validation type "' . $type . '"!'); } }
eggbe/helpers
src/Hash.php
PHP
mit
1,219
//****************************************************************************************************** // FrequencyValue.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 11/12/2004 - J. Ritchie Carroll // Generated original version of source code. // 09/15/2009 - Stephen C. Wills // Added new header and license agreement. // 12/17/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; using System.Runtime.Serialization; namespace GSF.PhasorProtocols.BPAPDCstream { /// <summary> /// Represents the BPA PDCstream implementation of a <see cref="IFrequencyValue"/>. /// </summary> [Serializable] public class FrequencyValue : FrequencyValueBase { #region [ Constructors ] /// <summary> /// Creates a new <see cref="FrequencyValue"/>. /// </summary> /// <param name="parent">The <see cref="IDataCell"/> parent of this <see cref="FrequencyValue"/>.</param> /// <param name="frequencyDefinition">The <see cref="IFrequencyDefinition"/> associated with this <see cref="FrequencyValue"/>.</param> public FrequencyValue(IDataCell parent, IFrequencyDefinition frequencyDefinition) : base(parent, frequencyDefinition) { } /// <summary> /// Creates a new <see cref="FrequencyValue"/> from specified parameters. /// </summary> /// <param name="parent">The <see cref="DataCell"/> parent of this <see cref="FrequencyValue"/>.</param> /// <param name="frequencyDefinition">The <see cref="FrequencyDefinition"/> associated with this <see cref="FrequencyValue"/>.</param> /// <param name="frequency">The floating point value that represents this <see cref="FrequencyValue"/>.</param> /// <param name="dfdt">The floating point value that represents the change in this <see cref="FrequencyValue"/> over time.</param> public FrequencyValue(DataCell parent, FrequencyDefinition frequencyDefinition, double frequency, double dfdt) : base(parent, frequencyDefinition, frequency, dfdt) { } /// <summary> /// Creates a new <see cref="FrequencyValue"/> from serialization parameters. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param> /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param> protected FrequencyValue(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion #region [ Properties ] /// <summary> /// Gets or sets the <see cref="DataCell"/> parent of this <see cref="FrequencyValue"/>. /// </summary> public new virtual DataCell Parent { get => base.Parent as DataCell; set => base.Parent = value; } /// <summary> /// Gets or sets the <see cref="FrequencyDefinition"/> associated with this <see cref="FrequencyValue"/>. /// </summary> public new virtual FrequencyDefinition Definition { get => base.Definition as FrequencyDefinition; set => base.Definition = value; } /// <summary> /// Gets the length of the <see cref="BodyImage"/>. /// </summary> /// <remarks> /// The base implementation assumes fixed integer values are represented as 16-bit signed /// integers and floating point values are represented as 32-bit single-precision floating-point /// values (i.e., short and float data types respectively). /// </remarks> protected override int BodyLength => Definition.Parent.IsPdcBlockSection ? 2 : base.BodyLength; // PMUs in PDC block do not include Df/Dt /// <summary> /// Gets the binary body image of the <see cref="FrequencyValue"/> object. /// </summary> protected override byte[] BodyImage { get { // PMUs in PDC block do not include Df/Dt if (!Definition.Parent.IsPdcBlockSection) return base.BodyImage; byte[] buffer = new byte[2]; BigEndian.CopyBytes((short)UnscaledFrequency, buffer, 0); return buffer; } } #endregion #region [ Methods ] /// <summary> /// Parses the binary body image. /// </summary> /// <param name="buffer">Binary image to parse.</param> /// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param> /// <param name="length">Length of valid data within <paramref name="buffer"/>.</param> /// <returns>The length of the data that was parsed.</returns> protected override int ParseBodyImage(byte[] buffer, int startIndex, int length) { // PMUs in PDC block do not include Df/Dt if (Definition.Parent.IsPdcBlockSection) { UnscaledFrequency = BigEndian.ToInt16(buffer, startIndex); return 2; } return base.ParseBodyImage(buffer, startIndex, length); } #endregion #region [ Static ] // Static Methods // Calculates binary length of a frequency value based on its definition internal static uint CalculateBinaryLength(IFrequencyDefinition definition) { // The frequency definition will determine the binary length based on data format return (uint)new FrequencyValue(null, definition).BinaryLength; } // Delegate handler to create a new BPA PDCstream frequency value internal static IFrequencyValue CreateNewValue(IDataCell parent, IFrequencyDefinition definition, byte[] buffer, int startIndex, out int parsedLength) { IFrequencyValue frequency = new FrequencyValue(parent, definition); parsedLength = frequency.ParseBinaryImage(buffer, startIndex, 0); return frequency; } #endregion } }
GridProtectionAlliance/gsf
Source/Libraries/GSF.PhasorProtocols/BPAPDCstream/FrequencyValue.cs
C#
mit
7,224
<ul class="context_menu"> <li><a href="?module=menu">Retour aux menus</a></li> </ul> <form action="?module=menu&action=edit" method="post"> <input type="hidden" name="menuId" value="<?php echo $menu->getId(); ?>" /> <label class="mandatory">Titre</label> <input type="text" name="title" value="<?php echo stripslashes($menu->getTitle()); ?>" /> <label>Commentaire</label> <textarea name="comment"><?php echo stripslashes($menu->getComment()); ?></textarea> <button type="submit">Modifier</button> </form>
fabienInizan/menuPlugin
templates/admin/menu/displayEditForm.php
PHP
mit
516
import { Component } from 'react'; import Router from 'next/router'; import io from 'socket.io-client'; import fetch from 'isomorphic-fetch'; import Page from '../../layouts/page.js'; import Slide from '../../components/slide.js'; import Code from '../../components/code.js' import Emojis from '../../components/emojis.js'; import SlideNavigation from '../../components/slidenavigation.js'; import { Title, Headline, Enum, Column } from '../../components/text.js'; import withRedux from 'next-redux-wrapper'; import { makeStore, _changeRole } from '../../components/store.js'; class SlideFour extends Component { constructor(props) { super(props); this.props = props; this.state = { socket: undefined }; this.emojiModule = this.emojiModule.bind(this); this.navModule = this.navModule.bind(this); } static async getInitialProps({ isServer }) { let host = 'http://localhost:3000'; if (!isServer) host = `${location.protocol}//${location.host}`; const response = await fetch(`${host}/static/html_template.txt`); const htmlCode = await response.text(); return { htmlCode }; } componentDidMount() { // socket if (!this.state.socket) { const socket = io(`${location.protocol}//${location.host}/`); socket.on('viewer-update', data => { if (this.props.role === 'VIEWER') { Router.replace(data.url); } }); this.setState(state => ( {socket: socket} )); } } componentWillUnmount() { if (this.state.socket) this.state.socket.close(); } emojiModule() { if (this.state.socket) { return ( <Emojis socket={this.state.socket} /> ); } } navModule() { if (this.state.socket && this.props.role) { return ( <SlideNavigation role={this.props.role} socket={this.state.socket} prev="/slides/0x04_y_tho" next="/slides/0x06_include" /> ); } } render() { return ( <Page> <Slide> <Title>0x05_call_by_reference</Title> <Headline>Anwendung im Browser</Headline> <Column> <Enum>JavaScript kann direkt im { '<script>-Tag' } geschrieben werden</Enum> <Enum>oder als externe Datei durch das src-Attribut eingebunden werden</Enum> </Column> <Column> <Code language='html'>{ this.props.htmlCode }</Code> </Column> { this.navModule() } </Slide> { this.emojiModule() } </Page> ); } }; const mapStateToProps = state => ({ role: state.role }); const mapDispatchToProps = dipatch => ({ changeRole: role => (dispatch(_changeRole(role))) }); export default withRedux(makeStore, mapStateToProps, mapDispatchToProps)(SlideFour);
AndyBitz/dme11a-js-presentation
pages/slides/0x05_call_by_reference.js
JavaScript
mit
2,834
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Examlpe")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Examlpe")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0a3acc12-4731-41d0-9c54-8985a348bf4d")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
msotiroff/Programming-FUNDAMENTALS
Practice/Lists/EqualSumAfterExtraction/Examlpe/Properties/AssemblyInfo.cs
C#
mit
1,390
/* eslint-disable promise/always-return */ import { runAuthenticatedQuery } from "schema/v2/test/utils" import gql from "lib/gql" describe("Me", () => { describe("ShowsByFollowedArtists", () => { it("returns shows by followed artists", async () => { const query = gql` { me { showsByFollowedArtists( first: 100 sort: NAME_ASC status: UPCOMING ) { totalCount edges { node { name } } } } } ` const expectedConnectionData = { totalCount: 2, edges: [ { node: { name: "Show 1", }, }, { node: { name: "Show 2", }, }, ], } const followedArtistsShowsLoader = jest.fn(async () => ({ headers: { "x-total-count": 2 }, body: [ { name: "Show 1", }, { name: "Show 2", }, ], })) const context = { meLoader: () => Promise.resolve({}), followedArtistsShowsLoader, } const { me: { showsByFollowedArtists }, } = await runAuthenticatedQuery(query, context) expect(showsByFollowedArtists).toEqual(expectedConnectionData) expect(followedArtistsShowsLoader).toHaveBeenCalledWith({ offset: 0, size: 100, sort: "name", status: "upcoming", total_count: true, }) }) }) })
artsy/metaphysics
src/schema/v2/me/__tests__/showsByFollowedArtists.test.ts
TypeScript
mit
1,640
<?php namespace scriptorium\UserBundle\Entity; use FOS\UserBundle\Entity\User as BaseUser; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Security\Core\Util\SecureRandom; /** * @ORM\Entity * @ORM\Table(name="fos_user") */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(name="registration_date", type="datetime") */ protected $registrationDate; /** * @ORM\Column(name="edition_date", type="datetime") */ protected $editionDate; /** * @Assert\File(maxSize="2048k") * @Assert\Image(mimeTypesMessage="Please upload a valid image.") */ protected $profilePictureFile; // for temporary storage private $tempProfilePicturePath; /** * @ORM\Column(type="string", length=255, nullable=true) */ protected $profilePicturePath; public function __construct() { parent::__construct(); // default registration date $this->registrationDate = new \DateTime(); // default edition date $this->editionDate = new \DateTime(); } /** * Get id * @return integer */ public function getId() { return $this->id; } /** * Get registration date * @return DateTime */ public function getRegistrationDate() { return $this->registrationDate; } /** * Set registration date * @param $date DateTime The registration date */ public function setRegistrationDate($date) { $this->registrationDate = $date; } /** * Get edition date * @return DateTime */ public function getEditionDate() { return $this->editionDate; } /** * Set edition date * @param $date DateTime The edition date */ public function setEditionDate($date) { $this->registrationDate = $date; } /** * Set registrationDate * @param $date DateTime The registration date */ public function setEditionDateNow() { $this->setEditionDate(new \DateTime()); } /** * Sets the file used for profile picture uploads * * @param UploadedFile $file * @return object */ public function setProfilePictureFile(UploadedFile $file = null) { // set the value of the holder $this->profilePictureFile = $file; // check if we have an old image path if (isset($this->profilePicturePath)) { // store the old name to delete after the update $this->tempProfilePicturePath = $this->profilePicturePath; $this->profilePicturePath = null; } else { $this->profilePicturePath = 'initial'; } return $this; } /** * Get the file used for profile picture uploads * * @return UploadedFile */ public function getProfilePictureFile() { return $this->profilePictureFile; } /** * Set profilePicturePath * * @param string $profilePicturePath * @return User */ public function setProfilePicturePath($profilePicturePath) { $this->profilePicturePath = $profilePicturePath; return $this; } /** * Get profilePicturePath * * @return string */ public function getProfilePicturePath() { return $this->profilePicturePath; } /** * Get the absolute path of the profilePicturePath */ public function getProfilePictureAbsolutePath() { return null === $this->profilePicturePath ? null : $this->getUploadRootDir().'/'.$this->profilePicturePath; } /** * Get root directory for file uploads * * @return string */ protected function getUploadRootDir($type='profilePicture') { // the absolute directory path where uploaded // documents should be saved return __DIR__.'/../../../../web/'.$this->getUploadDir($type); } /** * Specifies where in the /web directory profile pic uploads are stored * * @return string */ protected function getUploadDir($type='profilePicture') { // the type param is to change these methods at a later date for more file uploads // get rid of the __DIR__ so it doesn't screw up // when displaying uploaded doc/image in the view. return 'uploads/user/profilepics'; } /** * Get the web path for the user * * @return string */ public function getWebProfilePicturePath() { return '/'.$this->getUploadDir().'/'.$this->getProfilePicturePath(); } /** * @ORM\PrePersist() * @ORM\PreUpdate() */ public function preUploadProfilePicture() { if (null !== $this->getProfilePictureFile()) { // a file was uploaded // generate a unique filename $filename = $this->generateRandomProfilePictureFilename(); $this->setProfilePicturePath($filename.'.'.$this->getProfilePictureFile()->guessExtension()); } } /** * Generates a 32 char long random filename * * @return string */ public function generateRandomProfilePictureFilename() { $count = 0; do { $generator = new SecureRandom(); $random = $generator->nextBytes(16); $randomString = bin2hex($random); $count++; } while (file_exists($this->getUploadRootDir().'/'.$randomString.'.'.$this->getProfilePictureFile()->guessExtension()) && $count < 50); return $randomString; } /** * @ORM\PostPersist() * @ORM\PostUpdate() * * Upload the profile picture * * @return mixed */ public function uploadProfilePicture() { // check there is a profile pic to upload if ($this->getProfilePictureFile() === null) { return; } // if there is an error when moving the file, an exception will // be automatically thrown by move(). This will properly prevent // the entity from being persisted to the database on error $this->getProfilePictureFile()->move($this->getUploadRootDir(), $this->getProfilePicturePath()); // check if we have an old image if (isset($this->tempProfilePicturePath) && file_exists($this->getUploadRootDir().'/'.$this->tempProfilePicturePath)) { // delete the old image unlink($this->getUploadRootDir().'/'.$this->tempProfilePicturePath); // clear the temp image path $this->tempProfilePicturePath = null; } $this->profilePictureFile = null; } /** * @ORM\PostRemove() */ public function removeProfilePictureFile() { if ($file = $this->getProfilePictureAbsolutePath() && file_exists($this->getProfilePictureAbsolutePath())) { unlink($file); } } }
Komrod/UserScriptorium
src/scriptorium/UserBundle/Entity/User.php
PHP
mit
7,423
package com.jasonlam604.stocktechnicals.indicators; import com.jasonlam604.stocktechnicals.util.NumberFormatter; /** * Moving Average Convergence/Divergence Oscillator */ public class MovingAverageConvergenceDivergence { private static final int CROSSOVER_NONE = 0; private static final int CROSSOVER_POSITIVE = 1; private static final int CROSSOVER_NEGATIVE = -1; private double[] prices; private double[] macd; private double[] signal; private double[] diff; private int[] crossover; public MovingAverageConvergenceDivergence calculate(double[] prices, int fastPeriod, int slowPeriod, int signalPeriod) throws Exception { this.prices = prices; this.macd = new double[prices.length]; this.signal = new double[prices.length]; this.diff = new double[prices.length]; this.crossover = new int[prices.length]; ExponentialMovingAverage emaShort = new ExponentialMovingAverage(); emaShort.calculate(prices, fastPeriod).getEMA(); ExponentialMovingAverage emaLong = new ExponentialMovingAverage(); emaLong.calculate(prices, slowPeriod).getEMA(); for (int i = slowPeriod - 1; i < this.prices.length; i++) { this.macd[i] = NumberFormatter.round(emaShort.getEMA()[i] - emaLong.getEMA()[i]); } ExponentialMovingAverage signalEma = new ExponentialMovingAverage(); this.signal = signalEma.calculate(this.macd, signalPeriod).getEMA(); for (int i = 0; i < this.macd.length; i++) { this.diff[i] = this.macd[i] - this.signal[i]; if (this.diff[i] > 0 && this.diff[i - 1] < 0) { this.crossover[i] = MovingAverageConvergenceDivergence.CROSSOVER_POSITIVE; } else if (this.diff[i] < 0 && this.diff[i - 1] > 0) { this.crossover[i] = MovingAverageConvergenceDivergence.CROSSOVER_NEGATIVE; } else { this.crossover[i] = MovingAverageConvergenceDivergence.CROSSOVER_NONE; } } return this; } public double[] getMACD() { return this.macd; } public double[] getSignal() { return this.signal; } public double[] getDiff() { return this.diff; } public int[] getCrossover() { return this.crossover; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.prices.length; i++) { sb.append(String.format("%02.2f", this.prices[i])); sb.append(" "); sb.append(String.format("%02.2f", this.macd[i])); sb.append(" "); sb.append(String.format("%02.2f", this.signal[i])); sb.append(" "); sb.append(String.format("%02.2f", this.diff[i])); sb.append(" "); sb.append(String.format("%d", this.crossover[i])); sb.append(" "); sb.append("\n"); } return sb.toString(); } }
jasonlam604/StockTechnicals
src/com/jasonlam604/stocktechnicals/indicators/MovingAverageConvergenceDivergence.java
Java
mit
2,631
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLES2Prerequisites.h" #include "OgreGpuProgram.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreLogManager.h" #include "OgreRoot.h" #include "OgreStringConverter.h" #include "OgreGLUtil.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Support.h" #include "OgreGLSLESProgram.h" #include "OgreGLSLESProgramManager.h" #include "OgreGLSLPreprocessor.h" namespace Ogre { //----------------------------------------------------------------------- #if !OGRE_NO_GLES2_GLSL_OPTIMISER GLSLESProgram::CmdOptimisation GLSLESProgram::msCmdOptimisation; #endif //----------------------------------------------------------------------- //----------------------------------------------------------------------- GLSLESProgram::GLSLESProgram(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : GLSLShaderCommon(creator, name, handle, group, isManual, loader) , mGLShaderHandle(0) , mGLProgramHandle(0) #if !OGRE_NO_GLES2_GLSL_OPTIMISER , mIsOptimised(false) , mOptimiserEnabled(false) #endif { if (createParamDictionary("GLSLESProgram")) { setupBaseParamDictionary(); ParamDictionary* dict = getParamDictionary(); dict->addParameter(ParameterDef("preprocessor_defines", "Preprocessor defines use to compile the program.", PT_STRING),&msCmdPreprocessorDefines); #if !OGRE_NO_GLES2_GLSL_OPTIMISER dict->addParameter(ParameterDef("use_optimiser", "Should the GLSL optimiser be used. Default is false.", PT_BOOL),&msCmdOptimisation); #endif } // Manually assign language now since we use it immediately mSyntaxCode = "glsles"; // There is nothing to load mLoadFromFile = false; } //--------------------------------------------------------------------------- GLSLESProgram::~GLSLESProgram() { // Have to call this here reather than in Resource destructor // since calling virtual methods in base destructors causes crash if (isLoaded()) { unload(); } else { unloadHighLevel(); } } //--------------------------------------------------------------------------- #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLSLESProgram::notifyOnContextLost() { unloadHighLevelImpl(); } #endif GLuint GLSLESProgram::createGLProgramHandle() { if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) return 0; if (mGLProgramHandle) return mGLProgramHandle; OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram()); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { glLabelObjectEXT(GL_PROGRAM_OBJECT_EXT, mGLProgramHandle, 0, mName.c_str()); } return mGLProgramHandle; } bool GLSLESProgram::compile(bool checkErrors) { if (mCompiled == 1) { return true; } // Only create a shader object if glsl es is supported if (isSupported()) { // Create shader object GLenum shaderType = 0x0000; if (mType == GPT_VERTEX_PROGRAM) { shaderType = GL_VERTEX_SHADER; } else if (mType == GPT_FRAGMENT_PROGRAM) { shaderType = GL_FRAGMENT_SHADER; } OGRE_CHECK_GL_ERROR(mGLShaderHandle = glCreateShader(shaderType)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { glLabelObjectEXT(GL_SHADER_OBJECT_EXT, mGLShaderHandle, 0, mName.c_str()); } createGLProgramHandle(); } // Add preprocessor extras and main source if (!mSource.empty()) { const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); // Fix up the source in case someone forgot to redeclare gl_Position if (caps->hasCapability(RSC_GLSL_SSO_REDECLARE) && mType == GPT_VERTEX_PROGRAM) { size_t versionPos = mSource.find("#version"); int shaderVersion = StringConverter::parseInt(mSource.substr(versionPos+9, 3)); size_t belowVersionPos = mSource.find('\n', versionPos) + 1; if(shaderVersion >= 300) { // Check that it's missing and that this shader has a main function, ie. not a child shader. if(mSource.find("out highp vec4 gl_Position") == String::npos) { mSource.insert(belowVersionPos, "out highp vec4 gl_Position;\nout highp float gl_PointSize;\n"); } if(mSource.find("#extension GL_EXT_separate_shader_objects : require") == String::npos) { mSource.insert(belowVersionPos, "#extension GL_EXT_separate_shader_objects : require\n"); } } } #if !OGRE_NO_GLES2_GLSL_OPTIMISER const char *source = (getOptimiserEnabled() && getIsOptimised()) ? mOptimisedSource.c_str() : mSource.c_str(); #else const char *source = mSource.c_str(); #endif OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL)); } if (checkErrors) GLSLES::logObjectInfo("GLSL ES compiling: " + mName, mGLShaderHandle); OGRE_CHECK_GL_ERROR(glCompileShader(mGLShaderHandle)); // Check for compile errors OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &mCompiled)); if(!mCompiled && checkErrors) { String message = GLSLES::logObjectInfo("GLSL ES compile log: " + mName, mGLShaderHandle); checkAndFixInvalidDefaultPrecisionError(message); } // Log a message that the shader compiled successfully. if (mCompiled && checkErrors) GLSLES::logObjectInfo("GLSL ES compiled: " + mName, mGLShaderHandle); return (mCompiled == 1); } #if !OGRE_NO_GLES2_GLSL_OPTIMISER //----------------------------------------------------------------------- void GLSLESProgram::setOptimiserEnabled(bool enabled) { if(mOptimiserEnabled != enabled && mOptimiserEnabled && mCompiled == 1) { OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); } mGLShaderHandle = 0; mGLProgramHandle = 0; mCompiled = 0; } mOptimiserEnabled = enabled; } #endif //----------------------------------------------------------------------- void GLSLESProgram::createLowLevelImpl(void) { } //----------------------------------------------------------------------- void GLSLESProgram::unloadHighLevelImpl(void) { if (isSupported()) { // LogManager::getSingleton().logMessage("Deleting shader " + StringConverter::toString(mGLShaderHandle) + // " and program " + StringConverter::toString(mGLProgramHandle)); OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) { OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); } // destroy all programs using this shader GLSLESProgramManager::getSingletonPtr()->destroyAllByShader(this); mGLShaderHandle = 0; mGLProgramHandle = 0; mCompiled = 0; mLinked = 0; } } //----------------------------------------------------------------------- void GLSLESProgram::buildConstantDefinitions() const { // We need an accurate list of all the uniforms in the shader, but we // can't get at them until we link all the shaders into a program object. // Therefore instead, parse the source code manually and extract the uniforms createParameterMappingStructures(true); GLSLESProgramManager::getSingleton().extractUniformsFromGLSL(mSource, *mConstantDefs, mName); } //----------------------------------------------------------------------- #if !OGRE_NO_GLES2_GLSL_OPTIMISER String GLSLESProgram::CmdOptimisation::doGet(const void *target) const { return StringConverter::toString(static_cast<const GLSLESProgram*>(target)->getOptimiserEnabled()); } void GLSLESProgram::CmdOptimisation::doSet(void *target, const String& val) { static_cast<GLSLESProgram*>(target)->setOptimiserEnabled(StringConverter::parseBool(val)); } #endif //----------------------------------------------------------------------- void GLSLESProgram::attachToProgramObject( const GLuint programObject ) { // LogManager::getSingleton().logMessage("Attaching shader " + StringConverter::toString(mGLShaderHandle) + // " to program " + StringConverter::toString(programObject)); OGRE_CHECK_GL_ERROR(glAttachShader(programObject, mGLShaderHandle)); } //----------------------------------------------------------------------- void GLSLESProgram::detachFromProgramObject( const GLuint programObject ) { // LogManager::getSingleton().logMessage("Detaching shader " + StringConverter::toString(mGLShaderHandle) + // " to program " + StringConverter::toString(programObject)); OGRE_CHECK_GL_ERROR(glDetachShader(programObject, mGLShaderHandle)); } //----------------------------------------------------------------------- const String& GLSLESProgram::getLanguage(void) const { static const String language = "glsles"; return language; } //----------------------------------------------------------------------- Ogre::GpuProgramParametersSharedPtr GLSLESProgram::createParameters( void ) { GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters(); params->setTransposeMatrices(true); return params; } //----------------------------------------------------------------------- void GLSLESProgram::checkAndFixInvalidDefaultPrecisionError( String &message ) { String precisionQualifierErrorString = ": 'Default Precision Qualifier' : invalid type Type for default precision qualifier can be only float or int"; vector< String >::type linesOfSource = StringUtil::split(mSource, "\n"); if( message.find(precisionQualifierErrorString) != String::npos ) { LogManager::getSingleton().logMessage("Fixing invalid type Type for default precision qualifier by deleting bad lines the re-compiling"); // remove relevant lines from source vector< String >::type errors = StringUtil::split(message, "\n"); // going from the end so when we delete a line the numbers of the lines before will not change for(int i = static_cast<int>(errors.size()) - 1 ; i != -1 ; i--) { String & curError = errors[i]; size_t foundPos = curError.find(precisionQualifierErrorString); if(foundPos != String::npos) { String lineNumber = curError.substr(0, foundPos); size_t posOfStartOfNumber = lineNumber.find_last_of(':'); if (posOfStartOfNumber != String::npos) { lineNumber = lineNumber.substr(posOfStartOfNumber + 1, lineNumber.size() - (posOfStartOfNumber + 1)); if (StringConverter::isNumber(lineNumber)) { int iLineNumber = StringConverter::parseInt(lineNumber); linesOfSource.erase(linesOfSource.begin() + iLineNumber - 1); } } } } // rebuild source StringStream newSource; for(size_t i = 0; i < linesOfSource.size() ; i++) { newSource << linesOfSource[i] << "\n"; } mSource = newSource.str(); const char *source = mSource.c_str(); OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL)); if (compile()) { LogManager::getSingleton().logMessage("The removing of the lines fixed the invalid type Type for default precision qualifier error."); } else { LogManager::getSingleton().logMessage("The removing of the lines didn't help."); } } } //----------------------------------------------------------------------------- void GLSLESProgram::bindProgram(void) { // Tell the Link Program Manager what shader is to become active switch (mType) { case GPT_VERTEX_PROGRAM: GLSLESProgramManager::getSingleton().setActiveVertexShader( this ); break; case GPT_FRAGMENT_PROGRAM: GLSLESProgramManager::getSingleton().setActiveFragmentShader( this ); break; case GPT_GEOMETRY_PROGRAM: default: break; } } //----------------------------------------------------------------------------- void GLSLESProgram::unbindProgram(void) { // Tell the Link Program Manager what shader is to become inactive if (mType == GPT_VERTEX_PROGRAM) { GLSLESProgramManager::getSingleton().setActiveVertexShader( NULL ); } else if (mType == GPT_FRAGMENT_PROGRAM) { GLSLESProgramManager::getSingleton().setActiveFragmentShader( NULL ); } } //----------------------------------------------------------------------------- void GLSLESProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) { // Link can throw exceptions, ignore them at this point try { // Activate the link program object GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram(); // Pass on parameters from params to program object uniforms linkProgram->updateUniforms(params, mask, mType); } catch (Exception& e) {} } //----------------------------------------------------------------------------- void GLSLESProgram::bindProgramSharedParameters(GpuProgramParametersSharedPtr params, uint16 mask) { // Link can throw exceptions, ignore them at this point try { // Activate the link program object GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram(); // Pass on parameters from params to program object uniforms linkProgram->updateUniformBlocks(params, mask, mType); } catch (Exception& e) {} } //----------------------------------------------------------------------------- void GLSLESProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params) { // Activate the link program object GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram(); // Pass on parameters from params to program object uniforms linkProgram->updatePassIterationUniforms( params ); } //----------------------------------------------------------------------------- size_t GLSLESProgram::calculateSize(void) const { size_t memSize = 0; // Delegate Names memSize += sizeof(GLuint); memSize += sizeof(GLenum); memSize += GpuProgram::calculateSize(); return memSize; } }
RealityFactory/ogre
RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgram.cpp
C++
mit
18,117
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package consolealiensgame; import alieninterfaces.*; import java.lang.reflect.Constructor; /** * * @author guberti */ public class AlienContainer { public final String alienPackageName; public final String alienClassName; public final Constructor<?> alienConstructor; private final Alien alien; private final AlienAPI api; int tech; int energy; boolean fought; public int x; public int y; public boolean action; // Whether the alien has performed an action this turn // Declare stats here // // Heads up: This constructs an AlienContainer and contained Alien // public AlienContainer(int x, int y, String alienPackageName, String alienClassName, Constructor<?> cns, int energy, int tech) { Alien a; this.alienPackageName = alienPackageName; this.alienClassName = alienClassName; this.alienConstructor = cns; this.energy = energy; this.tech = tech; this.api = new AlienAPI(this); // construct and initialize alien try { a = (Alien) cns.newInstance(); a.init(this.api); } catch (Throwable t) { a = null; t.printStackTrace(); } this.alien = a; } public void move(ViewImplementation view) throws NotEnoughTechException { // Whether the move goes off the board will be determined by the grid api.view = view; MoveDir direction = alien.getMove(); checkMove(direction); // Throws an exception if illegal x += direction.x(); y += direction.y(); } public void kill() { energy = Integer.MIN_VALUE; } public Action getAction(ViewImplementation view) throws NotEnoughEnergyException, UnknownActionException { api.view = view; Action action = alien.getAction(); switch (action.code) { case None: case Gain: return new Action (action.code); case Research: if (tech > energy) { // If the tech can't be researched due to lack of energy throw new NotEnoughEnergyException(); } // Otherwise return new Action (ActionCode.Research, tech); case Spawn: if (action.power + 3 > energy) { throw new NotEnoughEnergyException(); } return action; default: throw new UnknownActionException(); } } public int fight() throws NotEnoughEnergyException, NotEnoughTechException { int fightPower = 0; //alien.getFightPower(api); GM need to fix this up after reconciling fighting into Action // If the alien cannot fight with the amount of energy it wants // Throw the appropriate exception if (fightPower > energy) { throw new NotEnoughEnergyException(); } if (fightPower > tech) { throw new NotEnoughTechException(); } // If the move is valid, subtract the energy expended energy -= fightPower; // Return how much power the alien will fight with return fightPower; } private void checkMove(MoveDir direction) throws NotEnoughTechException { // If the move is farther than the alien has the tech to move if (Math.pow(direction.x(), 2) + Math.pow(direction.y(), 2) > Math.pow(tech, 2)) { throw new NotEnoughTechException(); } } } class NotEnoughEnergyException extends Exception {} class NotEnoughTechException extends Exception {} class UnknownActionException extends Exception {}
guberti/AliensGame
ConsoleAliensGame/src/consolealiensgame/AlienContainer.java
Java
mit
4,017
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Example = mongoose.model('Example'), _ = require('lodash'), upload = require('./upload'); /** * Find example by id */ exports.example = function(req, res, next, id) { Example.load(id, function(err, example) { if (err) return next(err); if (!example) return next(new Error('Failed to load example ' + id)); req.example = example; next(); }); }; /** * Create a example */ exports.create = function(req, res) { var example = new Example(req.body); example.user = req.user; example.save(function(err) { if (err) { return res.send('/login', { errors: err.errors, example: example }); } else { res.jsonp(example); } }); }; /** * Update a example */ exports.update = function(req, res) { var example = req.example; example = _.extend(example, req.body); example.save(function(err) { if (err) { console.log("Error -" + err); return res.send('/login', { errors: err, example: example }); } else { console.log("Example Saved - " + example); res.jsonp(example); } }); }; /** * Delete an example */ exports.destroy = function(req, res) { var example = req.example; example.remove(function(err) { if (err) { return res.send('/login', { errors: err.errors, example: example }); } else { res.jsonp(example); } }); }; /** * Show an example */ exports.show = function(req, res) { res.jsonp(req.example); }; /** * List of Examples */ exports.all = function(req, res) { Example.find().sort('-created').populate('user', 'name username').exec(function(err, examples) { if (err) { res.render('error', { status: 500 }); } else { res.jsonp(examples); } }); };
dylanlawrence/ango
lib/controllers/example.js
JavaScript
mit
2,149
class ApplicationMailer < ActionMailer::Base helper Common::PageHelper end
jbox-web/media-server
app/mailers/application_mailer.rb
Ruby
mit
77
import { fireShuffleTasks } from 'src/model/ModelBase'; import { REFERENCE } from 'config/types'; import { rebindMatch } from 'shared/rebind'; import { isArray, isString } from 'utils/is'; import { escapeKey } from 'shared/keypaths'; import ExpressionProxy from './ExpressionProxy'; import resolveReference from './resolveReference'; import resolve from './resolve'; import LinkModel, { Missing } from 'src/model/LinkModel'; export default class ReferenceExpressionProxy extends LinkModel { constructor(fragment, template) { super(null, null, null, '@undefined'); this.root = fragment.ractive.viewmodel; this.template = template; this.rootLink = true; this.template = template; this.fragment = fragment; this.rebound(); } getKeypath() { return this.model ? this.model.getKeypath() : '@undefined'; } rebound() { const fragment = this.fragment; const template = this.template; let base = (this.base = resolve(fragment, template)); let idx; if (this.proxy) { teardown(this); } const proxy = (this.proxy = { rebind: (next, previous) => { if (previous === base) { next = rebindMatch(template, next, previous); if (next !== base) { this.base = base = next; } } else if (~(idx = members.indexOf(previous))) { next = rebindMatch(template.m[idx].n, next, previous); if (next !== members[idx]) { members.splice(idx, 1, next || Missing); } } if (next !== previous) { previous.unregister(proxy); if (next) next.addShuffleTask(() => next.register(proxy)); } }, handleChange: () => { pathChanged(); } }); base.register(proxy); const members = (this.members = template.m.map(tpl => { if (isString(tpl)) { return { get: () => tpl }; } let model; if (tpl.t === REFERENCE) { model = resolveReference(fragment, tpl.n); model.register(proxy); return model; } model = new ExpressionProxy(fragment, tpl); model.register(proxy); return model; })); const pathChanged = () => { const model = base && base.joinAll( members.reduce((list, m) => { const k = m.get(); if (isArray(k)) return list.concat(k); else list.push(escapeKey(String(k))); return list; }, []) ); if (model !== this.model) { this.model = model; this.relinking(model); fireShuffleTasks(); refreshPathDeps(this); this.fragment.shuffled(); } }; pathChanged(); } teardown() { teardown(this); super.teardown(); } unreference() { super.unreference(); if (!this.deps.length && !this.refs) this.teardown(); } unregister(dep) { super.unregister(dep); if (!this.deps.length && !this.refs) this.teardown(); } } function teardown(proxy) { if (proxy.base) proxy.base.unregister(proxy.proxy); if (proxy.models) { proxy.models.forEach(m => { if (m.unregister) m.unregister(proxy); }); } } function refreshPathDeps(proxy) { let len = proxy.deps.length; let i, v; for (i = 0; i < len; i++) { v = proxy.deps[i]; if (v.pathChanged) v.pathChanged(); if (v.fragment && v.fragment.pathModel) v.fragment.pathModel.applyValue(proxy.getKeypath()); } len = proxy.children.length; for (i = 0; i < len; i++) { refreshPathDeps(proxy.children[i]); } } const eproto = ExpressionProxy.prototype; const proto = ReferenceExpressionProxy.prototype; proto.unreference = eproto.unreference; proto.unregister = eproto.unregister; proto.unregisterLink = eproto.unregisterLink;
ractivejs/ractive
src/view/resolvers/ReferenceExpressionProxy.js
JavaScript
mit
3,804
package model.question; import model.enums.QuestionTypes; public class ImageQuestion implements QuestionIF { private String imagePath; private char[] answer; private QuestionTypes type; public ImageQuestion(String imagePath, char[] answer, QuestionTypes type){ this.setType(type); this.setImagePath(imagePath); this.setAnswer(answer); } private void setType(QuestionTypes type) { // TODO Auto-generated method stub this.type = type; } private void setAnswer(char[] answer) { // TODO Auto-generated method stub this.answer = answer; } private void setImagePath(String imagePath) { // TODO Auto-generated method stub this.imagePath = imagePath; } // ************************************************************************ // get question from file // ************************************************************************ @Override public String getQuestion() { // TODO Auto-generated method stub return imagePath; } // ************************************************************************ // get the answer read from file // ************************************************************************ @Override public char[] getAnswer() { // TODO Auto-generated method stub return answer; } @Override public QuestionTypes getType() { // TODO Auto-generated method stub return type; } }
KhaledMuahamed/GameDevelop
Game/src/model/question/ImageQuestion.java
Java
mit
1,428
// Copyright 2015, Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package queryservice contains the interface for the service definition // of the Query Service. package queryservice import ( "io" "golang.org/x/net/context" "github.com/youtube/vitess/go/sqltypes" "github.com/youtube/vitess/go/vt/tabletserver/querytypes" querypb "github.com/youtube/vitess/go/vt/proto/query" ) // QueryService is the interface implemented by the tablet's query service. // All streaming methods accept a callback function that will be called for // each response. If the callback returns an error, that error is returned // back by the function, except in the case of io.EOF in which case the stream // will be terminated with no error. Streams can also be terminated by canceling // the context. // This API is common for both server and client implementations. All functions // must be safe to be called concurrently. type QueryService interface { // Transaction management // Begin returns the transaction id to use for further operations Begin(ctx context.Context, target *querypb.Target) (int64, error) // Commit commits the current transaction Commit(ctx context.Context, target *querypb.Target, transactionID int64) error // Rollback aborts the current transaction Rollback(ctx context.Context, target *querypb.Target, transactionID int64) error // Prepare prepares the specified transaction. Prepare(ctx context.Context, target *querypb.Target, transactionID int64, dtid string) (err error) // CommitPrepared commits the prepared transaction. CommitPrepared(ctx context.Context, target *querypb.Target, dtid string) (err error) // RollbackPrepared rolls back the prepared transaction. RollbackPrepared(ctx context.Context, target *querypb.Target, dtid string, originalID int64) (err error) // CreateTransaction creates the metadata for a 2PC transaction. CreateTransaction(ctx context.Context, target *querypb.Target, dtid string, participants []*querypb.Target) (err error) // StartCommit atomically commits the transaction along with the // decision to commit the associated 2pc transaction. StartCommit(ctx context.Context, target *querypb.Target, transactionID int64, dtid string) (err error) // SetRollback transitions the 2pc transaction to the Rollback state. // If a transaction id is provided, that transaction is also rolled back. SetRollback(ctx context.Context, target *querypb.Target, dtid string, transactionID int64) (err error) // ConcludeTransaction deletes the 2pc transaction metadata // essentially resolving it. ConcludeTransaction(ctx context.Context, target *querypb.Target, dtid string) (err error) // ReadTransaction returns the metadata for the sepcified dtid. ReadTransaction(ctx context.Context, target *querypb.Target, dtid string) (metadata *querypb.TransactionMetadata, err error) // Query execution Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]interface{}, transactionID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, error) StreamExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]interface{}, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error ExecuteBatch(ctx context.Context, target *querypb.Target, queries []querytypes.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) // Combo methods, they also return the transactionID from the // Begin part. If err != nil, the transactionID may still be // non-zero, and needs to be propagated back (like for a DB // Integrity Error) BeginExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]interface{}, options *querypb.ExecuteOptions) (*sqltypes.Result, int64, error) BeginExecuteBatch(ctx context.Context, target *querypb.Target, queries []querytypes.BoundQuery, asTransaction bool, options *querypb.ExecuteOptions) ([]sqltypes.Result, int64, error) // Messaging methods. MessageStream(ctx context.Context, target *querypb.Target, name string, callback func(*sqltypes.Result) error) error MessageAck(ctx context.Context, target *querypb.Target, name string, ids []*querypb.Value) (count int64, err error) // SplitQuery is a MapReduce helper function // This version of SplitQuery supports multiple algorithms and multiple split columns. // See the documentation of SplitQueryRequest in 'proto/vtgate.proto' for more information. SplitQuery(ctx context.Context, target *querypb.Target, query querytypes.BoundQuery, splitColumns []string, splitCount int64, numRowsPerQueryPart int64, algorithm querypb.SplitQueryRequest_Algorithm) ([]querytypes.QuerySplit, error) // UpdateStream streams updates from the provided position or timestamp. UpdateStream(ctx context.Context, target *querypb.Target, position string, timestamp int64, callback func(*querypb.StreamEvent) error) error // StreamHealth streams health status. StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error // HandlePanic will be called if any of the functions panic. HandlePanic(err *error) // Close must be called for releasing resources. Close(ctx context.Context) error } type resultStreamer struct { done chan struct{} ch chan *sqltypes.Result err error } func (rs *resultStreamer) Recv() (*sqltypes.Result, error) { select { case <-rs.done: return nil, rs.err case qr := <-rs.ch: return qr, nil } } // ExecuteWithStreamer performs a StreamExecute, but returns a *sqltypes.ResultStream to iterate on. // This function should only be used for legacy code. New usage should directly use StreamExecute. func ExecuteWithStreamer(ctx context.Context, conn QueryService, target *querypb.Target, sql string, bindVariables map[string]interface{}, options *querypb.ExecuteOptions) sqltypes.ResultStream { rs := &resultStreamer{ done: make(chan struct{}), ch: make(chan *sqltypes.Result), } go func() { defer close(rs.done) rs.err = conn.StreamExecute(ctx, target, sql, bindVariables, options, func(qr *sqltypes.Result) error { select { case <-ctx.Done(): return io.EOF case rs.ch <- qr: } return nil }) if rs.err == nil { rs.err = io.EOF } }() return rs }
derekstavis/bluntly
vendor/github.com/youtube/vitess/go/vt/tabletserver/queryservice/queryservice.go
GO
mit
6,381
import os from typing import List, Tuple from raiden.network.blockchain_service import BlockChainService from raiden.network.pathfinding import get_random_service from raiden.network.proxies.service_registry import ServiceRegistry from raiden.network.rpc.client import JSONRPCClient from raiden.network.rpc.smartcontract_proxy import ContractProxy from raiden.utils import typing from raiden.utils.smart_contracts import deploy_contract_web3 from raiden.utils.solc import compile_files_cwd from raiden_contracts.constants import CONTRACT_HUMAN_STANDARD_TOKEN from raiden_contracts.contract_manager import ContractManager def deploy_token( deploy_client: JSONRPCClient, contract_manager: ContractManager, initial_amount: typing.TokenAmount, decimals: int, token_name: str, token_symbol: str, ) -> ContractProxy: token_address = deploy_contract_web3( contract_name=CONTRACT_HUMAN_STANDARD_TOKEN, deploy_client=deploy_client, contract_manager=contract_manager, constructor_arguments=(initial_amount, decimals, token_name, token_symbol), ) contract_abi = contract_manager.get_contract_abi(CONTRACT_HUMAN_STANDARD_TOKEN) return deploy_client.new_contract_proxy( contract_interface=contract_abi, contract_address=token_address ) def deploy_tokens_and_fund_accounts( token_amount: int, number_of_tokens: int, deploy_service: BlockChainService, participants: typing.List[typing.Address], contract_manager: ContractManager, ) -> typing.List[typing.TokenAddress]: """ Deploy `number_of_tokens` ERC20 token instances with `token_amount` minted and distributed among `blockchain_services`. Optionally the instances will be registered with the raiden registry. Args: token_amount (int): number of units that will be created per token number_of_tokens (int): number of token instances that will be created deploy_service (BlockChainService): the blockchain connection that will deploy participants (list(address)): participant addresses that will receive tokens """ result = list() for _ in range(number_of_tokens): token_address = deploy_contract_web3( CONTRACT_HUMAN_STANDARD_TOKEN, deploy_service.client, contract_manager=contract_manager, constructor_arguments=(token_amount, 2, "raiden", "Rd"), ) result.append(token_address) # only the creator of the token starts with a balance (deploy_service), # transfer from the creator to the other nodes for transfer_to in participants: deploy_service.token(token_address).transfer( to_address=transfer_to, amount=token_amount // len(participants) ) return result def deploy_service_registry_and_set_urls( private_keys, web3, contract_manager, service_registry_address ) -> Tuple[ServiceRegistry, List[str]]: urls = ["http://foo", "http://boo", "http://coo"] c1_client = JSONRPCClient(web3, private_keys[0]) c1_service_proxy = ServiceRegistry( jsonrpc_client=c1_client, service_registry_address=service_registry_address, contract_manager=contract_manager, ) c2_client = JSONRPCClient(web3, private_keys[1]) c2_service_proxy = ServiceRegistry( jsonrpc_client=c2_client, service_registry_address=service_registry_address, contract_manager=contract_manager, ) c3_client = JSONRPCClient(web3, private_keys[2]) c3_service_proxy = ServiceRegistry( jsonrpc_client=c3_client, service_registry_address=service_registry_address, contract_manager=contract_manager, ) # Test that getting a random service for an empty registry returns None pfs_address = get_random_service(c1_service_proxy, "latest") assert pfs_address is None # Test that setting the urls works c1_service_proxy.set_url(urls[0]) c2_service_proxy.set_url(urls[1]) c3_service_proxy.set_url(urls[2]) return c1_service_proxy, urls def get_test_contract(name): contract_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "smart_contracts", name) ) contracts = compile_files_cwd([contract_path]) return contract_path, contracts def deploy_rpc_test_contract(deploy_client, name): contract_path, contracts = get_test_contract(f"{name}.sol") contract_proxy, _ = deploy_client.deploy_solidity_contract( name, contracts, libraries=dict(), constructor_parameters=None, contract_path=contract_path ) return contract_proxy def get_list_of_block_numbers(item): """ Creates a list of block numbers of the given list/single event""" if isinstance(item, list): return [element["blockNumber"] for element in item] if isinstance(item, dict): block_number = item["blockNumber"] return [block_number] return list()
hackaugusto/raiden
raiden/tests/utils/smartcontracts.py
Python
mit
4,965
using System.Reflection; [assembly: AssemblyTitle("Querify.Nh")]
Lotpath/Querify
src/Querify.Nh/Properties/AssemblyInfo.cs
C#
mit
68
class Network < ApplicationRecord end
NextEpisode/NextEpisode
app/models/network.rb
Ruby
mit
38
using FluentValidation; using MediatR; using Shop.Infrastructure.Data; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.EntityFrameworkCore; using Shop.Core.Interfaces; using Shop.Infrastructure.Data.Extensions; namespace Shop.Features.Product { public class ProductEdit { #region Query public class Query : IRequest<Command> { public string ProductReference { get; set; } } public class QueryValidator : AbstractValidator<Query> { public QueryValidator() { RuleFor(x => x.ProductReference).NotNull(); } } public class QueryHandler : IAsyncRequestHandler<Query, Command> { private readonly ShopContext _db; public QueryHandler(ShopContext db) { _db = db; } public async Task<Command> Handle(Query query) { var product = await _db.Products .Where(p => p.ProductReference == query.ProductReference) .FirstOrDefaultAsync(); return Mapper.Map<Command>(product); } } #endregion #region Command public class Command : IRequest<bool> { public string ProductReference { get; set; } public string ProductName { get; set; } public string ProductShortDescription { get; set; } public string ProductDescription { get; set; } public decimal Price { get; set; } public decimal TaxRate { get; set; } public bool AvailableForOrder { get; set; } public bool Configureable { get; set; } } public class CommandValidator : AbstractValidator<Command> { public CommandValidator() { RuleFor(x => x.ProductReference).NotEmpty().NotNull(); RuleFor(x => x.ProductName).NotEmpty().NotNull(); RuleFor(x => x.ProductShortDescription).NotEmpty().NotNull(); RuleFor(x => x.ProductDescription).NotEmpty().NotNull(); RuleFor(x => x.Price).NotEmpty().NotNull(); RuleFor(x => x.TaxRate).NotEmpty().NotNull(); } } public class Handler : IAsyncRequestHandler<Command, bool> { private readonly ShopContext _db; public Handler(ShopContext db) { _db = db; } public async Task<bool> Handle(Command message) { var updatedProduct = Mapper.Map<Core.Entites.Product>(message); var currentProduct = await _db .Products .Active() .FirstOrDefaultAsync(p => p.ProductReference == message.ProductReference); if (currentProduct == null) return false; var isDirty = new MapToExisting().Map(updatedProduct, currentProduct); return !isDirty || await _db.SaveChangesAsync() > 0; } private class MapToExisting : IMapToExisting<Core.Entites.Product, Core.Entites.Product> { public bool Map(Core.Entites.Product source, Core.Entites.Product target) { target.MarkClean(); target.ProductName = source.ProductName; target.ProductShortDescription = source.ProductShortDescription; target.ProductDescription = source.ProductDescription; target.Price = source.Price; target.TaxRate = source.TaxRate; target.ShippingWeightKg = source.ShippingWeightKg; target.AvailableForOrder = source.AvailableForOrder; target.Configureable = source.Configureable; if (target.IsDirty) target.MarkUpdated(); return target.IsDirty; } } } #endregion public class MappingProfile : AutoMapper.Profile { public MappingProfile() { CreateMap<Core.Entites.Product, Command>(MemberList.None); CreateMap<Command, Core.Entites.Product>(MemberList.None); } } } }
jontansey/.Net-Core-Ecommerce-Base
src/Shop/Features/Product/ProductEdit.cs
C#
mit
4,494
using System; using System.Collections.Concurrent; using System.Threading; namespace Napack.Server { /// <summary> /// Holds statistics for the Napack Framework Server system as a whole. /// </summary> /// <remarks> /// This class and its contents is stored in memory. /// </remarks> public class SystemStats { private object lockObject; private DateTime startTime; public SystemStats() { this.RequestStats = new ConcurrentDictionary<string, RequestStats>(); this.TotalCallsSinceUptime = 0; this.UniqueIpsSinceUptime = 0; this.lockObject = new object(); this.startTime = DateTime.UtcNow; } public ConcurrentDictionary<string, RequestStats> RequestStats { get; private set; } public long TotalCallsSinceUptime; public long UniqueIpsSinceUptime; public TimeSpan Uptime => DateTime.UtcNow - startTime; public bool AddCall(string ip) { Interlocked.Increment(ref this.TotalCallsSinceUptime); ++this.TotalCallsSinceUptime; if (!RequestStats.ContainsKey(ip)) { lock (this.lockObject) { if (!RequestStats.ContainsKey(ip)) { Interlocked.Increment(ref this.UniqueIpsSinceUptime); RequestStats.AddOrUpdate(ip, new RequestStats(), (key, existing) => existing); } } } return RequestStats[ip].AddCall(); } } }
GuMiner/napack
server/Definitions/SystemStats/SystemStats.cs
C#
mit
1,627
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Microsoft; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class MediaType extends AbstractTag { protected $Id = 'MediaType'; protected $Name = 'MediaType'; protected $FullName = 'Microsoft::Xtra'; protected $GroupName = 'Microsoft'; protected $g0 = 'QuickTime'; protected $g1 = 'Microsoft'; protected $g2 = 'Video'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Media Type'; }
romainneutron/PHPExiftool
lib/PHPExiftool/Driver/Tag/Microsoft/MediaType.php
PHP
mit
796
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os from indico.core import signals from indico.core.db import db from .logger import logger from .oauth2 import require_oauth __all__ = ['require_oauth'] @signals.core.app_created.connect def _no_ssl_required_on_debug(app, **kwargs): if app.debug or app.testing: os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1' @signals.users.merged.connect def _delete_merged_user_tokens(target, source, **kwargs): target_app_links = {link.application: link for link in target.oauth_app_links} for source_link in source.oauth_app_links.all(): try: target_link = target_app_links[source_link.application] except KeyError: logger.info('merge: reassigning %r to %r', source_link, target) source_link.user = target else: logger.info('merge: merging %r into %r', source_link, target_link) target_link.update_scopes(set(source_link.scopes)) target_link.tokens.extend(source_link.tokens) db.session.delete(source_link)
indico/indico
indico/core/oauth/__init__.py
Python
mit
1,252
<?php /** * Created by PhpStorm. * User: Josh Houghtelin <josh@findsomehelp.com> * Date: 12/19/14 * Time: 6:08 PM */ require __DIR__.'/../vendor/autoload.php'; require __DIR__.'/api_key.php'; $vrp = new \Gueststream\Vrp($api_key); print_r($vrp->isOnline());
Gueststream-Inc/gueststream-php
examples/is_online.php
PHP
mit
265
using FlaUI.Core.AutomationElements.Infrastructure; using FlaUI.Core.Patterns; namespace FlaUI.Core.AutomationElements.PatternElements { /// <summary> /// An element which supports the <see cref="ISelectionItemPattern" />. /// </summary> public class SelectionItemAutomationElement : AutomationElement { /// <summary> /// Creates a <see cref="SelectionItemAutomationElement"/> element. /// </summary> public SelectionItemAutomationElement(BasicAutomationElementBase basicAutomationElement) : base(basicAutomationElement) { } /// <summary> /// Pattern object for the <see cref="ISelectionItemPattern"/>. /// </summary> protected ISelectionItemPattern SelectionItemPattern => Patterns.SelectionItem.Pattern; /// <summary> /// Value to get/set if this element is selected. /// </summary> public virtual bool IsSelected { get => SelectionItemPattern.IsSelected; set { if (IsSelected == value) return; if (value && !IsSelected) { Select(); } } } /// <summary> /// Selects the element. /// </summary> public virtual SelectionItemAutomationElement Select() { ExecuteInPattern(SelectionItemPattern, true, pattern => pattern.Select()); return this; } /// <summary> /// Adds the element to the selection. /// </summary> public virtual SelectionItemAutomationElement AddToSelection() { ExecuteInPattern(SelectionItemPattern, true, pattern => pattern.AddToSelection()); return this; } /// <summary> /// Removes the element from the selection. /// </summary> public virtual SelectionItemAutomationElement RemoveFromSelection() { ExecuteInPattern(SelectionItemPattern, true, pattern => pattern.RemoveFromSelection()); return this; } } }
maxinfet/FlaUI
src/FlaUI.Core/AutomationElements/PatternElements/SelectionItemAutomationElement.cs
C#
mit
2,132
#ifndef __SEQ_HPP__ #define __SEQ_HPP__ #include <string> #include <vector> #include <memory> #include <iostream> class SeqNode; typedef std::shared_ptr<SeqNode> SeqNodeSP; class SeqNode { public: enum E_CallType { E_UNKNOWN, E_SYNC, E_ASYNC, E_ASYNC_WAIT }; SeqNode(); void printTree(std::ostream &out,int tabcnt=0); void setCallType(E_CallType calltype); void setTaskSrc(const std::string& src); void setTaskDst(const std::string& dst); void setFunction(const std::string& func); void setReturn(const std::string& ret); void appendFuncParam(const std::string& param); void appendFuncExtra(const std::string& extra); void appendFuncMemo(const std::string& memo); friend void AppendChild(SeqNodeSP parent, SeqNodeSP child); protected: std::string toString(); private: E_CallType m_call_type; std::string m_task_src; std::string m_task_dst; std::string m_func_name; std::string m_func_ret; std::vector<std::string> m_func_param; std::vector<std::string> m_func_extra; std::vector<std::string> m_func_memo; std::vector< SeqNodeSP > m_child; std::weak_ptr<SeqNode> m_parent; }; SeqNodeSP CreateNode(); void AppendChild(SeqNodeSP parent, SeqNodeSP child); void SetMember(SeqNodeSP node,const std::string& key, const std::string& value); #endif
thuleqaid/boost_study
demo-xml/include/seq.hpp
C++
mit
1,305
<?php class Upload { private $error = array(); private $name; private $ext; private $orgWidth; private $orgHeight; private $width; private $height; private $maxWidth = 0; private $maxHeight = 0; private $prefix; private $suffix; private $uploadedFile; private $source; private $newImage; private $KB = 1024; private $MB = 1048576; private $GB = 1073741824; private $TB = 1099511627776; function __construct(array $fileToUpload) { $this->name = pathinfo($fileToUpload['name'], PATHINFO_FILENAME); $this->ext = strtolower(pathinfo($fileToUpload['name'], PATHINFO_EXTENSION)); $this->filesize = $fileToUpload['size']; $this->uploadedFile = $fileToUpload['tmp_name']; $this->orgWidth = getimagesize($this->uploadedFile)[0]; $this->orgHeight = getimagesize($this->uploadedFile)[1]; $this->setWidth($this->orgWidth); $this->setHeight($this->orgHeight); if (!file_exists($this->uploadedFile) OR $this->filesize == 0) { $this->error[] = _("You have to upload something!"); } } public function errors() { return $this->error; } public function AllowedTypes(array $types) { if (!in_array(mime_content_type($this->uploadedFile), $types)) { $this->error[] = _("This type of file is not allowed!"); } } public function GetType() { return mime_content_type($this->uploadedFile); } public function setMaxSize($size, $type) { if ($this->filesize > $size * $this->$type) { $this->error[] = _("Your file hits the limit!"); } } public function getImageHeight() { return $this->orgHeight; } public function getImageWidth() { return $this->orgWidth; } public function setPrefix($prefix) { $this->prefix = $prefix; } public function setSuffix($suffix) { $this->suffix = $suffix; } public function setWidth($width) { $this->width = $width; } public function setHeight($height) { $this->height = $height; } public function setMaxWidth($width) { $this->maxWidth = $width; } public function setMaxHeight($height) { $this->maxHeight = $height; } public function setPath($path) { $this->path = $path; } public function setName($name) { $this->name = $name; } public function rotateImage($degrees = 90, $filename) { $source = imagecreatefromjpeg($filename); $rotate = imagerotate($source, $degrees, 0); imagejpeg($rotate, $filename, 100); imagedestroy($source); imagedestroy($rotate); } public function Move() { if (!empty($this->error)) { return false; } $filename = $this->prefix . $this->name . $this->suffix . "." . $this->ext; if (move_uploaded_file($this->uploadedFile, $this->path . $filename)) { return $this->prefix . $this->name . $this->suffix . "." . $this->ext; } else { return false; } } public function Render() { if (!empty($this->error)) { return false; } $width = $this->width; if ($this->height == $this->orgHeight) { $height = ($this->orgHeight / $this->orgWidth) * $width; } else { $height = $this->height; } if ($this->maxWidth != 0 && $width > $this->maxWidth) { $width = $this->maxWidth; } if ($this->maxHeight != 0 && $height > $this->maxHeight) { $height = $this->maxHeight; } $this->newImage = imagecreatetruecolor($width, $height); switch ($this->ext) { case 'png': imagealphablending($this->newImage, false); imagesavealpha($this->newImage, true); $this->source = imagecreatefrompng($this->uploadedFile); imagecopyresampled($this->newImage, $this->source, 0, 0, 0, 0, $width, $height, $this->orgWidth, $this->orgHeight); $filename = $this->path . $this->prefix . $this->name . $this->suffix . "." . $this->ext; imagepng($this->newImage, $filename, 9); break; case 'gif': $this->source = imagecreatefromgif($this->uploadedFile); imagecopyresampled($this->newImage, $this->source, 0, 0, 0, 0, $width, $height, $this->orgWidth, $this->orgHeight); $filename = $this->path . $this->prefix . $this->name . $this->suffix . "." . $this->ext; imagegif($this->newImage, $filename); break; case 'jpeg': case 'jpg': $this->source = imagecreatefromjpeg($this->uploadedFile); imagecopyresampled($this->newImage, $this->source, 0, 0, 0, 0, $width, $height, $this->orgWidth, $this->orgHeight); $filename = $this->path . $this->prefix . $this->name . $this->suffix . "." . $this->ext; imagejpeg($this->newImage, $filename, 100); $exif = exif_read_data($this->uploadedFile); if(isset($exif['Orientation'])) { switch ($exif['Orientation']) { case 3: $this->rotateImage(180, $filename); break; case 6: $this->rotateImage(-90, $filename); break; case 8: $this->rotateImage(90, $filename); break; } } break; } imagedestroy($this->newImage); return $this->prefix . $this->name . $this->suffix . "." . $this->ext; } public function Clean() { imagedestroy($this->source); } }
MacXGaming/PHP-Uploader
Upload.php
PHP
mit
6,087
using System; using System.Collections.Generic; namespace RefinId.Specs { public class TestStorage : ILongIdStorage { private List<long> _values; public TestStorage(params long[] values) { _values = new List<long>(values); } public List<long> Values { get { return _values; } } public List<long> GetLastValues(bool requestFromRealTables = false) { return new List<long>(_values); } public void SaveLastValues(IEnumerable<long> values, bool removeUnusedRows = true) { _values = new List<long>(values); } public void SaveLastValue(long value) { SaveLastValues(new[] { value }); } public TableCommandBuilder Builder { get { throw new NotImplementedException(); } } } }
OlegAxenow/refinid
Refinid.Specs/TestStorage.cs
C#
mit
737
using SMSServices.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using WebApi.ErrorHelper; namespace SMSServices.Controllers { public class TeachersSubjectsController : ApiController { private SMSEntities entities = new SMSEntities(); // GET api/<controller> [Route("api/TeachersSubjects/All/{teacherId}")] //public IEnumerable<TeachersSubjects> Get() public HttpResponseMessage Get(int teacherId) { entities.Configuration.ProxyCreationEnabled = false; var query = entities.TeachersSubjects//.Include("Classes").Include("Shifts"); //query.Include("Sections") .Where(t => t.TeacherID == teacherId) .Select(e => new { e.TeacherSubjectID, e.TeacherID, TeacherName = e.Teachers.Name, e.SubjectID, SubjectCode = e.Subjects.Code, SubjectName = e.Subjects.Name, SubjectNameAr = e.Subjects.NameAr, Id = e.SubjectID, Code = e.Subjects.Code, Name = e.Subjects.Name, NameAr = e.Subjects.NameAr }); //return query.ToList(); //entities.TeachersSubjects.Include("Classes").Include("Shifts").Include("Sections"); return this.Request.CreateResponse(HttpStatusCode.OK, query.ToList()); } // POST api/<controller> [Route("api/TeachersSubjects/{TeacherID}/{SubjectIDs}")] public HttpResponseMessage Post(int TeacherID, string SubjectIDs) { try { foreach (string ID in SubjectIDs.Split(',')) { entities.TeachersSubjects.Add(new TeachersSubjects() { TeacherID = TeacherID, SubjectID = Convert.ToInt32(ID) }); } entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, "Done ..."); } //catch (Exception e) //{ // return Request.CreateResponse(HttpStatusCode.BadRequest, "I have some issue ..."); //} catch (DbUpdateException dbEx) { throw dbEx; //return Request.CreateResponse(HttpStatusCode.BadRequest, "I have more issue ..."); //StringBuilder sb = new StringBuilder(); //foreach (var item in dbEx.EntityValidationErrors) //{ // sb.Append(item + " errors: "); // foreach (var i in item.ValidationErrors) // { // sb.Append(i.PropertyName + " : " + i.ErrorMessage); // } // sb.Append(Environment.NewLine); //} ////throw new ApiDataException(GetErrorCode(dbEx), sb.ToString(), HttpStatusCode.BadRequest); //throw new ApiDataException(1021, "too many errors ...", HttpStatusCode.BadRequest); //return Request.CreateResponse(HttpStatusCode.OK, sb.ToString()); } //catch (DbUpdateException ex) //{ // throw ex; // //return Request.CreateResponse(HttpStatusCode.BadRequest, ex); //} } //// GET api/<controller>/5/1/2 //[Route("api/TeachersSubjects/{ShiftId}/{ClassId}/{SectionId}")] //public TeachersSubjects Get(int ShiftId, int ClassId, int SectionId) //{ // entities.Configuration.ProxyCreationEnabled = false; // TeachersSubjects TeacherSubject = entities.TeachersSubjects // .Where(t => t.ShiftID == ShiftId && t.ClassID == ClassId && t.SectionID == SectionId).FirstOrDefault(); // if (TeacherSubject == null) // { // TeacherSubject = new TeachersSubjects() { ClassID = 0 }; // } // return TeacherSubject; //} //[Route("api/TeachersSubjectsById/{id}")] //public TeachersSubjects Get(int id) //{ // entities.Configuration.ProxyCreationEnabled = false; // return entities.TeachersSubjects.Where(t => t.TeacherSubjectID == id).FirstOrDefault(); //} // POST api/<controller> //public HttpResponseMessage Post(TeachersSubjects teacher) //{ // try // { // entities.TeachersSubjects.Add(new TeachersSubjects() // { // TeacherID = teacher.TeacherID, // SubjectID = teacher.SubjectID // }); // entities.SaveChanges(); // return Request.CreateResponse(HttpStatusCode.OK, "Done ..."); // } // //catch (Exception e) // //{ // // return Request.CreateResponse(HttpStatusCode.BadRequest, "I have some issue ..."); // //} // catch (DbUpdateException dbEx) // { // throw dbEx; // //return Request.CreateResponse(HttpStatusCode.BadRequest, "I have more issue ..."); // //StringBuilder sb = new StringBuilder(); // //foreach (var item in dbEx.EntityValidationErrors) // //{ // // sb.Append(item + " errors: "); // // foreach (var i in item.ValidationErrors) // // { // // sb.Append(i.PropertyName + " : " + i.ErrorMessage); // // } // // sb.Append(Environment.NewLine); // //} // ////throw new ApiDataException(GetErrorCode(dbEx), sb.ToString(), HttpStatusCode.BadRequest); // //throw new ApiDataException(1021, "too many errors ...", HttpStatusCode.BadRequest); // //return Request.CreateResponse(HttpStatusCode.OK, sb.ToString()); // } // //catch (DbUpdateException ex) // //{ // // throw ex; // // //return Request.CreateResponse(HttpStatusCode.BadRequest, ex); // //} //} private int GetErrorCode(DbEntityValidationException dbEx) { int ErrorCode = (int)HttpStatusCode.BadRequest; if (dbEx.InnerException != null && dbEx.InnerException.InnerException != null) { if (dbEx.InnerException.InnerException is SqlException) { ErrorCode = (dbEx.InnerException.InnerException as SqlException).Number; } } return ErrorCode; } // PUT api/<controller>/5 public void Put(TeachersSubjects TeacherSubject) { try { var entity = entities.TeachersSubjects.Find(TeacherSubject.TeacherSubjectID); if (entity != null) { entities.Entry(entity).CurrentValues.SetValues(TeacherSubject); entities.SaveChanges(); } } catch //(DbUpdateException) { throw; } } /* // DELETE api/<controller>/5 public void Delete(int id) { try { var teacher = new TeachersSubjects { TeacherId = id }; if (teacher != null) { entities.Entry(teacher).State = EntityState.Deleted; entities.TeachersSubjects.Remove(teacher); entities.SaveChanges(); } } catch (Exception) { throw; } } */ [HttpPost] [Route("api/RemoveTeacherSubject/{id}")] public HttpResponseMessage RemoveTeacherSubject(int id) { try { var TeacherSubject = new TeachersSubjects { TeacherSubjectID = id }; if (TeacherSubject != null) { entities.Entry(TeacherSubject).State = EntityState.Deleted; entities.TeachersSubjects.Remove(TeacherSubject); entities.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, "Removed..."); } else return Request.CreateResponse(HttpStatusCode.NotFound, "not found..."); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.BadRequest, ex); //return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message + // " inner ex: " + ex.InnerException !=null ? ex.InnerException.Message : "null" ); //throw; } } protected override void Dispose(bool disposing) { if (disposing) { entities.Dispose(); } base.Dispose(disposing); } } }
zraees/sms-project
SMSServices/SMSServices/Controllers/TeachersSubjectsController.cs
C#
mit
9,436
// Week 5 - Task 7 import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.io.*; public class TCPSerServer { private static ServerSocket servSock; private static final int PORT = 1234; public static void main(String[] args) { System.out.println("!!!Opening port...\n"); try { servSock = new ServerSocket(PORT); } catch(IOException e) { System.out.println("Unable to attach to port!"); System.exit(1); } do { run(); }while (true); } private static void run() { Socket link = null; try{ link = servSock.accept(); PrintWriter out = new PrintWriter(link.getOutputStream(),true); ObjectInputStream istream = new ObjectInputStream (link.getInputStream()); Person p = null; while(true){ try{ p = (Person)istream.readObject(); System.out.println("SERVER - Received: New object.\n"); System.out.println("SERVER - Received: Person name=" + p.getName()); System.out.println("SERVER - Received: Person age=" + p.getAge()); System.out.println("SERVER - Received: Person address=" + p.getAddress()); out.println("Person object received."); } catch (Exception e) { System.out.println("Exception in run"); System.out.println("\n* Closing connection... *"); break; } } } catch(IOException e) { e.printStackTrace(); } finally { try { System.out.println("\n* Closing connection... *"); link.close(); } catch(IOException e) { System.out.println("Unable to disconnect!"); System.exit(1); } } } }
kieranhogan13/Java
Distributed Systems/Labs/Week 7_Lab_Review/Week_3_T7/TCPSerServer.java
Java
mit
1,769
<?php namespace Easybill\ZUGFeRD211\Model; use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\Type; use JMS\Serializer\Annotation\XmlElement; class DocumentLineDocument { /** * @Type("string") * @XmlElement(cdata = false, namespace = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100") * @SerializedName("LineID") */ public string $lineId; public static function create(string $lineId): self { $self = new self(); $self->lineId = $lineId; return $self; } }
easybill/zugferd-php
src/zugferd211/Model/DocumentLineDocument.php
PHP
mit
584
#include "nofx_ofSetOrientation.h" #include "ofAppRunner.h" namespace nofx { namespace AppRunner { NAN_METHOD(nofx_ofSetOrientation) { ofSetOrientation((ofOrientation) args[0]->Uint32Value()); NanReturnUndefined(); } // !nofx_ofSetOrientation } // !namespace AppRunner } // !namespace nofx
sepehr-laal/nofx
nofx/nofx_ofAppRunner/nofx_ofSetOrientation.cc
C++
mit
368
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("6. Fold and Sum")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("6. Fold and Sum")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c1bd8400-c942-4329-ae49-a7752bbf68bd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
tanyta78/ProgramingFundamentals
05Dictionaries/LabDictionariesLambdaLINQ/6. Fold and Sum/Properties/AssemblyInfo.cs
C#
mit
1,406
<html> <title>代客訂位訂餐</title> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> </head> <body> <div><form> 姓名 : <input type="text" id="name"> <br> 電話:<input type="text" id="phonenum"> <br> 日期:<select name="date_" id="date_"> <?php for($i=0; $i<7; $i++){ $temp = $dates[$i]; echo "<option value=\"".$temp."\">".$temp."</option>"; } ?> </select> <br> 時段:<select name="time_" id="time_"> <option value="0">11:00~13:00</option> <option value="1">13:00~15:00</option> <option value="2">17:00~19:00</option> <option value="3">19:00~21:00</option> </select> <br> 人數:<select name="quantity" id="quantity"> <?php for($i=1; $i<11; $i++){ echo "<option value=\"".$i."\">".$i."</option>"; } ?> </select> <br> <button class="myButton" id="submit">確認</button> <button class="myButton" type="button" onclick="window.location.replace('/CI/index.php/reservation');">回到大廳</button> <br> </form></div> <script> $(document).ready(function(){ $("#submit").click(function() { var order_confirm = confirm("是否訂菜?"); $.ajax({ url : "upload_seat_reservation_by_manager", type : "POST", dataType : "text", data : {"date_" : $('#date_').val(), "time_" : $('#time_').val(), "quantity" : $('#quantity').val(), "name" : $('#name').val(), "phonenum" : $('#phonenum').val()}, success : function(response){ var check = response; if(check == "c"){ if(!order_confirm){ window.location.replace("/CI/index.php/reservation/create_reservation"); }else{ window.location.replace("/CI/index.php/reservation/menu"); } } else if(check == "n"){ alert("no enough seat"); } else{ alert("invalid value"); } } }); }); }); </script> </body> </html> <style> body { background: url("http://127.0.0.1/CI/image/index_back.jpg"); background-size: cover; background-repeat: no-repeat; font-style: oblique; font-size: 18px; font-weight: bold; } div { background-color: #DDDDDD; width: 350px; height: 280px; margin-top: 150px; margin:0px auto; border-radius: 10px; box-shadow: 10px 10px 5px #111111; text-align:center; line-height:40px; } input { border: 1px solid #BBBBBB; //改變外框 background: #fff; // 背景色 /* 邊角圓弧化,不同瀏器覧設定不同 */ -moz-border-radius:3px; // Firefox -webkit-border-radius: 3px; // Safari 和 Chrome border-radius: 3px; // Opera 10.5+ } a{ text-decoration:none; color: #666666; } .myButton { margin-top: 15px; -moz-box-shadow:inset 0px 1px 0px 0px #ffffff; -webkit-box-shadow:inset 0px 1px 0px 0px #ffffff; box-shadow:inset 0px 1px 0px 0px #ffffff; background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #f9f9f9), color-stop(1, #e9e9e9)); background:-moz-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%); background:-webkit-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%); background:-o-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%); background:-ms-linear-gradient(top, #f9f9f9 5%, #e9e9e9 100%); background:linear-gradient(to bottom, #f9f9f9 5%, #e9e9e9 100%); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9', endColorstr='#e9e9e9',GradientType=0); background-color:#f9f9f9; -moz-border-radius:6px; -webkit-border-radius:6px; border-radius:6px; border:1px solid #807480; display:inline-block; cursor:pointer; color:#666666; font-family:Arial; font-size:15px; font-weight:bold; padding:11px 24px; text-decoration:none; text-shadow:0px 1px 0px #ffffff; } .myButton:hover { background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #e9e9e9), color-stop(1, #f9f9f9)); background:-moz-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%); background:-webkit-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%); background:-o-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%); background:-ms-linear-gradient(top, #e9e9e9 5%, #f9f9f9 100%); background:linear-gradient(to bottom, #e9e9e9 5%, #f9f9f9 100%); filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#e9e9e9', endColorstr='#f9f9f9',GradientType=0); background-color:#e9e9e9; } .myButton:active { position:relative; top:1px; } </style>
floydxiu/Restaurant-reservation-system
application/views/seat_reservation_by_manager.php
PHP
mit
4,390
/** * Created by zhang on 16/5/19. */ $.myjq = function () { alert("hello my jQuery") }; //js的扩展 $.fn.myjq=function(){ $(this).text("hello") };
qiang437587687/pythonBrother
jQueryFirst/jQuery扩展和noConflict/myjQuery.js
JavaScript
mit
161
// Generated by CoffeeScript 1.10.0 var Graphics; Graphics = (function() { function Graphics(ctx, viewport1) { this.ctx = ctx; this.viewport = viewport1; this.transform = { x: 0, y: 0, rotation: 0, scale: 1 }; } Graphics.prototype.translate = function(dx, dy) { this.transform.x += dx; this.transform.y += dy; return this.ctx.translate(dx, dy); }; Graphics.prototype.setColor = function(color) { this.ctx.fillStyle = color; return this.ctx.strokeStyle = color; }; Graphics.prototype.setLineWidth = function(linewidth) { return this.ctx.lineWidth = linewidth; }; Graphics.prototype.setFont = function(fontdef) { return this.ctx.font = fontdef; }; Graphics.prototype.drawArc = function(x, y, r, sAngle, eAngle) { this.ctx.beginPath(); this.ctx.arc(x, y, r, sAngle, eAngle, true); return this.ctx.stroke(); }; Graphics.prototype.fillArc = function(x, y, r, sAngle, eAngle) { this.ctx.beginPath(); this.ctx.arc(x, y, r, sAngle, eAngle, true); return this.ctx.fill(); }; Graphics.prototype.drawCircle = function(x, y, r) { return this.drawArc(x, y, r, 0, 2 * Math.PI); }; Graphics.prototype.fillCircle = function(x, y, r) { return this.fillArc(x, y, r, 0, 2 * Math.PI); }; Graphics.prototype.drawRect = function(x, y, width, height) { return this.ctx.strokeRect(x, y, width, height); }; Graphics.prototype.fillRect = function(x, y, width, height) { return this.ctx.fillRect(x, y, width, height); }; Graphics.prototype.drawText = function(x, y, text) { return this.ctx.fillText(text, x, y); }; Graphics.prototype.drawLine = function(x1, y1, x2, y2) { this.ctx.beginPath(); this.ctx.moveTo(x1, y1); this.ctx.lineTo(x2, y2); return this.ctx.stroke(); }; Graphics.prototype.drawPoly = function(ptlist) { var i, len, pt; this.ctx.beginPath(); this.ctx.moveTo(ptlist[0].x, ptlist[0].y); for (i = 0, len = ptlist.length; i < len; i++) { pt = ptlist[i]; this.ctx.lineTo(pt.x, pt.y); } this.ctx.closePath(); return this.ctx.stroke(); }; Graphics.prototype.fillPoly = function(ptlist) { var i, len, pt; this.ctx.beginPath(); this.ctx.moveTo(ptlist[0].x, ptlist[0].y); for (i = 0, len = ptlist.length; i < len; i++) { pt = ptlist[i]; this.ctx.lineTo(pt.x, pt.y); } this.ctx.closePath(); return this.ctx.fill(); }; return Graphics; })(); exports.createFromCanvas = function(canvas, viewport) { return new Graphics(canvas.getContext('2d'), viewport); };
aziis98/node-canvas-graphics-wrapper
graphics.js
JavaScript
mit
2,626
<?php // Autoload the library using Composer, if you're using a framework you shouldn't need to do this!! require_once '../vendor/autoload.php'; use Ballen\Dodns\CredentialManager; use Ballen\Dodns\Dodns; /** * Example of deleting a domain */ // We now create an instance of the DigitalOcean DNS client passing in our API credentials. $dns = new Dodns(new CredentialManager(file_get_contents('token.txt'))); // Set the domain entity that we wish to delete from our account... $domain = new \Ballen\Dodns\Entities\Domain(); $domain->setName('mytestdodmain.uk'); // Now we carry out the deletion and check if it was successful... if (!$dns->deleteDomain($domain)) { echo "An error occured and the domain could not be deleted!"; } else { echo sprintf("Congratulations, the domain <strong>%s</strong> has been deleted successfully!", $domain->getName()); }
bobsta63/dodns
examples/delete_a_domain.php
PHP
mit
886
<?php /* Plugin Name: FramePress Plugin URI: http://framepress.co Description: Boost your plugins with extra power! Author: Ivan Lansky (@perecedero) Author URI: http://about.me/ivan.lansky */ //init framework require 'bootstrap.php';
perecedero/FramePress
main.php
PHP
mit
245
using System; using DogeNews.Web.Mvp.UserControls.ArticleComments.EventArguments; using WebFormsMvp; namespace DogeNews.Web.Mvp.UserControls.ArticleComments { public interface IArticleCommentsView : IView<ArticleCommentsViewModel> { event EventHandler<ArticleCommetnsPageLoadEventArgs> PageLoad; event EventHandler<AddCommentEventArguments> AddComment; } }
SuchTeam-NoJoro-MuchSad/Doge-News
DogeNews/Src/Web/DogeNews.Web.Mvp/UserControls/ArticleComments/IArticleCommentsView.cs
C#
mit
390
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Latihan extends CI_Controller{ public function __construct(){ parent::__construct(); //Codeigniter : Write Less Do More } function index(){ $this->load->view('mhs/latihan'); // $this->load->view('sample'); } } ?>
aisy/polieditor
application/controllers/Latihan.php
PHP
mit
334
"use strict"; var EventEmitter = require ('events'); module.exports = new EventEmitter ();
alexandruradovici/messengertrivia
source/bus.js
JavaScript
mit
92
'use strict' const tap = require('tap') const ActiveDirectory = require('../index') const config = require('./config') const serverFactory = require('./mockServer') const settings = require('./settings').getGroupMembershipForUser tap.beforeEach((done, t) => { serverFactory(function (err, server) { if (err) return done(err) const connectionConfig = config(server.port) t.context.ad = new ActiveDirectory(connectionConfig) t.context.server = server done() }) }) tap.afterEach((done, t) => { if (t.context.server) t.context.server.close() done() }) tap.test('#getGroupMembershipForUser()', t => { settings.users.forEach((user) => { ['dn', 'userPrincipalName', 'sAMAccountName'].forEach((attr) => { const len = user.members.length t.test(`should return ${len} groups for ${attr}`, t => { t.context.ad.getGroupMembershipForUser(user[attr], function (err, groups) { t.error(err) t.true(groups.length >= user.members.length) const groupNames = groups.map((g) => { return g.cn }) user.members.forEach((g) => { t.true(groupNames.includes(g)) }) t.end() }) }) }) }) t.test('should return empty groups if groupName doesn\'t exist', t => { t.context.ad.getGroupMembershipForUser('!!!NON-EXISTENT GROUP!!!', function (err, groups) { t.error(err) t.type(groups, Array) t.equal(groups.length, 0) t.end() }) }) t.test('should return default group attributes when not specified', t => { const defaultAttributes = ['objectCategory', 'distinguishedName', 'cn', 'description'] const user = settings.users[0] t.context.ad.getGroupMembershipForUser(user.userPrincipalName, function (err, groups) { t.error(err) t.ok(groups) groups.forEach((g) => { const keys = Object.keys(g) defaultAttributes.forEach((attr) => { t.true(keys.includes(attr)) }) }) t.end() }) }) t.end() }) tap.test('#getGroupMembershipForUser(opts)', t => { t.test('should return only requested attributes', t => { const opts = { attributes: ['createTimeStamp'] } const user = settings.users[0] t.context.ad.getGroupMembershipForUser(opts, user.userPrincipalName, function (err, groups) { t.error(err) t.ok(groups) t.true(groups.length >= user.members.length) groups.forEach((g) => { const keys = Object.keys(g) keys.forEach((attr) => { t.true(opts.attributes.includes(attr)) }) }) t.end() }) }) t.end() })
jsumners/node-activedirectory
test/getgroupmembershipforuser.test.js
JavaScript
mit
2,662
package com.github.lg198.codefray.jfx; import com.github.lg198.codefray.api.game.Team; import com.github.lg198.codefray.game.GameEndReason; import com.github.lg198.codefray.game.GameStatistics; import com.github.lg198.codefray.util.TimeFormatter; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; public class GameResultGui { private final GameStatistics stats; public GameResultGui(GameStatistics gs) { stats = gs; } public VBox build() { VBox root = new VBox(); root.setAlignment(Pos.CENTER); root.setSpacing(10); root.setPadding(new Insets(15)); Label title = new Label("Game Result"); title.setStyle("-fx-font-size: 30px"); title.setUnderline(true); root.getChildren().add(title); VBox.setMargin(title, new Insets(0, 0, 5, 0)); root.getChildren().addAll( createWinnerStatBox(stats.reason), createStatBox("Rounds:", "" + stats.rounds), createStatBox("Length:", TimeFormatter.format(stats.timeInSeconds)), createStatBox("Red Golems Left:", "" + stats.redLeft), createStatBox("Blue Golems Left:", "" + stats.blueLeft), createStatBox("Red Health:", stats.redHealthPercent, Team.RED), createStatBox("Blue Health:", stats.blueHealthPercent, Team.BLUE) ); return root; } private HBox createWinnerStatBox(GameEndReason reason) { HBox box = new HBox(); box.setSpacing(6); box.setAlignment(Pos.CENTER); if (reason instanceof GameEndReason.Win) { Label key = new Label("Winner:"); Label value = new Label(((GameEndReason.Win)reason).winner.name()); key.setStyle("-fx-font-size: 20px"); value.setStyle(key.getStyle()); box.getChildren().addAll(key, value); return box; } else if (reason instanceof GameEndReason.Infraction) { Label key = new Label(((GameEndReason.Infraction)reason).guilty.name() + " cheated and lost"); key.setStyle("-fx-font-size: 20px"); box.getChildren().addAll(key); return box; } else { Label key = new Label("Winner:"); Label value = new Label("None"); key.setStyle("-fx-font-size: 20px"); value.setStyle(key.getStyle()); box.getChildren().addAll(key, value); return box; } } private HBox createStatBox(String name, String value) { HBox box = new HBox(); box.setSpacing(6); box.setAlignment(Pos.CENTER); box.getChildren().addAll(new Label(name), new Label(value)); return box; } private HBox createStatBox(String name, double perc, Team team) { HBox box = new HBox(); box.setAlignment(Pos.CENTER); box.setSpacing(6); ProgressBar pb = new ProgressBar(perc); if (team == Team.RED) { pb.setStyle("-fx-accent: red"); } else { pb.setStyle("-fx-accent: blue"); } box.getChildren().addAll(new Label(name), pb); return box; } }
lg198/CodeFray
src/com/github/lg198/codefray/jfx/GameResultGui.java
Java
mit
3,347
<?php namespace Flatmate\UtilitiesBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Consumption * * @ORM\Table() * @ORM\Entity * @ORM\HasLifecycleCallbacks() */ class Consumption { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var integer * * @ORM\Column(name="category_id", type="integer") */ private $categoryId; /** * @var string * * @ORM\Column(name="name", type="string", length=255) * @Assert\NotBlank(message="consumption.name.not_blank") */ private $name; /** * @var string * * @ORM\Column(name="value", type="decimal", scale=1) * @Assert\NotBlank(message="consumption.value.not_blank") */ private $value; /** * @var \DateTime * * @ORM\Column(name="created_at", type="datetime") */ private $createdAt; /** * @var * * @ORM\ManyToOne(targetEntity="Category") * @ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE") */ private $category; /** * @var integer * * @ORM\Column(name="user_id", type="integer") */ private $userId; /** * @var string * * @ORM\ManyToOne(targetEntity="Flatmate\UserBundle\Entity\User") * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE") */ private $user; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set categoryId * * @param integer $categoryId * @return Consumption */ public function setCategoryId($categoryId) { $this->categoryId = $categoryId; return $this; } /** * Set category * * @param $category * @return $this */ public function setCategory($category) { $this->category = $category; return $this; } /** * Get categoryId * * @return integer */ public function getCategoryId() { return $this->categoryId; } /** * Get category * * @return mixed */ public function getCategory() { return $this->category; } /** * Set name * * @param string $name * @return Consumption */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set value * * @param string $value * @return Consumption */ public function setValue($value) { $this->value = $value; return $this; } /** * Get value * * @return string */ public function getValue() { return $this->value; } /** * Set createdAt * * @param \DateTime $createdAt * @return Consumption */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Set Created At value at current time * * @ORM\PrePersist */ public function setCreatedAtNow() { $this->createdAt = new \DateTime(); } /** * Get User ID * * @return integer */ public function getUserId() { return $this->userId; } /** * Set User ID * * @param $userId */ public function setUserId($userId) { $this->userId = $userId; } /** * Get User * * @return string */ public function getUser() { return $this->user; } /** * Set User * * @param User */ public function setUser($user) { $this->user = $user; } }
TIIUNDER/flatmate
src/Flatmate/UtilitiesBundle/Entity/Consumption.php
PHP
mit
4,174
<? include('dbconnect.php'); $headerOptions = array( "title" => "Edit Stats" ); require_once "header.php"; ?> <?php $tn = $_GET['tn']; $played = $_GET['played']; $wins = $_GET['wins']; $losses = $_GET['losses']; $draws = $_GET['draws']; $ncs = $_GET['ncs']; $sql = "SELECT team_id FROM Team WHERE team_name='".$tn."';"; $result = mysql_query($sql) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); $tid = mysql_result($result, 0); //Update game... $sql = "UPDATE Stats SET played='".$played."', wins='".$wins."', losses='".$losses."', draws='".$draws."', ncs='".$ncs."' WHERE team_id='".$tid."';"; $result = mysql_query($sql) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); //$sql = "SELECT game_id FROM Game WHERE game_date='".$date."' AND game_time='".$time."' AND game_location='".$location."';"; //Redirect back to getteam.php header("Location: getteam.php?teamname=".$tn."");//?leaguetype='".$leaguetype."'&sport='".$sport."'&submit=Set+League"); ?>
anshaik/recsports
webapp/advproj/editstats.php
PHP
mit
1,187
version https://git-lfs.github.com/spec/v1 oid sha256:b1b66ad7cf63a081650856aed61fbfdf1b6b511e47c622989e9927e504424a5d size 2493
yogeshsaroya/new-cdnjs
ajax/libs/jquery.lazyloadxt/0.8.12/jquery.lazyloadxt.extra.min.js
JavaScript
mit
129
#include "ErrorCodes.h" std::error_code make_error_code(SimBlockErrc ec) { return {static_cast<int>(ec), simblockErrCategory}; }
josokw/Fuzzy
libDySySim/ErrorCodes.cpp
C++
mit
133
<?php /* Safe sample input : backticks interpretation, reading the file /tmp/tainted.txt sanitize : cast in float construction : use of sprintf via a %d with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = `cat /tmp/tainted.txt`; $tainted = (float) $tainted ; $var = include(sprintf("pages/'%d'.php", $tainted)); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_98/safe/CWE_98__backticks__CAST-cast_float__include_file_id-sprintf_%d_simple_quote.php
PHP
mit
1,212
<?php namespace Oriancci\Query; class Insert extends Built { public function buildQuery() { // INSERT INTO $sql = 'INSERT INTO '; $sql .= $this->buildTableName(INSERT_INTO); // SET $sql .= ' SET '; $sql .= $this->buildSet(SET); return $sql; } }
bashaus/oriancci
src/Oriancci/Query/Insert.php
PHP
mit
322
package pl.yourempire.api.event; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Event { private static Map<Class<Event>, ArrayList<ListenerCaller>> listenerMap = new HashMap<>(); public static void callEvent(Event e) { if (listenerMap.containsKey(e.getClass())) { for (ListenerCaller lc : listenerMap.get(e.getClass())) { try { lc.getEventMethod().invoke(lc.getInstance(), e); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (InvocationTargetException e1) { e1.printStackTrace(); } } } } public static boolean isEvent(Class<?> clazz) { try { clazz.cast(Event.class); return true; } catch(ClassCastException e) { return false; } } public static void registerListener(Listener l) { Arrays.asList(l.getClass().getMethods()).forEach(m -> { if (m.getParameterTypes().length == 1 && isEvent(m.getParameterTypes()[0])) { listenerMap.get(m.getParameterTypes()[0]).add(new ListenerCaller(l, m)); } }); } protected boolean cancelled; public Event() { cancelled = false; } public void setCancelled(boolean flag) { this.cancelled = flag; } public boolean isCancelled() { return this.cancelled; } }
YourEmpire/YourEmpire
Your Empire API/src/main/java/pl/yourempire/api/event/Event.java
Java
mit
1,714
tinyMCE.init({ mode : 'textareas', theme : "advanced", theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", });
thoas/i386
src/milkshape/media/tiny_mce/init.js
JavaScript
mit
502
package org.fluentjava.iwant.plannerapi; public interface ResourcePool { boolean hasFreeResources(); Resource acquire(); void release(Resource resource); }
wipu/iwant
essential/iwant-planner-api/src/main/java/org/fluentjava/iwant/plannerapi/ResourcePool.java
Java
mit
164
#ifndef ENDOCAST_EXTRACTOR_HPP #define ENDOCAST_EXTRACTOR_HPP 1 #include <mi/VolumeData.hpp> class EndocastExtractor { private: public: EndocastExtractor ( void ) ; ~EndocastExtractor ( void ) ; bool extract ( mi::VolumeData<float>& distData, mi::VolumeData<int>& labelData, const double scale ) ; private: bool init ( mi::VolumeData<float>& distData, mi::VolumeData<int>& labelData, const double scale ) ; bool run ( mi::VolumeData<float>& distData, mi::VolumeData<int>& labelData ) ; }; #endif // ENDOCAST_EXTRACTOR_HPP
tmichi/xendocast
xendocast/EndocastExtractor.hpp
C++
mit
579
import { SplashEffect } from "./effect.js"; import { Linear } from "../interpolation.js"; export class TranslateFromPosition extends SplashEffect { constructor(element, options) { super(element); options = options || {}; this.x = options.x || 0; this.y = options.y || 0; // Can be whatever, but the effect won't do // anything if it isn't a valid css unit. this.unit = options.unit || "px"; // Can be either "transform" or "position" this.translationType = options.translationType || "transform"; this.interpolation = options.interpolation || new Linear(); } in(value) { this._set( this.interpolation.in(value * -1 + 1) * this.x, this.interpolation.in(value * -1 + 1) * this.y ); } out(value) { this._set( this.interpolation.out(value) * this.x, this.interpolation.out(value) * this.y ); } _set(x, y) { if (this.translationType = "transform") { this.setTransform("translateX", x + this.unit); this.setTransform("translateY", y + this.unit); } else if (this.translationType = "position") { this.setStyle("left", x + this.unit); this.setStyle("top", y + this.unit); } else { console.error("Unknown translation type: " + this.translationType); } } }
magnontobi/splasher.js
src/js/effects/translateFromPosition.js
JavaScript
mit
1,226
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk { /// <summary> /// Structure specifying parameters of a newly created framebuffer. /// </summary> [StructLayout(LayoutKind.Sequential)] public partial struct FramebufferCreateInfo { /// <summary> /// Reserved for future use. /// </summary> public SharpVk.FramebufferCreateFlags? Flags { get; set; } /// <summary> /// A render pass that defines what render passes the framebuffer will /// be compatible with. /// </summary> public SharpVk.RenderPass RenderPass { get; set; } /// <summary> /// An array of ImageView handles, each of which will be used as the /// corresponding attachment in a render pass instance. /// </summary> public SharpVk.ImageView[] Attachments { get; set; } /// <summary> /// width, height and layers define the dimensions of the framebuffer. /// If the render pass uses multiview, then layers must be one and each /// attachment requires a number of layers that is greater than the /// maximum bit index set in the view mask in the subpasses in which it /// is used. /// </summary> public uint Width { get; set; } /// <summary> /// /// </summary> public uint Height { get; set; } /// <summary> /// /// </summary> public uint Layers { get; set; } /// <summary> /// /// </summary> /// <param name="pointer"> /// </param> internal unsafe void MarshalTo(SharpVk.Interop.FramebufferCreateInfo* pointer) { pointer->SType = StructureType.FramebufferCreateInfo; pointer->Next = null; if (this.Flags != null) { pointer->Flags = this.Flags.Value; } else { pointer->Flags = default(SharpVk.FramebufferCreateFlags); } pointer->RenderPass = this.RenderPass?.handle ?? default(SharpVk.Interop.RenderPass); pointer->AttachmentCount = (uint)(Interop.HeapUtil.GetLength(this.Attachments)); if (this.Attachments != null) { var fieldPointer = (SharpVk.Interop.ImageView*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Interop.ImageView>(this.Attachments.Length).ToPointer()); for(int index = 0; index < (uint)(this.Attachments.Length); index++) { fieldPointer[index] = this.Attachments[index]?.handle ?? default(SharpVk.Interop.ImageView); } pointer->Attachments = fieldPointer; } else { pointer->Attachments = null; } pointer->Width = this.Width; pointer->Height = this.Height; pointer->Layers = this.Layers; } } }
FacticiusVir/SharpVk
src/SharpVk/FramebufferCreateInfo.gen.cs
C#
mit
4,531
namespace Sorting { using System; using System.Collections.Generic; using Constants; /// <summary> /// Define class for selection sort algorithm and its implementation /// </summary> /// <typeparam name="T">Type of the elements to be sorted</typeparam> /// <see cref="https://en.wikipedia.org/wiki/Selection_sort"/> /// <seealso cref="http://www.algolist.net/Algorithms/Sorting/Selection_sort"/> public class SelectionSorter<T> : ISorter<T> where T : IComparable<T> { public void Sort(IList<T> collection) { if (collection == null) { throw new ArgumentNullException(ExceptionMessage.CollectionCannotBeNullExceptionMessage); } int swapIndex = 0; for (int i = 0; i < collection.Count - 1; i++) { swapIndex = i; for (int j = i + 1; j < collection.Count; j++) { if (collection[swapIndex].CompareTo(collection[j]) > 0) { swapIndex = j; } } this.Swap(collection, i, swapIndex); } } private void Swap(IList<T> collection, int index, int swapIndex) { T swap = collection[index]; collection[index] = collection[swapIndex]; collection[swapIndex] = swap; } } }
DimitarSD/Telerik-Academy
01. Programming/05. Data Structures and Algorithms [C#]/11. Sorting Algorithms/Sorting/SelectionSorter.cs
C#
mit
1,456
# encoding: utf-8 module Axiom class Relation module Operation # A mixin for Binary relations module Binary include Axiom::Operation::Binary # Hook called when module is included # # @param [Module] descendant # the module or class including Binary # # @return [undefined] # # @api private def self.included(descendant) super descendant.extend(ClassMethods) end private_class_method :included # Initialize a Binary relation # # @return [undefined] # # @api private def initialize(*) super @header = left.header | right.header end module ClassMethods # Instantiate a new Binary relation # # @example # binary = BinaryRelation.new(left, right) # # @param [Relation] left # @param [Relation] right # # @return [Binary] # # @api public def new(left, right) assert_sorted_match(left, right) super end private # Assert that sorted and unsorted relations are not mixed # # @param [Relation] left # @param [Relation] right # # @return [undefined] # # @raise [RelationMismatchError] # raised if one relation is sorted and the other is not # # @api private def assert_sorted_match(left, right) if left.directions.empty? != right.directions.empty? fail RelationMismatchError, 'both relations must be sorted or neither may be sorted' end end end # module ClassMethods end # module Binary end # module Operation end # class Relation end # module Axiom
solnic/axiom
lib/axiom/relation/operation/binary.rb
Ruby
mit
1,923
<?php /* /* Safe sample input : use exec to execute the script /tmp/tainted.php and store the output in $tainted SANITIZE : uses indirect reference construction : prepared query and no right verification */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $script = "/tmp/tainted.php"; exec($script, $result, $return); $tainted = $result[0]; $course_array = array(); //get the user id $user_id = intval($_SESSION[‘user_id’]); //creation of the references with only data allowed to the user $result = mysql_query("SELECT * FROM COURSE where course.allowed = {$user_id}"); while ($row = mysql_fetch_array($result)) { $course_array[] = $result[‘id’]; } $_SESSION[‘course_array’] = $course_array; if (isset($_SESSION[‘course_array’])) { $course_array = $_SESSION[‘course_array’]; if (isset($course_array[$taintedId])) { //indirect reference > get the right id $tainted = $course_array[$tainted]; } } else { $tainted = 0; //default value } $query = "SELECT * FROM COURSE WHERE id=?"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); //Connection to the database (address, user, password) $stmt = $conn->prepare($query); $stmt->bind_param("i", $checked_data); $stmt->execute(); mysql_close($conn);
designsecurity/progpilot
projects/tests/tests/vulntestsuite/CWE_862_SQL__exec__Indirect_reference__prepared_query-no_right_verification.php
PHP
mit
2,134
package com.myconnector.client.domain; import java.util.List; import com.google.gwt.user.client.rpc.IsSerializable; import com.myconnector.client.domain.interfaces.ITodoContext; import com.myconnector.client.domain.interfaces.ITodoItem; import com.myconnector.client.domain.interfaces.ITodoList; public class TodoListClient implements IsSerializable, ITodoList { private Long id; private String title; private boolean todoItemsLoaded = false; private List<ITodoItem> todoItems; private Integer position; private ITodoContext context; public TodoListClient() { } public TodoListClient(Long id, String title) { super(); this.id = id; 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; } public List<ITodoItem> getTodoItems() { return todoItems; } public void setTodoItems(List<ITodoItem> todoItems) { this.todoItems = todoItems; } public Integer getPosition() { return position; } public void setPosition(Integer position) { this.position = position; } public boolean isTodoItemsLoaded() { return todoItemsLoaded; } public void setTodoItemsLoaded(boolean todoItemsLoaded) { this.todoItemsLoaded = todoItemsLoaded; } public ITodoContext getContext() { return context; } public void setContext(ITodoContext context) { this.context = context; } }
nileshk/truedolist-java
src/main/java/com/myconnector/client/domain/TodoListClient.java
Java
mit
1,476
/** * Wheel, copyright (c) 2019 - present by Arno van der Vegt * Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt **/ const File = require('./File'); exports.FileDetail = class extends File.File { constructor(opts) { opts.className = 'file detail'; super(opts); } initDOM(parentNode) { let file = this._file; this.create( parentNode, { id: this.setElement.bind(this), className: this._className, children: [ File.getIcon(this._getImage, file), { id: this.setLinkElement.bind(this), type: 'a', href: '#', className: 'no-select name', innerHTML: file.name }, !file.directory && file.size ? { type: 'span', href: '#', className: 'no-select size', innerHTML: file.size + ' - ' + this.bytesToSize(file.size) } : null, (file.modified || file.hash) ? { type: 'span', href: '#', className: 'no-select modified', innerHTML: file.modified || file.hash } : null ] } ); } /** * https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript **/ bytesToSize(bytes) { const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (parseInt(bytes, 10) === 0) { return '0 Byte'; } let i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } };
ArnoVanDerVegt/wheel
js/frontend/lib/components/files/FileDetail.js
JavaScript
mit
2,137
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Position } from '../core/position'; import { Range } from '../core/range'; import { InlineDecoration, ViewModelDecoration } from './viewModel'; import { filterValidationDecorations } from '../config/editorOptions'; var ViewModelDecorations = /** @class */ (function () { function ViewModelDecorations(editorId, model, configuration, linesCollection, coordinatesConverter) { this.editorId = editorId; this.model = model; this.configuration = configuration; this._linesCollection = linesCollection; this._coordinatesConverter = coordinatesConverter; this._decorationsCache = Object.create(null); this._cachedModelDecorationsResolver = null; this._cachedModelDecorationsResolverViewRange = null; } ViewModelDecorations.prototype._clearCachedModelDecorationsResolver = function () { this._cachedModelDecorationsResolver = null; this._cachedModelDecorationsResolverViewRange = null; }; ViewModelDecorations.prototype.dispose = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype.reset = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype.onModelDecorationsChanged = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype.onLineMappingChanged = function () { this._decorationsCache = Object.create(null); this._clearCachedModelDecorationsResolver(); }; ViewModelDecorations.prototype._getOrCreateViewModelDecoration = function (modelDecoration) { var id = modelDecoration.id; var r = this._decorationsCache[id]; if (!r) { var modelRange = modelDecoration.range; var options = modelDecoration.options; var viewRange = void 0; if (options.isWholeLine) { var start = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.startLineNumber, 1)); var end = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber))); viewRange = new Range(start.lineNumber, start.column, end.lineNumber, end.column); } else { viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange); } r = new ViewModelDecoration(viewRange, options); this._decorationsCache[id] = r; } return r; }; ViewModelDecorations.prototype.getDecorationsViewportData = function (viewRange) { var cacheIsValid = (this._cachedModelDecorationsResolver !== null); cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange)); if (!cacheIsValid) { this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange); this._cachedModelDecorationsResolverViewRange = viewRange; } return this._cachedModelDecorationsResolver; }; ViewModelDecorations.prototype._getDecorationsViewportData = function (viewportRange) { var modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, filterValidationDecorations(this.configuration.options)); var startLineNumber = viewportRange.startLineNumber; var endLineNumber = viewportRange.endLineNumber; var decorationsInViewport = [], decorationsInViewportLen = 0; var inlineDecorations = []; for (var j = startLineNumber; j <= endLineNumber; j++) { inlineDecorations[j - startLineNumber] = []; } for (var i = 0, len = modelDecorations.length; i < len; i++) { var modelDecoration = modelDecorations[i]; var decorationOptions = modelDecoration.options; var viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration); var viewRange = viewModelDecoration.range; decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration; if (decorationOptions.inlineClassName) { var inlineDecoration = new InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */); var intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber); var intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber); for (var j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) { inlineDecorations[j - startLineNumber].push(inlineDecoration); } } if (decorationOptions.beforeContentClassName) { if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) { var inlineDecoration = new InlineDecoration(new Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* Before */); inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration); } } if (decorationOptions.afterContentClassName) { if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) { var inlineDecoration = new InlineDecoration(new Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* After */); inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration); } } } return { decorations: decorationsInViewport, inlineDecorations: inlineDecorations }; }; return ViewModelDecorations; }()); export { ViewModelDecorations };
TeamSPoon/logicmoo_workspace
packs_web/swish/web/node_modules/monaco-editor/esm/vs/editor/common/viewModel/viewModelDecorations.js
JavaScript
mit
6,682
<?php namespace Code200\ImageKing\Classes; use Cms\Helpers\File; use Code200\ImageKing\Classes\Exceptions\ExtensionNotAllowedException; use Code200\Imageking\models\Settings; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\URL; class ImageService { /** * @var string */ private $html; /** * @var DomManipulator */ private $domImageFinder; /** * Filepath of current image * @var string */ private $imageFilePath; /** * @var Settings */ private $s; /** * Allowed image extensions * @var array */ private $allowedExtensions; /** * Responsive sizes * @var array */ private $responsiveSizes; /** * ImageService constructor. * @param string $html */ public function __construct($html) { $this->html = $html; $this->setDomImageFinder(); $this->s = Settings::instance(); } protected function setDomImageFinder() { $this->domImageFinder = new DomImageFinder($this->html); } /** * Process images and returns modified HTML containing images. * * @return string */ public function process() { $imageNodes = $this->domImageFinder->getImageNodes(); foreach ($imageNodes as $node) { try { //get image $this->imageFilePath = $this->getFilePathFromNode($node); $image = $this->getNewImageManipulator($this->imageFilePath); $this->checkIfProcessable($image); //check cache $newMainImagePath = $image->getStoragePath(); if(!file_exists($newMainImagePath) || empty(Settings::get("enable_cache", 0)) ) { $imgChanged = $this->processMainImage($image); } $node->setAttribute("src", $image->getPublicUrl($newMainImagePath)); //responsive versions $this->prepareResponsiveVersions($this->imageFilePath, $node); //captions $this->applyCaptions($node); } catch (\RemotePathException $e) { //we simply cant and dont want to process remote images ... continue; } catch (ExtensionNotAllowedException $e) { //we dont want to process certain files I guess continue; } catch (\Exception $e) { Log::warning("[Code200.ImageKing] could not process image: " . $this->imageFilePath); continue; } } return $this->domImageFinder->dom->saveHTML(); } private function processMainImage(&$image) { $imgChanged = false; //limit its output size in case we dont want to share sources $maxWidth = $this->s->get("max_width"); if (!empty($maxWidth) && $maxWidth < $image->getWidth() ) { $image->resize($maxWidth, null); $imgChanged = true; } //watermark if ($this->shouldWatermark()) { $image->applyWatermark(); $imgChanged = true; } if($imgChanged || $this->s->get("enable_private_paths")) { $newMainImagePath = $image->getStoragePath(); $image->save($newMainImagePath); // $node->setAttribute("src", $image->getPublicUrl($newMainImagePath)); } return $imgChanged; } /** * Return new image manipulator object * @param $imagePath * @return ImageManipulator */ protected function getNewImageManipulator($imagePath){ return new ImageManipulator($imagePath); } /** * Is watermarking enabled in settings * @return bool */ private function shouldWatermark() { $isWatermarkEnabled = $this->s->get("enable_watermark"); if (!$isWatermarkEnabled) { return false; } return true; } private function applyCaptions(&$node){ if(empty($this->s->get("enable_captions")) && ! empty($node->getAttribute("title"))){ return; } $figureElement = $this->domImageFinder->dom->createElement("figure"); $captionElement = $this->domImageFinder->dom->createElement("figcaption", $node->getAttribute("title")); $node->parentNode->replaceChild($figureElement, $node); $figureElement->appendChild($node); $figureElement->appendChild($captionElement); } /** * Returns array of allowed image extensions to be manipulated * @return array string */ private function getAllowedExtensions() { if (empty($this->allowedExtensions)) { $this->allowedExtensions = array_map( function ($element) { return trim($element); }, explode(",", $this->s->get("allowed_extensions")) ); } return $this->allowedExtensions; } /** * Returns int array of responsive sizes * @return array int */ private function getResponsiveSizes() { if (empty($this->responsiveSizes)) { if(!empty($this->s->get("responsive_sizes"))) { //fetch from settings $this->responsiveSizes = array_map( function ($el) { if (empty($el)) { return null; } return (int)trim($el); }, explode(",", $this->s->get("responsive_sizes")) ); //limit max size to settings $this->responsiveSizes = array_filter($this->responsiveSizes, function($el){ if(!empty($el) && (empty($this->getMaxWidth()) || $this->getMaxWidth() >= $el)) { return true; } }); } else { $this->responsiveSizes = array(); } } return $this->responsiveSizes; } /** * Checks if image is processable * @param ImageManipulator $image * @return bool */ protected function checkIfProcessable($image) { if (!in_array($image->getExtension(), $this->getAllowedExtensions())) { throw new ExtensionNotAllowedException("Extension not allowed."); } return true; } /** * @param $imagePath * @param $node * @return ImageManipulator * @throws \Exception */ private function prepareResponsiveVersions($imagePath, &$node) { $srcSetAttributes = array(); foreach ($this->getResponsiveSizes() as $newSize) { $image = $this->getNewImageManipulator($imagePath); $newPath = $image->getStoragePath($newSize); if( !file_exists($newPath) || empty(Settings::get("enable_cache", false))){ $image->resize($newSize, null); if($this->shouldWatermark()){ $image->applyWatermark(); } // $newPath = $image->getStoragePath($newSize); $image->save($newPath); $srcSetAttributes[] = sprintf('%s %sw', $image->getPublicUrl($newPath), $newSize); } else { $srcSetAttributes[] = sprintf('%s %sw', $image->getPublicUrl($newPath), $newSize); } } $node->setAttribute('srcset', implode(",", $srcSetAttributes)); } /** * Gets max (limit) image width from settings * @return int */ private function getMaxWidth(){ return (int)trim($this->s->get("max_width")); } /** * Remove the local host name from path src and add the base path. * * @param $node * @return mixed */ protected function getFilePathFromNode($node) { $imagePath = rawurldecode($this->domImageFinder->getSrcAttribute($node)); return str_replace(URL::to('/'), '', base_path($imagePath)); } }
webeks/octobercms-imageking
classes/ImageService.php
PHP
mit
8,124
const _transform = require('lodash/transform'); function MatchTransformer(match) { if( !(this instanceof MatchTransformer) ) { return this.transform(new MatchTransformer(match)); } if( typeof match === 'string' ) { // Escape string match = match.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); match = new RegExp(match); } this._match = match; } MatchTransformer.prototype.parse = function(source) { return _transform(source, (result, value, key) => { if( this._match.test(key) ) result[key] = value; }, {}); }; MatchTransformer.prototype.reverse = MatchTransformer.prototype.parse; module.exports = MatchTransformer;
bubobox/parse-js
src/transformers/match.js
JavaScript
mit
696
import ProgressBar from "progress"; import padEnd from "lodash/padEnd"; class ProgressBarController { constructor() { this.bar = null; } init(total) { if (this.bar) { this.terminate(); } // Intentionally a noop because node-progress doesn't work well in non-TTY // environments if (!process.stdout.isTTY) { return; } // Don't do any of this while testing if (process.env.NODE_ENV === "lerna-test") { return; } this.bar = new ProgressBar(":packagename ╢:bar╟", { total: total, complete: "█", incomplete: "░", clear: true, // terminal columns - package name length - additional characters length width: (process.stdout.columns || 100) - 50 - 3 }); } tick(name) { if (this.bar) { this.bar.tick({ packagename: padEnd(name.slice(0, 50), 50) }); } } clear() { if (this.bar) { this.bar.terminate(); } } restore() { if (this.bar) { // This is a hack to get the bar to redraw it's last state. // See: https://github.com/tj/node-progress/blob/d47913502ba5b551fcaad9e94fe7b2f5876a7939/lib/node-progress.js#L154-L159 this.bar.stream.write(this.bar.lastDraw); } } terminate() { this.clear(); this.bar = null; } } export default new ProgressBarController();
onigoetz/lerna-hg
src/progressBar.js
JavaScript
mit
1,365
var commons = require('../commons') var frisby = require('frisby'); var FormData = require('form-data'); frisby.create('Get file') .get(commons.host+'/file/2134354/zgzhrthztrh/sgeh' ) .after(function(err, res, body) { expect(res.request.href.match(/errcode=404/)).not.toBeNull() }) .toss()
bodji/test2
test/file/non_existing_spec.js
JavaScript
mit
312
<?php namespace Frontend\PublicBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class FrontendPublicExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
OliverMartin/Travel
src/Frontend/PublicBundle/DependencyInjection/FrontendPublicExtension.php
PHP
mit
887
package command import ( "fmt" "os" "path/filepath" "time" "github.com/kemokemo/gckdir/lib" "github.com/skratchdot/open-golang/open" "github.com/urfave/cli" ) var ( // UsageVerify is Usage of verify subcommand for cli UsageVerify = "Verifies the structure and each hash value of files." ) // CmdVerify verifies directory information below cases. // Case 1. a json file of hash list with target directory // Case 2. source directory with target directory func CmdVerify(c *cli.Context) error { help := fmt.Sprintf("Please see '%s %s --help'.", c.App.Name, c.Command.FullName()) source := c.Args().Get(0) target := c.Args().Get(1) if source == "" || target == "" { return cli.NewExitError( fmt.Sprintf("Source path or target path is empty. %s", help), ExitCodeInvalidArguments) } source = filepath.Clean(source) target = filepath.Clean(target) sourceList, err := lib.GetHashList(source) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to get the hash list. %v\n%s", err, help), ExitCodeFunctionError) } targetList, err := lib.GetHashList(target) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to get the hash list. %v\n%s", err, help), ExitCodeFunctionError) } result := lib.VerifyHashList(sourceList, targetList, !c.Bool("no-hv"), !c.Bool("no-uv")) var path string if c.Bool("report") || c.Bool("open") { pathList := lib.PathList{SourcePath: source, TargetPath: target} path, err = createReport(c.String("output"), pathList, result) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to create a result report. %v\n%s", err, help), ExitCodeFunctionError) } } if c.Bool("open") { err = open.Run(path) if err != nil { return cli.NewExitError( fmt.Sprintf("Failed to open a result report. %v\n%s", err, help), ExitCodeFunctionError) } } if result.VerifyResult == false { fmt.Println("Verification failed.") return cli.NewExitError("", ExitCodeVerificationFailed) } return nil } func createReport(output string, pathList lib.PathList, result lib.HashList) (string, error) { cd, err := os.Getwd() if err != nil { return "", err } if output == "" { output = time.Now().Format("Result_20060102-030405.000000000.html") } path := filepath.Join(cd, output) file, err := os.Create(path) defer func() { err = file.Close() if err != nil { fmt.Println("failed to close file: ", err) } }() err = lib.CreateReport(file, pathList, result) if err != nil { return "", err } path = filepath.Join("file:///", path) return path, nil }
KemoKemo/gckdir
command/verify.go
GO
mit
2,586
/// <reference path="Transform3D.ts" /> namespace zen { export class GameObject extends Transform3D { public name:string = "GameObject"; public tag:string = ""; public layer:string = ""; private _guid:string = zen.guid.create(); public get guid() { return this._guid; } private _app:Application; constructor(app:Application) { super(); this._app = app; } private _components:{[key:string]:Component} = {}; public addComponent(component:Component):void { let system:System = this._app.systemManager.getSystem(component.type); if(system) { if(!this._components[component.type]) { component.gameObject = this; system.addComponent(this, component); this._components[component.type] = component; } else { console.error("Game Object already has " + component.type + " Component"); } } else { console.error("System: " + component.type + " doesn't exist"); } } public getComponent<T extends Component>(type:ComponentType | number):T { return <T>this._components[type]; } public removeComponent(component:Component):void { let system:System = this._app.systemManager.getSystem(component.type); if(system) { if(this._components[component.type]) { component.gameObject = null; system.removeComponent(this); delete this._components[component.type]; } else { console.error("Game Object doesn't have " + component.type + " Component"); } } else { console.error("System: " + component.type + " doesn't exist"); } } } }
shawn0326/zen
src/GameObject.ts
TypeScript
mit
1,986
<?php get_template_part('templates/front', 'page'); ?>
miso999/nabytoktt
front-page.php
PHP
mit
59
module.exports = function(grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ // watch for changes and trigger compass, jshint, uglify and livereload watch: { js: { files: ['jquery.accrue.js'], tasks: ['jshint','uglify'], options: { livereload: true, }, }, css: { files: 'example.scss', tasks: ['sass'], options: { livereload: true, }, } }, // we use the Sass sass: { dist: { options: { // nested, compact, compressed, expanded style: 'compressed' }, files: { 'example.css': 'example.scss' } } }, // uglify to concat & minify uglify: { js: { files: { 'jquery.accrue.min.js': 'jquery.accrue.js', } } }, // lint me. jshint: { all: ['jquery.accrue.js'] } }); // register task grunt.registerTask('default', ['watch']); };
jpederson/Accrue.js
gruntfile.js
JavaScript
mit
1,376
require "lita" Lita.load_locales Dir[File.expand_path( File.join("..", "..", "locales", "*.yml"), __FILE__ )] require "lita/handlers/urban"
taylorlapeyre/lita-urban
lib/lita-urban.rb
Ruby
mit
144
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO; using System.Text; public class KinectManager : MonoBehaviour { public enum Smoothing : int { None, Default, Medium, Aggressive } // Public Bool to determine how many players there are. Default of one user. public bool TwoUsers = false; // Public Bool to determine if the sensor is used in near mode. public bool NearMode = false; // Public Bool to determine whether to receive and compute the user map public bool ComputeUserMap = false; // Public Bool to determine whether to receive and compute the color map public bool ComputeColorMap = false; // Public Bool to determine whether to display user map on the GUI public bool DisplayUserMap = false; // Public Bool to determine whether to display color map on the GUI public bool DisplayColorMap = false; // Public Bool to determine whether to display the skeleton lines on user map public bool DisplaySkeletonLines = false; // Public Floats to specify the width and height of the depth and color maps as % of the camera width and height // if percents are zero, they are calculated based on actual Kinect image´s width and height public float MapsPercentWidth = 0f; public float MapsPercentHeight = 0f; // How high off the ground is the sensor (in meters). public float SensorHeight = 1.0f; // Kinect elevation angle (in degrees) public int SensorAngle = 0; // Minimum user distance in order to process skeleton data public float MinUserDistance = 1.0f; // Public Bool to determine whether to detect only the closest user or not public bool DetectClosestUser = true; // Public Bool to determine whether to use only the tracked joints (and ignore the inferred ones) public bool IgnoreInferredJoints = true; // Selection of smoothing parameters public Smoothing smoothing = Smoothing.Default; // Public Bool to determine the use of additional filters public bool UseBoneOrientationsFilter = false; public bool UseClippedLegsFilter = false; public bool UseBoneOrientationsConstraint = true; public bool UseSelfIntersectionConstraint = false; // Lists of GameObjects that will be controlled by which player. public List<GameObject> Player1Avatars; public List<GameObject> Player2Avatars; // Calibration poses for each player, if needed public KinectGestures.Gestures Player1CalibrationPose; public KinectGestures.Gestures Player2CalibrationPose; // List of Gestures to detect for each player public List<KinectGestures.Gestures> Player1Gestures; public List<KinectGestures.Gestures> Player2Gestures; // Minimum time between gesture detections public float MinTimeBetweenGestures = 0f; // List of Gesture Listeners. They must implement KinectGestures.GestureListenerInterface public List<MonoBehaviour> GestureListeners; // GUI Text to show messages. public GameObject CalibrationText; // GUI Texture to display the hand cursor for Player1 public GameObject HandCursor1; // GUI Texture to display the hand cursor for Player1 public GameObject HandCursor2; // Bool to specify whether Left/Right-hand-cursor and the Click-gesture control the mouse cursor and click public bool ControlMouseCursor = false; // Bool to keep track of whether Kinect has been initialized private bool KinectInitialized = false; // Bools to keep track of who is currently calibrated. private bool Player1Calibrated = false; private bool Player2Calibrated = false; private bool AllPlayersCalibrated = false; // Values to track which ID (assigned by the Kinect) is player 1 and player 2. private uint Player1ID; private uint Player2ID; // Lists of AvatarControllers that will let the models get updated. private List<AvatarController> Player1Controllers; private List<AvatarController> Player2Controllers; // User Map vars. private Texture2D usersLblTex; private Color32[] usersMapColors; private ushort[] usersPrevState; private Rect usersMapRect; private int usersMapSize; private Texture2D usersClrTex; //Color[] usersClrColors; private Rect usersClrRect; //short[] usersLabelMap; private short[] usersDepthMap; private float[] usersHistogramMap; // List of all users private List<uint> allUsers; // Image stream handles for the kinect private IntPtr colorStreamHandle; private IntPtr depthStreamHandle; // Color image data, if used private Color32[] colorImage; private byte[] usersColorMap; // Skeleton related structures private KinectWrapper.NuiSkeletonFrame skeletonFrame; private KinectWrapper.NuiTransformSmoothParameters smoothParameters; private int player1Index, player2Index; // Skeleton tracking states, positions and joints' orientations private Vector3 player1Pos, player2Pos; private Matrix4x4 player1Ori, player2Ori; private bool[] player1JointsTracked, player2JointsTracked; private bool[] player1PrevTracked, player2PrevTracked; private Vector3[] player1JointsPos, player2JointsPos; private Matrix4x4[] player1JointsOri, player2JointsOri; private KinectWrapper.NuiSkeletonBoneOrientation[] jointOrientations; // Calibration gesture data for each player private KinectGestures.GestureData player1CalibrationData; private KinectGestures.GestureData player2CalibrationData; // Lists of gesture data, for each player private List<KinectGestures.GestureData> player1Gestures = new List<KinectGestures.GestureData>(); private List<KinectGestures.GestureData> player2Gestures = new List<KinectGestures.GestureData>(); // general gesture tracking time start private float[] gestureTrackingAtTime; // List of Gesture Listeners. They must implement KinectGestures.GestureListenerInterface public List<KinectGestures.GestureListenerInterface> gestureListeners; private Matrix4x4 kinectToWorld, flipMatrix; private static KinectManager instance; // Timer for controlling Filter Lerp blends. private float lastNuiTime; // Filters private TrackingStateFilter[] trackingStateFilter; private BoneOrientationsFilter[] boneOrientationFilter; private ClippedLegsFilter[] clippedLegsFilter; private BoneOrientationsConstraint boneConstraintsFilter; private SelfIntersectionConstraint selfIntersectionConstraint; // returns the single KinectManager instance public static KinectManager Instance { get { return instance; } } // checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization public static bool IsKinectInitialized() { return instance != null ? instance.KinectInitialized : false; } // checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization public bool IsInitialized() { return KinectInitialized; } // this function is used internally by AvatarController public static bool IsCalibrationNeeded() { return false; } // // returns the raw depth/user data,if ComputeUserMap is true // public short[] GetUsersDepthMap() // { // return usersDepthMap; // } // returns the depth data for a specific pixel,if ComputeUserMap is true public short GetDepthForPixel(int x, int y) { int index = y * KinectWrapper.Constants.ImageWidth + x; if(index >= 0 && index < usersDepthMap.Length) return usersDepthMap[index]; else return 0; } // returns the depth map position for a 3d joint position public Vector2 GetDepthMapPosForJointPos(Vector3 posJoint) { Vector3 vDepthPos = KinectWrapper.MapSkeletonPointToDepthPoint(posJoint); Vector2 vMapPos = new Vector2(vDepthPos.x, vDepthPos.y); return vMapPos; } // returns the color map position for a depth 2d position public Vector2 GetColorMapPosForDepthPos(Vector2 posDepth) { int cx, cy; KinectWrapper.NuiImageViewArea pcViewArea = new KinectWrapper.NuiImageViewArea { eDigitalZoom = 0, lCenterX = 0, lCenterY = 0 }; int hr = KinectWrapper.NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution( KinectWrapper.Constants.ImageResolution, KinectWrapper.Constants.ImageResolution, ref pcViewArea, (int)posDepth.x, (int)posDepth.y, GetDepthForPixel((int)posDepth.x, (int)posDepth.y), out cx, out cy); return new Vector2(cx, cy); } // returns the depth image/users histogram texture,if ComputeUserMap is true public Texture2D GetUsersLblTex() { return usersLblTex; } // returns the color image texture,if ComputeColorMap is true public Texture2D GetUsersClrTex() { return usersClrTex; } // returns true if at least one user is currently detected by the sensor public bool IsUserDetected() { return KinectInitialized && (allUsers.Count > 0); } // returns the UserID of Player1, or 0 if no Player1 is detected public uint GetPlayer1ID() { return Player1ID; } // returns the UserID of Player2, or 0 if no Player2 is detected public uint GetPlayer2ID() { return Player2ID; } // returns true if the User is calibrated and ready to use public bool IsPlayerCalibrated(uint UserId) { if(UserId == Player1ID) return Player1Calibrated; else if(UserId == Player2ID) return Player2Calibrated; return false; } // returns the raw unmodified joint position, as returned by the Kinect sensor public Vector3 GetRawSkeletonJointPos(uint UserId, int joint) { if(UserId == Player1ID) return joint >= 0 && joint < player1JointsPos.Length ? (Vector3)skeletonFrame.SkeletonData[player1Index].SkeletonPositions[joint] : Vector3.zero; else if(UserId == Player2ID) return joint >= 0 && joint < player2JointsPos.Length ? (Vector3)skeletonFrame.SkeletonData[player2Index].SkeletonPositions[joint] : Vector3.zero; return Vector3.zero; } // returns the User position, relative to the Kinect-sensor, in meters public Vector3 GetUserPosition(uint UserId) { if(UserId == Player1ID) return player1Pos; else if(UserId == Player2ID) return player2Pos; return Vector3.zero; } // returns the User rotation, relative to the Kinect-sensor public Quaternion GetUserOrientation(uint UserId, bool flip) { if(UserId == Player1ID && player1JointsTracked[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter]) return ConvertMatrixToQuat(player1Ori, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter, flip); else if(UserId == Player2ID && player2JointsTracked[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter]) return ConvertMatrixToQuat(player2Ori, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter, flip); return Quaternion.identity; } // returns true if the given joint of the specified user is being tracked public bool IsJointTracked(uint UserId, int joint) { if(UserId == Player1ID) return joint >= 0 && joint < player1JointsTracked.Length ? player1JointsTracked[joint] : false; else if(UserId == Player2ID) return joint >= 0 && joint < player2JointsTracked.Length ? player2JointsTracked[joint] : false; return false; } // returns the joint position of the specified user, relative to the Kinect-sensor, in meters public Vector3 GetJointPosition(uint UserId, int joint) { if(UserId == Player1ID) return joint >= 0 && joint < player1JointsPos.Length ? player1JointsPos[joint] : Vector3.zero; else if(UserId == Player2ID) return joint >= 0 && joint < player2JointsPos.Length ? player2JointsPos[joint] : Vector3.zero; return Vector3.zero; } // returns the local joint position of the specified user, relative to the parent joint, in meters public Vector3 GetJointLocalPosition(uint UserId, int joint) { int parent = KinectWrapper.GetSkeletonJointParent(joint); if(UserId == Player1ID) return joint >= 0 && joint < player1JointsPos.Length ? (player1JointsPos[joint] - player1JointsPos[parent]) : Vector3.zero; else if(UserId == Player2ID) return joint >= 0 && joint < player2JointsPos.Length ? (player2JointsPos[joint] - player2JointsPos[parent]) : Vector3.zero; return Vector3.zero; } // returns the joint rotation of the specified user, relative to the Kinect-sensor public Quaternion GetJointOrientation(uint UserId, int joint, bool flip) { if(UserId == Player1ID) { if(joint >= 0 && joint < player1JointsOri.Length && player1JointsTracked[joint]) return ConvertMatrixToQuat(player1JointsOri[joint], joint, flip); } else if(UserId == Player2ID) { if(joint >= 0 && joint < player2JointsOri.Length && player2JointsTracked[joint]) return ConvertMatrixToQuat(player2JointsOri[joint], joint, flip); } return Quaternion.identity; } // returns the joint rotation of the specified user, relative to the parent joint public Quaternion GetJointLocalOrientation(uint UserId, int joint, bool flip) { int parent = KinectWrapper.GetSkeletonJointParent(joint); if(UserId == Player1ID) { if(joint >= 0 && joint < player1JointsOri.Length && player1JointsTracked[joint]) { Matrix4x4 localMat = (player1JointsOri[parent].inverse * player1JointsOri[joint]); return Quaternion.LookRotation(localMat.GetColumn(2), localMat.GetColumn(1)); } } else if(UserId == Player2ID) { if(joint >= 0 && joint < player2JointsOri.Length && player2JointsTracked[joint]) { Matrix4x4 localMat = (player2JointsOri[parent].inverse * player2JointsOri[joint]); return Quaternion.LookRotation(localMat.GetColumn(2), localMat.GetColumn(1)); } } return Quaternion.identity; } // returns the direction between baseJoint and nextJoint, for the specified user public Vector3 GetDirectionBetweenJoints(uint UserId, int baseJoint, int nextJoint, bool flipX, bool flipZ) { Vector3 jointDir = Vector3.zero; if(UserId == Player1ID) { if(baseJoint >= 0 && baseJoint < player1JointsPos.Length && player1JointsTracked[baseJoint] && nextJoint >= 0 && nextJoint < player1JointsPos.Length && player1JointsTracked[nextJoint]) { jointDir = player1JointsPos[nextJoint] - player1JointsPos[baseJoint]; } } else if(UserId == Player2ID) { if(baseJoint >= 0 && baseJoint < player2JointsPos.Length && player2JointsTracked[baseJoint] && nextJoint >= 0 && nextJoint < player2JointsPos.Length && player2JointsTracked[nextJoint]) { jointDir = player2JointsPos[nextJoint] - player2JointsPos[baseJoint]; } } if(jointDir != Vector3.zero) { if(flipX) jointDir.x = -jointDir.x; if(flipZ) jointDir.z = -jointDir.z; } return jointDir; } // adds a gesture to the list of detected gestures for the specified user public void DetectGesture(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); if(index >= 0) DeleteGesture(UserId, gesture); KinectGestures.GestureData gestureData = new KinectGestures.GestureData(); gestureData.userId = UserId; gestureData.gesture = gesture; gestureData.state = 0; gestureData.joint = 0; gestureData.progress = 0f; gestureData.complete = false; gestureData.cancelled = false; gestureData.checkForGestures = new List<KinectGestures.Gestures>(); switch(gesture) { case KinectGestures.Gestures.ZoomIn: gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomOut); gestureData.checkForGestures.Add(KinectGestures.Gestures.Wheel); break; case KinectGestures.Gestures.ZoomOut: gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomIn); gestureData.checkForGestures.Add(KinectGestures.Gestures.Wheel); break; case KinectGestures.Gestures.Wheel: gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomIn); gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomOut); break; // case KinectGestures.Gestures.Jump: // gestureData.checkForGestures.Add(KinectGestures.Gestures.Squat); // break; // // case KinectGestures.Gestures.Squat: // gestureData.checkForGestures.Add(KinectGestures.Gestures.Jump); // break; // // case KinectGestures.Gestures.Push: // gestureData.checkForGestures.Add(KinectGestures.Gestures.Pull); // break; // // case KinectGestures.Gestures.Pull: // gestureData.checkForGestures.Add(KinectGestures.Gestures.Push); // break; } if(UserId == Player1ID) player1Gestures.Add(gestureData); else if(UserId == Player2ID) player2Gestures.Add(gestureData); } // resets the gesture-data state for the given gesture of the specified user public bool ResetGesture(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); if(index < 0) return false; KinectGestures.GestureData gestureData = (UserId == Player1ID) ? player1Gestures[index] : player2Gestures[index]; gestureData.state = 0; gestureData.joint = 0; gestureData.progress = 0f; gestureData.complete = false; gestureData.cancelled = false; gestureData.startTrackingAtTime = Time.realtimeSinceStartup + KinectWrapper.Constants.MinTimeBetweenSameGestures; if(UserId == Player1ID) player1Gestures[index] = gestureData; else if(UserId == Player2ID) player2Gestures[index] = gestureData; return true; } // resets the gesture-data states for all detected gestures of the specified user public void ResetPlayerGestures(uint UserId) { if(UserId == Player1ID) { int listSize = player1Gestures.Count; for(int i = 0; i < listSize; i++) { ResetGesture(UserId, player1Gestures[i].gesture); } } else if(UserId == Player2ID) { int listSize = player2Gestures.Count; for(int i = 0; i < listSize; i++) { ResetGesture(UserId, player2Gestures[i].gesture); } } } // deletes the given gesture from the list of detected gestures for the specified user public bool DeleteGesture(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); if(index < 0) return false; if(UserId == Player1ID) player1Gestures.RemoveAt(index); else if(UserId == Player2ID) player2Gestures.RemoveAt(index); return true; } // clears detected gestures list for the specified user public void ClearGestures(uint UserId) { if(UserId == Player1ID) { player1Gestures.Clear(); } else if(UserId == Player2ID) { player2Gestures.Clear(); } } // returns the count of detected gestures in the list of detected gestures for the specified user public int GetGesturesCount(uint UserId) { if(UserId == Player1ID) return player1Gestures.Count; else if(UserId == Player2ID) return player2Gestures.Count; return 0; } // returns the list of detected gestures for the specified user public List<KinectGestures.Gestures> GetGesturesList(uint UserId) { List<KinectGestures.Gestures> list = new List<KinectGestures.Gestures>(); if(UserId == Player1ID) { foreach(KinectGestures.GestureData data in player1Gestures) list.Add(data.gesture); } else if(UserId == Player2ID) { foreach(KinectGestures.GestureData data in player1Gestures) list.Add(data.gesture); } return list; } // returns true, if the given gesture is in the list of detected gestures for the specified user public bool IsGestureDetected(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); return index >= 0; } // returns true, if the given gesture for the specified user is complete public bool IsGestureComplete(uint UserId, KinectGestures.Gestures gesture, bool bResetOnComplete) { int index = GetGestureIndex(UserId, gesture); if(index >= 0) { if(UserId == Player1ID) { KinectGestures.GestureData gestureData = player1Gestures[index]; if(bResetOnComplete && gestureData.complete) { ResetPlayerGestures(UserId); return true; } return gestureData.complete; } else if(UserId == Player2ID) { KinectGestures.GestureData gestureData = player2Gestures[index]; if(bResetOnComplete && gestureData.complete) { ResetPlayerGestures(UserId); return true; } return gestureData.complete; } } return false; } // returns true, if the given gesture for the specified user is cancelled public bool IsGestureCancelled(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); if(index >= 0) { if(UserId == Player1ID) { KinectGestures.GestureData gestureData = player1Gestures[index]; return gestureData.cancelled; } else if(UserId == Player2ID) { KinectGestures.GestureData gestureData = player2Gestures[index]; return gestureData.cancelled; } } return false; } // returns the progress in range [0, 1] of the given gesture for the specified user public float GetGestureProgress(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); if(index >= 0) { if(UserId == Player1ID) { KinectGestures.GestureData gestureData = player1Gestures[index]; return gestureData.progress; } else if(UserId == Player2ID) { KinectGestures.GestureData gestureData = player2Gestures[index]; return gestureData.progress; } } return 0f; } // returns the current "screen position" of the given gesture for the specified user public Vector3 GetGestureScreenPos(uint UserId, KinectGestures.Gestures gesture) { int index = GetGestureIndex(UserId, gesture); if(index >= 0) { if(UserId == Player1ID) { KinectGestures.GestureData gestureData = player1Gestures[index]; return gestureData.screenPos; } else if(UserId == Player2ID) { KinectGestures.GestureData gestureData = player2Gestures[index]; return gestureData.screenPos; } } return Vector3.zero; } // recreates and reinitializes the lists of avatar controllers, after the list of avatars for player 1/2 was changed public void SetAvatarControllers() { if(Player1Avatars.Count == 0 && Player2Avatars.Count == 0) { AvatarController[] avatars = FindObjectsOfType(typeof(AvatarController)) as AvatarController[]; foreach(AvatarController avatar in avatars) { Player1Avatars.Add(avatar.gameObject); } } if(Player1Controllers != null) { Player1Controllers.Clear(); foreach(GameObject avatar in Player1Avatars) { if(avatar != null && avatar.activeInHierarchy) { AvatarController controller = avatar.GetComponent<AvatarController>(); controller.RotateToInitialPosition(); controller.Start(); Player1Controllers.Add(controller); } } } if(Player2Controllers != null) { Player2Controllers.Clear(); foreach(GameObject avatar in Player2Avatars) { if(avatar != null && avatar.activeInHierarchy) { AvatarController controller = avatar.GetComponent<AvatarController>(); controller.RotateToInitialPosition(); controller.Start(); Player2Controllers.Add(controller); } } } } // removes the currently detected kinect users, allowing a new detection/calibration process to start public void ClearKinectUsers() { if(!KinectInitialized) return; // remove current users for(int i = allUsers.Count - 1; i >= 0; i--) { uint userId = allUsers[i]; RemoveUser(userId); } ResetFilters(); } // clears Kinect buffers and resets the filters public void ResetFilters() { if(!KinectInitialized) return; // clear kinect vars player1Pos = Vector3.zero; player2Pos = Vector3.zero; player1Ori = Matrix4x4.identity; player2Ori = Matrix4x4.identity; int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count; for(int i = 0; i < skeletonJointsCount; i++) { player1JointsTracked[i] = false; player2JointsTracked[i] = false; player1PrevTracked[i] = false; player2PrevTracked[i] = false; player1JointsPos[i] = Vector3.zero; player2JointsPos[i] = Vector3.zero; player1JointsOri[i] = Matrix4x4.identity; player2JointsOri[i] = Matrix4x4.identity; } if(trackingStateFilter != null) { for(int i = 0; i < trackingStateFilter.Length; i++) if(trackingStateFilter[i] != null) trackingStateFilter[i].Reset(); } if(boneOrientationFilter != null) { for(int i = 0; i < boneOrientationFilter.Length; i++) if(boneOrientationFilter[i] != null) boneOrientationFilter[i].Reset(); } if(clippedLegsFilter != null) { for(int i = 0; i < clippedLegsFilter.Length; i++) if(clippedLegsFilter[i] != null) clippedLegsFilter[i].Reset(); } } //----------------------------------- end of public functions --------------------------------------// void Start() { //CalibrationText = GameObject.Find("CalibrationText"); int hr = 0; try { hr = KinectWrapper.NuiInitialize(KinectWrapper.NuiInitializeFlags.UsesSkeleton | KinectWrapper.NuiInitializeFlags.UsesDepthAndPlayerIndex | (ComputeColorMap ? KinectWrapper.NuiInitializeFlags.UsesColor : 0)); if (hr != 0) { throw new Exception("NuiInitialize Failed"); } hr = KinectWrapper.NuiSkeletonTrackingEnable(IntPtr.Zero, 8); // 0, 12,8 if (hr != 0) { throw new Exception("Cannot initialize Skeleton Data"); } depthStreamHandle = IntPtr.Zero; if(ComputeUserMap) { hr = KinectWrapper.NuiImageStreamOpen(KinectWrapper.NuiImageType.DepthAndPlayerIndex, KinectWrapper.Constants.ImageResolution, 0, 2, IntPtr.Zero, ref depthStreamHandle); if (hr != 0) { throw new Exception("Cannot open depth stream"); } } colorStreamHandle = IntPtr.Zero; if(ComputeColorMap) { hr = KinectWrapper.NuiImageStreamOpen(KinectWrapper.NuiImageType.Color, KinectWrapper.Constants.ImageResolution, 0, 2, IntPtr.Zero, ref colorStreamHandle); if (hr != 0) { throw new Exception("Cannot open color stream"); } } // set kinect elevation angle KinectWrapper.NuiCameraElevationSetAngle(SensorAngle); // init skeleton structures skeletonFrame = new KinectWrapper.NuiSkeletonFrame() { SkeletonData = new KinectWrapper.NuiSkeletonData[KinectWrapper.Constants.NuiSkeletonCount] }; // values used to pass to smoothing function smoothParameters = new KinectWrapper.NuiTransformSmoothParameters(); switch(smoothing) { case Smoothing.Default: smoothParameters.fSmoothing = 0.5f; smoothParameters.fCorrection = 0.5f; smoothParameters.fPrediction = 0.5f; smoothParameters.fJitterRadius = 0.05f; smoothParameters.fMaxDeviationRadius = 0.04f; break; case Smoothing.Medium: smoothParameters.fSmoothing = 0.5f; smoothParameters.fCorrection = 0.1f; smoothParameters.fPrediction = 0.5f; smoothParameters.fJitterRadius = 0.1f; smoothParameters.fMaxDeviationRadius = 0.1f; break; case Smoothing.Aggressive: smoothParameters.fSmoothing = 0.7f; smoothParameters.fCorrection = 0.3f; smoothParameters.fPrediction = 1.0f; smoothParameters.fJitterRadius = 1.0f; smoothParameters.fMaxDeviationRadius = 1.0f; break; } // init the tracking state filter trackingStateFilter = new TrackingStateFilter[KinectWrapper.Constants.NuiSkeletonMaxTracked]; for(int i = 0; i < trackingStateFilter.Length; i++) { trackingStateFilter[i] = new TrackingStateFilter(); trackingStateFilter[i].Init(); } // init the bone orientation filter boneOrientationFilter = new BoneOrientationsFilter[KinectWrapper.Constants.NuiSkeletonMaxTracked]; for(int i = 0; i < boneOrientationFilter.Length; i++) { boneOrientationFilter[i] = new BoneOrientationsFilter(); boneOrientationFilter[i].Init(); } // init the clipped legs filter clippedLegsFilter = new ClippedLegsFilter[KinectWrapper.Constants.NuiSkeletonMaxTracked]; for(int i = 0; i < clippedLegsFilter.Length; i++) { clippedLegsFilter[i] = new ClippedLegsFilter(); } // init the bone orientation constraints boneConstraintsFilter = new BoneOrientationsConstraint(); boneConstraintsFilter.AddDefaultConstraints(); // init the self intersection constraints selfIntersectionConstraint = new SelfIntersectionConstraint(); // create arrays for joint positions and joint orientations int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count; player1JointsTracked = new bool[skeletonJointsCount]; player2JointsTracked = new bool[skeletonJointsCount]; player1PrevTracked = new bool[skeletonJointsCount]; player2PrevTracked = new bool[skeletonJointsCount]; player1JointsPos = new Vector3[skeletonJointsCount]; player2JointsPos = new Vector3[skeletonJointsCount]; player1JointsOri = new Matrix4x4[skeletonJointsCount]; player2JointsOri = new Matrix4x4[skeletonJointsCount]; gestureTrackingAtTime = new float[KinectWrapper.Constants.NuiSkeletonMaxTracked]; //create the transform matrix that converts from kinect-space to world-space Quaternion quatTiltAngle = new Quaternion(); quatTiltAngle.eulerAngles = new Vector3(-SensorAngle, 0.0f, 0.0f); //float heightAboveHips = SensorHeight - 1.0f; // transform matrix - kinect to world //kinectToWorld.SetTRS(new Vector3(0.0f, heightAboveHips, 0.0f), quatTiltAngle, Vector3.one); kinectToWorld.SetTRS(new Vector3(0.0f, SensorHeight, 0.0f), quatTiltAngle, Vector3.one); flipMatrix = Matrix4x4.identity; flipMatrix[2, 2] = -1; instance = this; DontDestroyOnLoad(gameObject); } catch(DllNotFoundException e) { string message = "Please check the Kinect SDK installation."; Debug.LogError(message); Debug.LogError(e.ToString()); if(CalibrationText != null) CalibrationText.guiText.text = message; return; } catch (Exception e) { string message = e.Message + " - " + KinectWrapper.GetNuiErrorString(hr); Debug.LogError(message); Debug.LogError(e.ToString()); if(CalibrationText != null) CalibrationText.guiText.text = message; return; } // get the main camera rectangle Rect cameraRect = Camera.main.pixelRect; // calculate map width and height in percent, if needed if(MapsPercentWidth == 0f) MapsPercentWidth = (KinectWrapper.GetDepthWidth() / 2) / cameraRect.width; if(MapsPercentHeight == 0f) MapsPercentHeight = (KinectWrapper.GetDepthHeight() / 2) / cameraRect.height; if(ComputeUserMap) { // Initialize depth & label map related stuff usersMapSize = KinectWrapper.GetDepthWidth() * KinectWrapper.GetDepthHeight(); usersLblTex = new Texture2D(KinectWrapper.GetDepthWidth(), KinectWrapper.GetDepthHeight()); usersMapColors = new Color32[usersMapSize]; usersPrevState = new ushort[usersMapSize]; //usersMapRect = new Rect(Screen.width, Screen.height - usersLblTex.height / 2, -usersLblTex.width / 2, usersLblTex.height / 2); //usersMapRect = new Rect(cameraRect.width, cameraRect.height - cameraRect.height * MapsPercentHeight, -cameraRect.width * MapsPercentWidth, cameraRect.height * MapsPercentHeight); usersMapRect = new Rect(cameraRect.width - cameraRect.width * MapsPercentWidth, cameraRect.height, cameraRect.width * MapsPercentWidth, -cameraRect.height * MapsPercentHeight); usersDepthMap = new short[usersMapSize]; usersHistogramMap = new float[8192]; } if(ComputeColorMap) { // Initialize color map related stuff usersClrTex = new Texture2D(KinectWrapper.GetDepthWidth(), KinectWrapper.GetDepthHeight()); //usersClrRect = new Rect(cameraRect.width, cameraRect.height - cameraRect.height * MapsPercentHeight, -cameraRect.width * MapsPercentWidth, cameraRect.height * MapsPercentHeight); usersClrRect = new Rect(cameraRect.width - cameraRect.width * MapsPercentWidth, cameraRect.height, cameraRect.width * MapsPercentWidth, -cameraRect.height * MapsPercentHeight); if(ComputeUserMap) usersMapRect.x -= cameraRect.width * MapsPercentWidth; //usersClrTex.width / 2; colorImage = new Color32[KinectWrapper.GetDepthWidth() * KinectWrapper.GetDepthHeight()]; usersColorMap = new byte[colorImage.Length << 2]; } // try to automatically find the available avatar controllers in the scene if(Player1Avatars.Count == 0 && Player2Avatars.Count == 0) { AvatarController[] avatars = FindObjectsOfType(typeof(AvatarController)) as AvatarController[]; foreach(AvatarController avatar in avatars) { Player1Avatars.Add(avatar.gameObject); } } // Initialize user list to contain ALL users. allUsers = new List<uint>(); // Pull the AvatarController from each of the players Avatars. Player1Controllers = new List<AvatarController>(); Player2Controllers = new List<AvatarController>(); // Add each of the avatars' controllers into a list for each player. foreach(GameObject avatar in Player1Avatars) { if(avatar != null && avatar.activeInHierarchy) { Player1Controllers.Add(avatar.GetComponent<AvatarController>()); } } foreach(GameObject avatar in Player2Avatars) { if(avatar != null && avatar.activeInHierarchy) { Player2Controllers.Add(avatar.GetComponent<AvatarController>()); } } // create the list of gesture listeners gestureListeners = new List<KinectGestures.GestureListenerInterface>(); foreach(MonoBehaviour script in GestureListeners) { if(script && (script is KinectGestures.GestureListenerInterface)) { KinectGestures.GestureListenerInterface listener = (KinectGestures.GestureListenerInterface)script; gestureListeners.Add(listener); } } // GUI Text. if(CalibrationText != null) { CalibrationText.guiText.text = "WAITING FOR USERS"; } Debug.Log("Waiting for users."); KinectInitialized = true; } void Update() { if(KinectInitialized) { // // for testing purposes only // KinectWrapper.UpdateKinectSensor(); // If the players aren't all calibrated yet, draw the user map. if(ComputeUserMap) { if(depthStreamHandle != IntPtr.Zero && KinectWrapper.PollDepth(depthStreamHandle, NearMode, ref usersDepthMap)) { UpdateUserMap(); } } if(ComputeColorMap) { if(colorStreamHandle != IntPtr.Zero && KinectWrapper.PollColor(colorStreamHandle, ref usersColorMap, ref colorImage)) { UpdateColorMap(); } } if(KinectWrapper.PollSkeleton(ref smoothParameters, ref skeletonFrame)) { ProcessSkeleton(); } // Update player 1's models if he/she is calibrated and the model is active. if(Player1Calibrated) { foreach (AvatarController controller in Player1Controllers) { //if(controller.Active) { controller.UpdateAvatar(Player1ID, NearMode); } } // Check for complete gestures foreach(KinectGestures.GestureData gestureData in player1Gestures) { if(gestureData.complete) { if(gestureData.gesture == KinectGestures.Gestures.Click) { if(ControlMouseCursor) { MouseControl.MouseClick(); } } foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { if(listener.GestureCompleted(Player1ID, 0, gestureData.gesture, (KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos)) { ResetPlayerGestures(Player1ID); } } } else if(gestureData.cancelled) { foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { if(listener.GestureCancelled(Player1ID, 0, gestureData.gesture, (KinectWrapper.SkeletonJoint)gestureData.joint)) { ResetGesture(Player1ID, gestureData.gesture); } } } else if(gestureData.progress >= 0.1f) { if((gestureData.gesture == KinectGestures.Gestures.RightHandCursor || gestureData.gesture == KinectGestures.Gestures.LeftHandCursor) && gestureData.progress >= 0.5f) { if(HandCursor1 != null) { HandCursor1.transform.position = Vector3.Lerp(HandCursor1.transform.position, gestureData.screenPos, 3 * Time.deltaTime); } if(ControlMouseCursor) { MouseControl.MouseMove(gestureData.screenPos); } } foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { listener.GestureInProgress(Player1ID, 0, gestureData.gesture, gestureData.progress, (KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos); } } } } // Update player 2's models if he/she is calibrated and the model is active. if(Player2Calibrated) { foreach (AvatarController controller in Player2Controllers) { //if(controller.Active) { controller.UpdateAvatar(Player2ID, NearMode); } } // Check for complete gestures foreach(KinectGestures.GestureData gestureData in player2Gestures) { if(gestureData.complete) { if(gestureData.gesture == KinectGestures.Gestures.Click) { if(ControlMouseCursor) { MouseControl.MouseClick(); } } foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { if(listener.GestureCompleted(Player2ID, 1, gestureData.gesture, (KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos)) { ResetPlayerGestures(Player2ID); } } } else if(gestureData.cancelled) { foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { if(listener.GestureCancelled(Player2ID, 1, gestureData.gesture, (KinectWrapper.SkeletonJoint)gestureData.joint)) { ResetGesture(Player2ID, gestureData.gesture); } } } else if(gestureData.progress >= 0.1f) { if((gestureData.gesture == KinectGestures.Gestures.RightHandCursor || gestureData.gesture == KinectGestures.Gestures.LeftHandCursor) && gestureData.progress >= 0.5f) { if(HandCursor2 != null) { HandCursor2.transform.position = Vector3.Lerp(HandCursor2.transform.position, gestureData.screenPos, 3 * Time.deltaTime); } if(ControlMouseCursor) { MouseControl.MouseMove(gestureData.screenPos); } } foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { listener.GestureInProgress(Player2ID, 1, gestureData.gesture, gestureData.progress, (KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos); } } } } } // Kill the program with ESC. if(Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } // Make sure to kill the Kinect on quitting. void OnApplicationQuit() { if(KinectInitialized) { // Shutdown OpenNI KinectWrapper.NuiShutdown(); instance = null; } } // Draw the Histogram Map on the GUI. void OnGUI() { if(KinectInitialized) { if(ComputeUserMap && (/**(allUsers.Count == 0) ||*/ DisplayUserMap)) { GUI.DrawTexture(usersMapRect, usersLblTex); } if(ComputeColorMap && (/**(allUsers.Count == 0) ||*/ DisplayColorMap)) { GUI.DrawTexture(usersClrRect, usersClrTex); } } } // Update the User Map void UpdateUserMap() { int numOfPoints = 0; Array.Clear(usersHistogramMap, 0, usersHistogramMap.Length); // Calculate cumulative histogram for depth for (int i = 0; i < usersMapSize; i++) { // Only calculate for depth that contains users if ((usersDepthMap[i] & 7) != 0) { usersHistogramMap[usersDepthMap[i] >> 3]++; numOfPoints++; } } if (numOfPoints > 0) { for (int i = 1; i < usersHistogramMap.Length; i++) { usersHistogramMap[i] += usersHistogramMap[i-1]; } for (int i = 0; i < usersHistogramMap.Length; i++) { usersHistogramMap[i] = 1.0f - (usersHistogramMap[i] / numOfPoints); } } // dummy structure needed by the coordinate mapper KinectWrapper.NuiImageViewArea pcViewArea = new KinectWrapper.NuiImageViewArea { eDigitalZoom = 0, lCenterX = 0, lCenterY = 0 }; // Create the actual users texture based on label map and depth histogram Color32 clrClear = Color.clear; for (int i = 0; i < usersMapSize; i++) { // Flip the texture as we convert label map to color array int flipIndex = i; // usersMapSize - i - 1; ushort userMap = (ushort)(usersDepthMap[i] & 7); ushort userDepth = (ushort)(usersDepthMap[i] >> 3); ushort nowUserPixel = userMap != 0 ? (ushort)((userMap << 13) | userDepth) : userDepth; ushort wasUserPixel = usersPrevState[flipIndex]; // draw only the changed pixels if(nowUserPixel != wasUserPixel) { usersPrevState[flipIndex] = nowUserPixel; if (userMap == 0) { usersMapColors[flipIndex] = clrClear; } else { if(colorImage != null) { int x = i % KinectWrapper.Constants.ImageWidth; int y = i / KinectWrapper.Constants.ImageWidth; int cx, cy; int hr = KinectWrapper.NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution( KinectWrapper.Constants.ImageResolution, KinectWrapper.Constants.ImageResolution, ref pcViewArea, x, y, usersDepthMap[i], out cx, out cy); if(hr == 0) { int colorIndex = cx + cy * KinectWrapper.Constants.ImageWidth; //colorIndex = usersMapSize - colorIndex - 1; if(colorIndex >= 0 && colorIndex < usersMapSize) { Color32 colorPixel = colorImage[colorIndex]; usersMapColors[flipIndex] = colorPixel; // new Color(colorPixel.r / 256f, colorPixel.g / 256f, colorPixel.b / 256f, 0.9f); usersMapColors[flipIndex].a = 230; // 0.9f } } } else { // Create a blending color based on the depth histogram float histDepth = usersHistogramMap[userDepth]; Color c = new Color(histDepth, histDepth, histDepth, 0.9f); switch(userMap % 4) { case 0: usersMapColors[flipIndex] = Color.red * c; break; case 1: usersMapColors[flipIndex] = Color.green * c; break; case 2: usersMapColors[flipIndex] = Color.blue * c; break; case 3: usersMapColors[flipIndex] = Color.magenta * c; break; } } } } } // Draw it! usersLblTex.SetPixels32(usersMapColors); usersLblTex.Apply(); } // Update the Color Map void UpdateColorMap() { usersClrTex.SetPixels32(colorImage); usersClrTex.Apply(); } // Assign UserId to player 1 or 2. void CalibrateUser(uint UserId, ref KinectWrapper.NuiSkeletonData skeletonData) { // If player 1 hasn't been calibrated, assign that UserID to it. if(!Player1Calibrated) { // Check to make sure we don't accidentally assign player 2 to player 1. if (!allUsers.Contains(UserId)) { if(CheckForCalibrationPose(UserId, ref Player1CalibrationPose, ref player1CalibrationData, ref skeletonData)) { Player1Calibrated = true; Player1ID = UserId; allUsers.Add(UserId); foreach(AvatarController controller in Player1Controllers) { controller.SuccessfulCalibration(UserId); } // add the gestures to detect, if any foreach(KinectGestures.Gestures gesture in Player1Gestures) { DetectGesture(UserId, gesture); } print ("user.detected"); // notify the gesture listeners about the new user foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { listener.UserDetected(UserId, 0); } // reset skeleton filters ResetFilters(); // If we're not using 2 users, we're all calibrated. //if(!TwoUsers) { AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // true; } } } } // Otherwise, assign to player 2. else if(TwoUsers && !Player2Calibrated) { if (!allUsers.Contains(UserId)) { if(CheckForCalibrationPose(UserId, ref Player2CalibrationPose, ref player2CalibrationData, ref skeletonData)) { Player2Calibrated = true; Player2ID = UserId; allUsers.Add(UserId); foreach(AvatarController controller in Player2Controllers) { controller.SuccessfulCalibration(UserId); } // add the gestures to detect, if any foreach(KinectGestures.Gestures gesture in Player2Gestures) { DetectGesture(UserId, gesture); } // notify the gesture listeners about the new user foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { listener.UserDetected(UserId, 1); } // reset skeleton filters ResetFilters(); // All users are calibrated! AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // true; } } } // If all users are calibrated, stop trying to find them. if(AllPlayersCalibrated) { Debug.Log("All players calibrated."); if(CalibrationText != null) { CalibrationText.guiText.text = ""; } } } // Remove a lost UserId void RemoveUser(uint UserId) { // If we lose player 1... if(UserId == Player1ID) { // Null out the ID and reset all the models associated with that ID. Player1ID = 0; Player1Calibrated = false; foreach(AvatarController controller in Player1Controllers) { controller.RotateToCalibrationPose(UserId, IsCalibrationNeeded()); } foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { listener.UserLost(UserId, 0); } player1CalibrationData.userId = 0; } // If we lose player 2... if(UserId == Player2ID) { // Null out the ID and reset all the models associated with that ID. Player2ID = 0; Player2Calibrated = false; foreach(AvatarController controller in Player2Controllers) { controller.RotateToCalibrationPose(UserId, IsCalibrationNeeded()); } foreach(KinectGestures.GestureListenerInterface listener in gestureListeners) { listener.UserLost(UserId, 1); } player2CalibrationData.userId = 0; } // clear gestures list for this user ClearGestures(UserId); // remove from global users list allUsers.Remove(UserId); AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // false; // Try to replace that user! Debug.Log("Waiting for users."); if(CalibrationText != null) { CalibrationText.guiText.text = "WAITING FOR USERS"; } } // Some internal constants private const int stateTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.Tracked; private const int stateNotTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.NotTracked; private int [] mustBeTrackedJoints = { (int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft, (int)KinectWrapper.NuiSkeletonPositionIndex.FootLeft, (int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight, (int)KinectWrapper.NuiSkeletonPositionIndex.FootRight, }; // Process the skeleton data void ProcessSkeleton() { List<uint> lostUsers = new List<uint>(); lostUsers.AddRange(allUsers); // calculate the time since last update float currentNuiTime = Time.realtimeSinceStartup; float deltaNuiTime = currentNuiTime - lastNuiTime; for(int i = 0; i < KinectWrapper.Constants.NuiSkeletonCount; i++) { KinectWrapper.NuiSkeletonData skeletonData = skeletonFrame.SkeletonData[i]; uint userId = skeletonData.dwTrackingID; if(skeletonData.eTrackingState == KinectWrapper.NuiSkeletonTrackingState.SkeletonTracked) { // get the skeleton position Vector3 skeletonPos = kinectToWorld.MultiplyPoint3x4(skeletonData.Position); if(!AllPlayersCalibrated) { // check if this is the closest user bool bClosestUser = true; if(DetectClosestUser) { for(int j = 0; j < KinectWrapper.Constants.NuiSkeletonCount; j++) { if(j != i) { KinectWrapper.NuiSkeletonData skeletonDataOther = skeletonFrame.SkeletonData[j]; if((skeletonDataOther.eTrackingState == KinectWrapper.NuiSkeletonTrackingState.SkeletonTracked) && (Mathf.Abs(kinectToWorld.MultiplyPoint3x4(skeletonDataOther.Position).z) < Mathf.Abs(skeletonPos.z))) { bClosestUser = false; break; } } } } if(bClosestUser) { CalibrateUser(userId, ref skeletonData); } } //// get joints orientations //KinectWrapper.NuiSkeletonBoneOrientation[] jointOrients = new KinectWrapper.NuiSkeletonBoneOrientation[(int)KinectWrapper.NuiSkeletonPositionIndex.Count]; //KinectWrapper.NuiSkeletonCalculateBoneOrientations(ref skeletonData, jointOrients); if(userId == Player1ID && Mathf.Abs(skeletonPos.z) >= MinUserDistance) { player1Index = i; // get player position player1Pos = skeletonPos; // apply tracking state filter first trackingStateFilter[0].UpdateFilter(ref skeletonData); // fixup skeleton to improve avatar appearance. if(UseClippedLegsFilter && clippedLegsFilter[0] != null) { clippedLegsFilter[0].FilterSkeleton(ref skeletonData, deltaNuiTime); } if(UseSelfIntersectionConstraint && selfIntersectionConstraint != null) { selfIntersectionConstraint.Constrain(ref skeletonData); } // get joints' position and rotation for (int j = 0; j < (int)KinectWrapper.NuiSkeletonPositionIndex.Count; j++) { bool playerTracked = IgnoreInferredJoints ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked : (Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked : (int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked); player1JointsTracked[j] = player1PrevTracked[j] && playerTracked; player1PrevTracked[j] = playerTracked; if(player1JointsTracked[j]) { player1JointsPos[j] = kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]); //player1JointsOri[j] = jointOrients[j].absoluteRotation.rotationMatrix * flipMatrix; } // if(j == (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter) // { // string debugText = String.Format("{0} {1}", /**(int)skeletonData.eSkeletonPositionTrackingState[j], */ // player1JointsTracked[j] ? "T" : "F", player1JointsPos[j]/**, skeletonData.SkeletonPositions[j]*/); // // if(CalibrationText) // CalibrationText.guiText.text = debugText; // } } // draw the skeleton on top of texture if(DisplaySkeletonLines && ComputeUserMap) { DrawSkeleton(usersLblTex, ref skeletonData, ref player1JointsTracked); } // calculate joint orientations KinectWrapper.GetSkeletonJointOrientation(ref player1JointsPos, ref player1JointsTracked, ref player1JointsOri); // filter orientation constraints if(UseBoneOrientationsConstraint && boneConstraintsFilter != null) { boneConstraintsFilter.Constrain(ref player1JointsOri, ref player1JointsTracked); } // filter joint orientations. // it should be performed after all joint position modifications. if(UseBoneOrientationsFilter && boneOrientationFilter[0] != null) { boneOrientationFilter[0].UpdateFilter(ref skeletonData, ref player1JointsOri); } // get player rotation player1Ori = player1JointsOri[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter]; // check for gestures if(Time.realtimeSinceStartup >= gestureTrackingAtTime[0]) { int listGestureSize = player1Gestures.Count; float timestampNow = Time.realtimeSinceStartup; for(int g = 0; g < listGestureSize; g++) { KinectGestures.GestureData gestureData = player1Gestures[g]; if((timestampNow >= gestureData.startTrackingAtTime) && !IsConflictingGestureInProgress(gestureData)) { KinectGestures.CheckForGesture(userId, ref gestureData, Time.realtimeSinceStartup, ref player1JointsPos, ref player1JointsTracked); player1Gestures[g] = gestureData; if(gestureData.complete) { gestureTrackingAtTime[0] = timestampNow + MinTimeBetweenGestures; } } } } } else if(userId == Player2ID && Mathf.Abs(skeletonPos.z) >= MinUserDistance) { player2Index = i; // get player position player2Pos = skeletonPos; // apply tracking state filter first trackingStateFilter[1].UpdateFilter(ref skeletonData); // fixup skeleton to improve avatar appearance. if(UseClippedLegsFilter && clippedLegsFilter[1] != null) { clippedLegsFilter[1].FilterSkeleton(ref skeletonData, deltaNuiTime); } if(UseSelfIntersectionConstraint && selfIntersectionConstraint != null) { selfIntersectionConstraint.Constrain(ref skeletonData); } // get joints' position and rotation for (int j = 0; j < (int)KinectWrapper.NuiSkeletonPositionIndex.Count; j++) { bool playerTracked = IgnoreInferredJoints ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked : (Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked : (int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked); player2JointsTracked[j] = player2PrevTracked[j] && playerTracked; player2PrevTracked[j] = playerTracked; if(player2JointsTracked[j]) { player2JointsPos[j] = kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]); } } // draw the skeleton on top of texture if(DisplaySkeletonLines && ComputeUserMap) { DrawSkeleton(usersLblTex, ref skeletonData, ref player2JointsTracked); } // calculate joint orientations KinectWrapper.GetSkeletonJointOrientation(ref player2JointsPos, ref player2JointsTracked, ref player2JointsOri); // filter orientation constraints if(UseBoneOrientationsConstraint && boneConstraintsFilter != null) { boneConstraintsFilter.Constrain(ref player2JointsOri, ref player2JointsTracked); } // filter joint orientations. // it should be performed after all joint position modifications. if(UseBoneOrientationsFilter && boneOrientationFilter[1] != null) { boneOrientationFilter[1].UpdateFilter(ref skeletonData, ref player2JointsOri); } // get player rotation player2Ori = player2JointsOri[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter]; // check for gestures if(Time.realtimeSinceStartup >= gestureTrackingAtTime[1]) { int listGestureSize = player2Gestures.Count; float timestampNow = Time.realtimeSinceStartup; for(int g = 0; g < listGestureSize; g++) { KinectGestures.GestureData gestureData = player2Gestures[g]; if((timestampNow >= gestureData.startTrackingAtTime) && !IsConflictingGestureInProgress(gestureData)) { KinectGestures.CheckForGesture(userId, ref gestureData, Time.realtimeSinceStartup, ref player2JointsPos, ref player2JointsTracked); player2Gestures[g] = gestureData; if(gestureData.complete) { gestureTrackingAtTime[1] = timestampNow + MinTimeBetweenGestures; } } } } } lostUsers.Remove(userId); } } // update the nui-timer lastNuiTime = currentNuiTime; // remove the lost users if any if(lostUsers.Count > 0) { foreach(uint userId in lostUsers) { RemoveUser(userId); } lostUsers.Clear(); } } // draws the skeleton in the given texture private void DrawSkeleton(Texture2D aTexture, ref KinectWrapper.NuiSkeletonData skeletonData, ref bool[] playerJointsTracked) { int jointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count; for(int i = 0; i < jointsCount; i++) { int parent = KinectWrapper.GetSkeletonJointParent(i); if(playerJointsTracked[i] && playerJointsTracked[parent]) { Vector3 posParent = KinectWrapper.MapSkeletonPointToDepthPoint(skeletonData.SkeletonPositions[parent]); Vector3 posJoint = KinectWrapper.MapSkeletonPointToDepthPoint(skeletonData.SkeletonPositions[i]); // posParent.y = KinectWrapper.Constants.ImageHeight - posParent.y - 1; // posJoint.y = KinectWrapper.Constants.ImageHeight - posJoint.y - 1; // posParent.x = KinectWrapper.Constants.ImageWidth - posParent.x - 1; // posJoint.x = KinectWrapper.Constants.ImageWidth - posJoint.x - 1; //Color lineColor = playerJointsTracked[i] && playerJointsTracked[parent] ? Color.red : Color.yellow; DrawLine(aTexture, (int)posParent.x, (int)posParent.y, (int)posJoint.x, (int)posJoint.y, Color.yellow); } } aTexture.Apply(); } // draws a line in a texture private void DrawLine(Texture2D a_Texture, int x1, int y1, int x2, int y2, Color a_Color) { int width = KinectWrapper.Constants.ImageWidth; int height = KinectWrapper.Constants.ImageHeight; int dy = y2 - y1; int dx = x2 - x1; int stepy = 1; if (dy < 0) { dy = -dy; stepy = -1; } int stepx = 1; if (dx < 0) { dx = -dx; stepx = -1; } dy <<= 1; dx <<= 1; if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height) for(int x = -1; x <= 1; x++) for(int y = -1; y <= 1; y++) a_Texture.SetPixel(x1 + x, y1 + y, a_Color); if (dx > dy) { int fraction = dy - (dx >> 1); while (x1 != x2) { if (fraction >= 0) { y1 += stepy; fraction -= dx; } x1 += stepx; fraction += dy; if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height) for(int x = -1; x <= 1; x++) for(int y = -1; y <= 1; y++) a_Texture.SetPixel(x1 + x, y1 + y, a_Color); } } else { int fraction = dx - (dy >> 1); while (y1 != y2) { if (fraction >= 0) { x1 += stepx; fraction -= dy; } y1 += stepy; fraction += dx; if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height) for(int x = -1; x <= 1; x++) for(int y = -1; y <= 1; y++) a_Texture.SetPixel(x1 + x, y1 + y, a_Color); } } } // convert the matrix to quaternion, taking care of the mirroring private Quaternion ConvertMatrixToQuat(Matrix4x4 mOrient, int joint, bool flip) { Vector4 vZ = mOrient.GetColumn(2); Vector4 vY = mOrient.GetColumn(1); if(!flip) { vZ.y = -vZ.y; vY.x = -vY.x; vY.z = -vY.z; } else { vZ.x = -vZ.x; vZ.y = -vZ.y; vY.z = -vY.z; } if(vZ.x != 0.0f || vZ.y != 0.0f || vZ.z != 0.0f) return Quaternion.LookRotation(vZ, vY); else return Quaternion.identity; } // return the index of gesture in the list, or -1 if not found private int GetGestureIndex(uint UserId, KinectGestures.Gestures gesture) { if(UserId == Player1ID) { int listSize = player1Gestures.Count; for(int i = 0; i < listSize; i++) { if(player1Gestures[i].gesture == gesture) return i; } } else if(UserId == Player2ID) { int listSize = player2Gestures.Count; for(int i = 0; i < listSize; i++) { if(player2Gestures[i].gesture == gesture) return i; } } return -1; } private bool IsConflictingGestureInProgress(KinectGestures.GestureData gestureData) { foreach(KinectGestures.Gestures gesture in gestureData.checkForGestures) { int index = GetGestureIndex(gestureData.userId, gesture); if(index >= 0) { if(gestureData.userId == Player1ID) { if(player1Gestures[index].progress > 0f) return true; } else if(gestureData.userId == Player2ID) { if(player2Gestures[index].progress > 0f) return true; } } } return false; } // check if the calibration pose is complete for given user private bool CheckForCalibrationPose(uint userId, ref KinectGestures.Gestures calibrationGesture, ref KinectGestures.GestureData gestureData, ref KinectWrapper.NuiSkeletonData skeletonData) { if(calibrationGesture == KinectGestures.Gestures.None) return true; // init gesture data if needed if(gestureData.userId != userId) { gestureData.userId = userId; gestureData.gesture = calibrationGesture; gestureData.state = 0; gestureData.joint = 0; gestureData.progress = 0f; gestureData.complete = false; gestureData.cancelled = false; } // get temporary joints' position int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count; bool[] jointsTracked = new bool[skeletonJointsCount]; Vector3[] jointsPos = new Vector3[skeletonJointsCount]; int stateTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.Tracked; int stateNotTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.NotTracked; int [] mustBeTrackedJoints = { (int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft, (int)KinectWrapper.NuiSkeletonPositionIndex.FootLeft, (int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight, (int)KinectWrapper.NuiSkeletonPositionIndex.FootRight, }; for (int j = 0; j < skeletonJointsCount; j++) { jointsTracked[j] = Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked : (int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked; if(jointsTracked[j]) { jointsPos[j] = kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]); } } // estimate the gesture progess KinectGestures.CheckForGesture(userId, ref gestureData, Time.realtimeSinceStartup, ref jointsPos, ref jointsTracked); // check if gesture is complete if(gestureData.complete) { gestureData.userId = 0; return true; } return false; } }
Acidburn0zzz/Corridors
Assets/KinectScripts/KinectManager.cs
C#
mit
63,304
<?php namespace Lam\MdlBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Lam\MdlBundle\Entity\FormationInformatique * @ORM\Table() * @ORM\Entity(repositoryClass="Lam\MdlBundle\Entity\FormationInformatiqueRepository") */ class Formationinformatique { /** * @var integer $id * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string $titre * * @ORM\Column(name="Titre", type="string", length=100, nullable=false) */ private $titre; /** * @var text $objectif * * @ORM\Column(name="Objectif", type="text", nullable=false) */ private $objectif; /** * @var string $public * * @ORM\Column(name="Public", type="string", length=150, nullable=false) */ private $public; /** * @var text $prerequis * * @ORM\Column(name="Prerequis", type="text", nullable=false) */ private $prerequis; /** * @var string $logo * * @ORM\Column(name="Logo", type="string", length=50, nullable=false) */ private $logo; /** * @var integer $nbplace * * @ORM\Column(name="nbPlace", type="integer", nullable=false) */ private $nbplace; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set titre * * @param string $titre */ public function setTitre($titre) { $this->titre = $titre; } /** * Get titre * * @return string */ public function getTitre() { return $this->titre; } /** * Set objectif * * @param text $objectif */ public function setObjectif($objectif) { $this->objectif = $objectif; } /** * Get objectif * * @return text */ public function getObjectif() { return $this->objectif; } /** * Set public * * @param string $public */ public function setPublic($public) { $this->public = $public; } /** * Get public * * @return string */ public function getPublic() { return $this->public; } /** * Set prerequis * * @param text $prerequis */ public function setPrerequis($prerequis) { $this->prerequis = $prerequis; } /** * Get prerequis * * @return text */ public function getPrerequis() { return $this->prerequis; } /** * Set logo * * @param string $logo */ public function setLogo($logo) { $this->logo = $logo; } /** * Get logo * * @return string */ public function getLogo() { return $this->logo; } /** * Set nbplace * * @param integer $nbplace */ public function setNbplace($nbplace) { $this->nbplace = $nbplace; } /** * Get nbplace * * @return integer */ public function getNbplace() { return $this->nbplace; } }
gody77/SymfonyMDL
src/Lam/MdlBundle/Entity/FormationInformatique.php
PHP
mit
3,232
package com.hackathon.hackathon2014.activity; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import com.hackathon.hackathon2014.R; import com.hackathon.hackathon2014.webservice.PostRequestHandler; import com.hackathon.hackathon2014.webservice.RestProvider; import com.hackathon.hackathon2014.adapter.QuestionListAdapter; import com.hackathon.hackathon2014.model.Question; import java.util.List; public class QuestionActivity extends Activity { public static String EXTRA_QUESTION = "question"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.question, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.fragment_question, container, false); Toast.makeText(rootView.getContext(),"Loading...",Toast.LENGTH_LONG).show(); RestProvider.getQuestions(new PostRequestHandler<List<Question>>() { @Override public void handle(List<Question> questions) { QuestionListAdapter questionListAdapter = new QuestionListAdapter(getActivity(), questions); ListView listView = (ListView) rootView.findViewById(R.id.questionListView); listView.setAdapter(questionListAdapter); listView.setOnItemClickListener(new OpenAnswerEvent(getActivity(), questions)); } }); return rootView; } private class OpenAnswerEvent implements android.widget.AdapterView.OnItemClickListener { private List<Question> questions; private Activity activity; private OpenAnswerEvent(Activity activity, List<Question> questions) { this.activity = activity; this.questions = questions; } @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Question question = questions.get(i); question.setSelected(true); Intent intent = new Intent(activity,CategoryActivity.class); intent.putExtra(EXTRA_QUESTION, question); activity.startActivity(intent); final ImageView questionIcon = (ImageView) view.findViewById(R.id.questionIcon); QuestionListAdapter.renderChecked(question.isSelected(), questionIcon, R.drawable.ok_enable, R.drawable.ok_disable); } } } }
dst-hackathon/socialradar-android
hackathon2014/app/src/main/java/com/hackathon/hackathon2014/activity/QuestionActivity.java
Java
mit
4,070
package net.tqft.iterables.interfaces; public interface Transformer<S, T> { public abstract T evaluate(S s); }
craigfreilly/masters-project-submission
src/KnotTheory/JavaKh-v2/src/net/tqft/iterables/interfaces/Transformer.java
Java
mit
126
require "capybarel/dsl/elements" require "capybarel/dsl/javascript" require "capybarel/dsl/from_yaml" module Capybarel module DSL module All include Capybarel::DSL::Elements include Capybarel::DSL::JavaScript include Capybarel::DSL::FromYaml end end end
fantactuka/capybarel
lib/capybarel/dsl.rb
Ruby
mit
285
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import update from 'immutability-helper'; class ListItemBullet extends Component { render() { let cssClasses = `listbullet`; const bulletStyle = { border: `5px solid ${this.props.color}`, backgroundColor: 'white' }; return ( <div className={cssClasses} style={bulletStyle}></div> ); } }; class MyRouteMap extends Component { render() { const renderList = (list) => { const lis = list.map((data, index) => { return (<li key={index}><ListItemBullet color={this.props.color} /> { data.url? (<a href={data.url}><span className='description'>{data.name}</span><div className='details'>This is a test.<br/>This is second line</div></a>) : (<span className='description'>{data.name}</span>) } </li>); }) return lis; }; const cssClasses = `App-routemap ${this.props.color}`; const ulStyle = { //color: this.props.color, marginTop: '30px' }; const ulBeforeStyle = { content: " ", position: 'absolute', marginLeft: '8px', left: '0px', top: '20px', bottom: '40px', width: '12px', zIndex: -5, backgroundColor: this.props.color }; return ( <div className="App-routemap-div"> <h2>{this.props.title}</h2> <ul className={cssClasses} style={ulStyle}> <div style={ulBeforeStyle}></div> { renderList(this.props.datalist) } </ul> </div> ); } } class App extends Component { constructor() { super(); this.state = { list_unix: [ { name: "Git 使用與教學", url: "https://se101.mtsa.me/Slide/Git/#/" } ], 'list_system': [ "作業系統概述", "分散式系統架構", "Scaling Up" ], 'list_data': [ "大數據分析簡介", "TensorFlow 簡介", ], 'list_algo': [ "Python3 語法介紹", "演算法簡介", "基礎資料結構", "字串處理", "動態規劃", "圖論演算法" ] }; } handleClick(e) { var p = this.state.list_data; p.push("Test Item"); var newState = update(this.state, {'list_data': {$set: p}}); this.setState(newState); } render() { return ( <div className="App"> <div className="App-header"> <h1>SE101: 我想成為軟體工程師!</h1> <span className="App-intro">UMich Taiwanese Software Engineers Reading Group - Fall 2017</span> </div> <div className="App-contents"> <MyRouteMap title='黑框框與開發者工具'datalist={this.state.list_unix} color='red' /> <MyRouteMap title='系統架設與維運' datalist={this.state.list_system} color='darkgreen' /> <MyRouteMap title='資料科學與技術' datalist={this.state.list_data} color='darkblue' /> <MyRouteMap title='編程面試與程式語言' datalist={this.state.list_algo} color='orange' /> </div> </div> ); //<button onClick={() => this.handleClick()}>Add Item</button> } } export default App;
tmt514/se101f17
website/src/App.js
JavaScript
mit
3,281
using System; using System.IO; namespace Pulse.Core { /// <summary> /// НЕ потокобезопасный! /// </summary> public sealed class StreamSegment : Stream { private long _offset, _length; public readonly Stream BaseStream; public StreamSegment(Stream stream, long offset, long length, FileAccess access) { Exceptions.CheckArgumentNull(stream, "stream"); if (offset < 0 || offset >= stream.Length) throw new ArgumentOutOfRangeException("offset", offset, "Смещение выходит за границы потока."); if (offset + length > stream.Length) throw new ArgumentOutOfRangeException("length", length, "Недопустимая длина."); _offset = offset; _length = length; BaseStream = stream; switch (access) { case FileAccess.Read: BaseStream.Position = _offset; break; case FileAccess.Write: BaseStream.Position = _offset; break; default: BaseStream.Seek(_offset, SeekOrigin.Begin); break; } } public override bool CanRead { get { return BaseStream.CanRead; } } public override bool CanSeek { get { return BaseStream.CanSeek; } } public override bool CanWrite { get { return BaseStream.CanWrite; } } public override long Length { get { return _length; } } public override long Position { get { return BaseStream.Position - _offset; } set { BaseStream.Position = value + _offset; } } public override void Flush() { BaseStream.Flush(); } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: Position = offset; break; case SeekOrigin.Current: Position += offset; break; case SeekOrigin.End: Position = Length + offset; break; } return Position; } public void SetOffset(long value) { _offset = value; } public override void SetLength(long value) { _length = value; } public override int Read(byte[] buffer, int offset, int count) { return BaseStream.Read(buffer, offset, (int)Math.Min(count, Length - Position)); } public override void Write(byte[] buffer, int offset, int count) { BaseStream.Write(buffer, offset, count); } } }
kidaa/Pulse
Pulse.Core/Components/StreamSegment.cs
C#
mit
3,012
import Ember from 'ember'; export default Ember.Component.extend({ tagName: '', didInsertElement: function() { this.startPoppover(); }, willDestroyElement: function() { this.dismissPoppover(); }, startPoppover: function() { var options = this.getPoppoverOptions(); Ember.$(function() { Ember.$('[data-toggle="popover"]').popover(options); }); }, getPoppoverOptions: function() { var template = Ember.$('.poppover-template').innerHTML; var content = Ember.$('.poppover-content').html(); return { template: template, placement: 'right', title: 'Download Tip', trigger: 'hover', content: content, html: true }; }, dismissPoppover: function() { Ember.$('[data-toggle="popover"]').popover('hide'); } });
iorrah/you-rockstar
app/components/resume/yr-download-tips.js
JavaScript
mit
806
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Str; class TagsTableSeeder extends Seeder { /** * Run the database seeding. */ public function run() { DB::table('tags')->truncate(); DB::table('tags')->insert([ [ 'name' => 'Qnique', 'slug' => Str::slug('qnique'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Quilting', 'slug' => Str::slug('quilting'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Quilting Machine', 'slug' => Str::slug('quilting-machine'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Sewing Machine', 'slug' => Str::slug('sewing-machine'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Expert Quilter', 'slug' => Str::slug('expert-quilter'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Quilting Tutorial', 'slug' => Str::slug('quilting-tutorial'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Hand Quilting', 'slug' => Str::slug('hand-quilting'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Hand Quilting Frame', 'slug' => Str::slug('hand-quilting-frame'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Quilting Hoop', 'slug' => Str::slug('quilting-hoop'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Quilting Lap Hoop', 'slug' => Str::slug('quilting-lap-hoop'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Grace', 'slug' => Str::slug('grace'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Grace Company', 'slug' => Str::slug('grace-company'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Grace Frame', 'slug' => Str::slug('grace-frame'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Grace Manufacturing', 'slug' => Str::slug('grace-manufacturing'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], [ 'name' => 'Affordable Programmer', 'slug' => Str::slug('affordable-programmer'), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'lang' => 'en', ], ]); } }
madsynn/LaraMaker
.temp/seeds/TagsTableSeeder.php
PHP
mit
4,116
/* * SonarLint for Visual Studio * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Diagnostics; using Microsoft.CodeAnalysis; using SonarAnalyzer.Helpers; using SonarLint.VisualStudio.Integration.Vsix.Suppression; namespace SonarLint.VisualStudio.Integration.Vsix { // This workflow affects only the VSIX Analyzers internal class SonarAnalyzerConnectedWorkflow : SonarAnalyzerWorkflowBase { private readonly IRoslynSuppressionHandler suppressionHandler; public SonarAnalyzerConnectedWorkflow(Workspace workspace, IRoslynSuppressionHandler suppressionHandler) : base(workspace) { if (suppressionHandler == null) { throw new ArgumentNullException(nameof(suppressionHandler)); } this.suppressionHandler = suppressionHandler; SonarAnalysisContext.ReportDiagnostic = VsixAnalyzerReportDiagnostic; } internal /* for testing purposes */ void VsixAnalyzerReportDiagnostic(IReportingContext context) { Debug.Assert(context.SyntaxTree != null, "Not expecting to be called with a null SyntaxTree"); Debug.Assert(context.Diagnostic != null, "Not expecting to be called with a null Diagnostic"); Debug.Assert(GetProjectNuGetAnalyzerStatus(context.SyntaxTree) == ProjectAnalyzerStatus.NoAnalyzer, "Not expecting to be called when project contains any SonarAnalyzer NuGet"); if (this.suppressionHandler.ShouldIssueBeReported(context.SyntaxTree, context.Diagnostic)) { context.ReportDiagnostic(context.Diagnostic); } } } }
SonarSource-VisualStudio/sonarlint-visualstudio
src/Integration.Vsix/Delegates/SonarAnalyzerConnectedWorkflow.cs
C#
mit
2,486
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * SoundcloudSearch Schema */ var SoundcloudSearchSchema = new Schema({ // SoundcloudSearch model fields // ... search: { type: String, required: 'There must be a search term', trim: true }, result: { type: Object }, created: { type: Date, default: Date.now } }); mongoose.model('SoundcloudSearch', SoundcloudSearchSchema);
bhops/Music
app/models/soundcloud-search.server.model.js
JavaScript
mit
463
import random # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): _largesize = 300 def __init__(self, head): self.head = head self.lsize = 0 while head.next: head = head.next self.lsize += 1 self.m1_idx = None self.m2_idx = None if self.lsize > self._largesize: self.m1_idx = self.lsize / 3 # start from 1/3 self.m1 = self._getN(self.m1_idx) self.m2_idx = self.m1_idx * 2 # start from 2/3 self.m2 = self._getN(self.m2_idx) def _getN(self, n): n -= 1 p = self.head while n: p = p.next n -= 1 return p def getRandom(self): def _get(delta, start): p = start while delta: p = p.next delta -= 1 return p.val nextpos = random.randint(0, self.lsize) if not self.m1_idx: return _get(nextpos, self.head) if nextpos < self.m1_idx: val = _get(nextpos, self.head) elif nextpos < self.m2_idx: val = _get(nextpos - self.m1_idx, self.m1) else: val = _get(nextpos - self.m2_idx, self.m2) return val
daicang/Leetcode-solutions
382-linked-list-random-node.py
Python
mit
1,372
package db import ( "io/ioutil" "os" . "fmt" "strings" . "github.com/yak-labs/chirp-lang" "github.com/yak-labs/smilax-web/table/levi" ) /* table get Site Table Row -> []Value table set Site Table Row []Value table match Site Table RowPattern ValuePattern -> []{row value} */ var Lev = levi.New("leveldb.dat") var data_dir = os.Getenv("SMILAX_DATA_DIR") var log_file = Sprintf("%s/table_log.txt", data_dir) func init() { if len(data_dir) == 0 { data_dir = "." } } func cmdTableLoad(fr *Frame, argv []T) T { Arg0(argv) TableLoad() return Empty } func cmdTableGet(fr *Frame, argv []T) T { site, table, row := Arg3(argv) return MkList(TableGet(site.String(), table.String(), row.String())) } func cmdTableSet(fr *Frame, argv []T) T { site, table, row, values := Arg4(argv) TableSet(site.String(), table.String(), row.String(), values.String()) return Empty } func cmdTableMatch(fr *Frame, argv []T) T { site, table, rowPat, valuePat := Arg4(argv) return MkList(TableMatch(site.String(), table.String(), rowPat.String(), valuePat.String())) } func TableLoad() { // Start with a fresh levelDB database. Lev.Close() err := os.RemoveAll("leveldb.data") if err != nil { panic(err) } Lev = levi.New("leveldb.dat") text, err := ioutil.ReadFile(log_file) if err != nil { panic(err) } lines := strings.Split(string(text), "\n") for _, line := range lines { line = strings.Trim(line, " \t") if line == "" || strings.HasPrefix(line, "#") { continue } words := ParseList(line) leviSet(words[0].String(), words[1].String(), words[2].String(), words[3].String()) } } func TableGet(site, table, row string) []T { key := Sprintf("/%s/%s/%s", site, table, row) vals := Lev.Get(key) return ParseList(vals) } func leviSet(site, table, row, values string) { key := Sprintf("/%s/%s/%s", site, table, row) Lev.Set(key, values) } func TableSet(site, table, row, values string) { leviSet(site, table, row, values) line := MkList( []T { MkString(site), MkString(table), MkString(row), MkString(values), }).String() line = Sprintf("%s\n", line) f, err := os.OpenFile(log_file, os.O_APPEND|os.O_WRONLY, 0600) if err != nil { panic(err) } defer f.Close() if _, err = f.WriteString(line); err != nil { panic(err) } } func TableMatch(site, table, rowPat, valuePat string) []T { threeSlashLen := len(site) + len(table) + 3 keyPattern := Sprintf("/%s/%s/%s", site, table, rowPat) prefix := keyPattern star := strings.IndexAny(prefix, "*[") if star >= 0 { prefix = prefix[:star] // Shorten prefix, stopping before '*'. } zz := make([]T, 0) it := Lev.Find(prefix) // for it.Next() // IF mappy for _ = it; it.Valid() ; it.Next() { key := string(it.Key()) value := string(it.Value()) if !strings.HasPrefix(key, prefix) { break // Gone too far. } if StringMatch(keyPattern, key) { z := make([]T, 0, 0) vv := ParseList(value) for _, v := range vv { if StringMatch(valuePat, v.String()) { z = append(z, v) } } if len(z) > 0 { zz = append(zz, MkList([]T{MkString(key[threeSlashLen:]), MkList(z)})) } } } if err := it.GetError(); err != nil { panic(err) } return zz } var tableEnsemble = []EnsembleItem{ EnsembleItem{Name: "load", Cmd: cmdTableLoad}, EnsembleItem{Name: "get", Cmd: cmdTableGet}, EnsembleItem{Name: "set", Cmd: cmdTableSet}, EnsembleItem{Name: "match", Cmd: cmdTableMatch}, } func init() { if Unsafes == nil { Unsafes = make(map[string]Command, 333) } Unsafes["table"] = MkEnsemble(tableEnsemble) }
yak-labs/smilax-web
table/table.go
GO
mit
3,563
package eu.cyfronoid.core.configuration.evaluator; import java.util.ArrayDeque; public class Stack extends ArrayDeque<Double> { private static final long serialVersionUID = 1L; @Override public void push(Double v) { super.push(v); } @Override public Double pop() { Double v = super.pop(); return v; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("["); for (Double v: this) { builder.append(v); builder.append(" "); } builder.append("]"); return builder.toString(); } }
widmofazowe/cyfronoid-core
src/eu/cyfronoid/core/configuration/evaluator/Stack.java
Java
mit
694
// * ———————————————————————————————————————————————————————— * // // * cli upload // * uploads image by providing a link by running: // * enduro upload http://www.imgur.com/asd.png // * ———————————————————————————————————————————————————————— * // var cli_upload = function () {} // vendor dependencies var Promise = require('bluebird') // local dependencies var logger = require(ENDURO_FOLDER + '/libs/logger') var file_uploader = require(ENDURO_FOLDER + '/libs/admin_utilities/file_uploader') // * ———————————————————————————————————————————————————————— * // // * cli upload // * generates object based on flag array // * // * @return {string} - url for uploaded link // * ———————————————————————————————————————————————————————— * // cli_upload.prototype.cli_upload = function (file_url) { if (!file_url) { logger.err('File url not specified\nUsage: $ enduro upload http://yourdomain.com/yourimage.png') return Promise.reject() } return file_uploader.upload_by_url(file_url) } module.exports = new cli_upload()
dmourato/mastercv
libs/cli_tools/cli_upload.js
JavaScript
mit
1,479
import React from "react" import Img from "gatsby-image" import { StaticQuery, graphql } from "gatsby" import html5 from "../images/html5.svg" import js from "../images/javascript.svg" import jQuery from "../images/jquery.svg" import php from "../images/php.svg" import python from "../images/python.svg" import css3 from "../images/css3.svg" import sass from "../images/sass.svg" import react from "../images/react.svg" import redux from "../images/redux.svg" import angular from "../images/angular.svg" import nodejs from "../images/nodejs.svg" import express from "../images/express.svg" import graphQL from "../images/graphql.svg" import apollo from "../images/apollo.svg" import laravel from "../images/laravel.svg" import django from "../images/django.svg" import ruby from "../images/ruby.svg" import rails from "../images/rails.svg" import firebase from "../images/firebase.svg" import mongodb from "../images/mongodb.svg" import postgresql from "../images/postgresql.svg" const About = ({ id }) => ( <StaticQuery query={graphql` query AboutImgQuery { aboutImg: file(relativePath: { eq: "towers.jpg" }) { childImageSharp { fluid(maxWidth: 1200) { ...GatsbyImageSharpFluid } } } } `} render={data => ( <section id={id} className="section cover"> <Img title="About image" alt="Towers" fluid={data.aboutImg.childImageSharp.fluid} style={{ borderBottom: "2px solid #0F2027", position: "absolute", left: 0, top: 0, width: "100%", height: "100%", }} /> <div className="overlay" /> <div className="about"> <h1 className="name mt-5"> <b>About Me</b> </h1> <div className="description mb-4"> <h5 className="greetings"> I'm a developer who is driven by the motivation to learn and utilize all of the <br /> newest and leading software technologies, tools and frameworks.{" "} <br /> Here are some of the technologies I have worked with: </h5> </div> <div className="svg-container"> <div className="logo-container"> <a href="https://rebrand.ly/w1zfk5" target="_blank" rel="noopener noreferrer" > <img src={html5} alt="html5" /> </a> <h5>HTML</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/gpe80b" target="_blank" rel="noopener noreferrer" > <img src={css3} alt="css3" /> </a> <h5>CSS</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/ac3zez" target="_blank" rel="noopener noreferrer" > <img src={sass} alt="sass" /> </a> <h5>Sass</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/gdw8nf" target="_blank" rel="noopener noreferrer" > <img src={js} alt="js" /> </a> <h5>JavaScript</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/t8q4kk" target="_blank" rel="noopener noreferrer" > <img src={jQuery} alt="jQuery" /> </a> <h5>jQuery</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/5dmk0k" target="_blank" rel="noopener noreferrer" > <img src={php} alt="php" /> </a> <h5>PHP</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/51v3f7" target="_blank" rel="noopener noreferrer" > <img src={ruby} alt="ruby" /> </a> <h5>Ruby</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/u9f3bu" target="_blank" rel="noopener noreferrer" > <img src={python} alt="python" /> </a> <h5>Python</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/4711zo" target="_blank" rel="noopener noreferrer" > <img src={react} alt="react" /> </a> <h5>React</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/f4fdtb" target="_blank" rel="noopener noreferrer" > <img src={redux} alt="redux" /> </a> <h5>Redux</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/0af3pn" target="_blank" rel="noopener noreferrer" > <img src={angular} alt="angular" /> </a> <h5>Angular</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/fno5hy" target="_blank" rel="noopener noreferrer" > <img src={nodejs} alt="nodejs" /> </a> <h5>Node</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/8pwvla" target="_blank" rel="noopener noreferrer" > <img src={express} alt="express" /> </a> <h5>Express</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/chgco7" target="_blank" rel="noopener noreferrer" > <img src={graphQL} alt="graphQL" /> </a> <h5>GraphQL</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/s8v7qq" target="_blank" rel="noopener noreferrer" > <img src={apollo} alt="apollo" /> </a> <h5>Apollo</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/jm3gu8" target="_blank" rel="noopener noreferrer" > <img src={laravel} alt="laravel" /> </a> <h5>Laravel</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/hbkv6c" target="_blank" rel="noopener noreferrer" > <img src={django} alt="django" /> </a> <h5>Django</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/71jw07" target="_blank" rel="noopener noreferrer" > <img src={rails} alt="rails" /> </a> <h5>Ruby on Rails</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/8jg10f" target="_blank" rel="noopener noreferrer" > <img src={firebase} alt="firebase" /> </a> <h5>Firebase</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/1lamx3" target="_blank" rel="noopener noreferrer" > <img src={mongodb} alt="mongodb" /> </a> <h5>MongoDB</h5> </div> <div className="logo-container"> <a href="https://rebrand.ly/az0ssm" target="_blank" rel="noopener noreferrer" > <img src={postgresql} alt="postgresql" /> </a> <h5>PostgreSQL</h5> </div> </div> <div className="arrow animated bounceInDown" /> </div> </section> )} /> ) export default About
ajspotts/ajspotts.github.io
src/components/about.js
JavaScript
mit
9,133
var debug = require('debug')('harmonyhubjs:client:login:hub') var Client = require('node-xmpp-client') var Q = require('q') var util = require('../util') /** PrivateFunction: getIdentity * Logs in to a Harmony hub as a guest and uses the userAuthToken from logitech's * web service to retrieve an identity token. * * Parameters: * (String) hubhost - Hostname/IP of the Harmony hub to connect. * (int) hubport - Optional. Port of the Harmony hub to connect. By default, * this is set to 5222. * * Returns: * (Q.promise) - The resolved promise passes the retrieved identity token. */ function getIdentity (hubhost, hubport) { debug('retrieve identity by logging in as guest') // guest@x.com / guest // guest@connect.logitech.com/gatorade var deferred = Q.defer() var iqId var xmppClient = new Client({ jid: 'guest@x.com/gatorade', password: 'guest', host: hubhost, port: hubport, disallowTLS: true, reconnect: true }) xmppClient.on('online', function () { debug('XMPP client connected') var body = 'method=pair:name=harmonyjs#iOS6.0.1#iPhone' var iq = util.buildIqStanza( 'get', 'connect.logitech.com', 'vnd.logitech.connect/vnd.logitech.pair', body, 'guest') iqId = iq.attr('id') xmppClient.send(iq) }) xmppClient.on('error', function (e) { debug('XMPP client error', e) xmppClient.end() deferred.reject(e) }) xmppClient.on('stanza', function (stanza) { debug('received XMPP stanza: ' + stanza) if (stanza.attrs.id === iqId.toString()) { var body = stanza.getChildText('oa') var response = util.decodeColonSeparatedResponse(body) if (response.identity && response.identity !== undefined) { debug('received identity token: ' + response.identity) xmppClient.end() deferred.resolve(response.identity) } else { debug('could not find identity token') xmppClient.end() deferred.reject(new Error('Did not retrieve identity.')) } } }) return deferred.promise } /** PrivateFunction: loginWithIdentity * After fetching an identity from the Harmony hub, this function creates an * XMPP client using that identity. It returns a promise which, when resolved, * passes that XMPP client. * * Parameters: * (String) identity - Identity token to login to the Harmony hub. * (String) hubhost - Hostname/IP of the Harmony hub to connect. * (int) hubport - Optional. Port of the Harmony hub to connect. By default, * this is set to 5222. * * Returns: * (Q.promise) - When resolved, passes the logged in XMPP client, ready to * communicate with the Harmony hub. */ function loginWithIdentity (identity, hubhost, hubport) { debug('create xmpp client using retrieved identity token: ' + identity) var deferred = Q.defer() var jid = identity + '@connect.logitech.com/gatorade' var password = identity var xmppClient = new Client({ jid: jid, password: password, host: hubhost, port: hubport, disallowTLS: true }) xmppClient.on('error', function (e) { debug('XMPP login error', e) xmppClient.end() deferred.reject(e) }) xmppClient.once('online', function () { debug('XMPP client connected using identity token') deferred.resolve(xmppClient) }) return deferred.promise } /** Function: loginToHub * Uses a userAuthToken to login to a Harmony hub. * * Parameters: * (String) userAuthToken - A authentication token, retrieved from logitechs * web service. * (String) hubhost - Hostname/IP of the Harmony hub to connect. * (int) hubport - Optional. Port of the Harmony hub to connect. By default, * this is set to 5222. * * Returns: * (Q.promise) - The final resolved promise will pass a fully authenticated * XMPP client which can be used to communicate with the * Harmony hub. */ function loginToHub (hubhost, hubport) { debug('perform hub login') hubport = hubport || 5222 return getIdentity(hubhost, hubport) .then(function (identity) { return loginWithIdentity(identity, hubhost, hubport) }) } module.exports = loginToHub
swissmanu/harmonyhubjs-client
lib/login/hub.js
JavaScript
mit
4,310
from players.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_2(player): # __INIT__ def __init__(self): player.__init__(self) self.experiences = deque() # CHOOSE NEXT ACTION def act(self, state): return self.calculate(state) # CALCULATE NETWORK def calculate(self, state): size = len( self.experiences ) if size < self.NUM_FRAMES: return self.create_random_action() states = np.zeros( (self.NUM_FRAMES , self.obsv_shape[0], self.obsv_shape[1] ) ) for i , j in enumerate( range( size - self.NUM_FRAMES , size ) ): states[i] = self.experiences[j][1] states = np.expand_dims( states, 0 ) output = np.squeeze( self.brain.run('Output', [['Observation', states]]) ) action = np.random.choice( np.arange(len(output)), p=output ) return self.create_action(action) # PREPARE NETWORK def operations(self): # Action Placeholders self.brain.addInput( shape = [ None , self.num_actions ] , name = 'Actions' ) self.brain.addInput( shape = [ None ] , name = 'Target' ) # Operations self.brain.addOperation( function = tb.ops.pgcost, input = [ 'Output', 'Actions', 'Target' ], name = 'Cost' ) # Optimizer self.brain.addOperation( function = tb.optims.adam, input = 'Cost', learning_rate = self.LEARNING_RATE, name = 'Optimizer' ) # TensorBoard self.brain.addSummaryScalar( input = 'Cost' ) self.brain.addSummaryHistogram( input = 'Target' ) self.brain.addWriter( name = 'Writer' , dir = './' ) self.brain.addSummary( name = 'Summary' ) self.brain.initialize() # TRAIN NETWORK def train(self, prev_state, curr_state, actn, rewd, done, episode): # Store New Experience Until Done self.experiences.append((prev_state, curr_state, actn, rewd, done)) batchsize = len( self.experiences ) - self.NUM_FRAMES + 1 # Check for Train if done: # Select Batch batch = self.experiences # Separate Batch Data prev_states = np.zeros( ( batchsize , self.NUM_FRAMES , self.obsv_shape[0], self.obsv_shape[1] ) ) curr_states = np.zeros( ( batchsize , self.NUM_FRAMES , self.obsv_shape[0], self.obsv_shape[1] ) ) actions = np.zeros( ( batchsize , self.num_actions ) ) rewards = np.zeros( ( batchsize ) ) dones = np.zeros( ( batchsize ) ) # Select Batches for i in range( 0 , batchsize ): for j in range( 0 , self.NUM_FRAMES ): prev_states[i,j,:,:] = self.experiences[ i + j ][0] curr_states[i,j,:,:] = self.experiences[ i + j ][1] actions[i] = self.experiences[ i + self.NUM_FRAMES - 1][2] rewards[i] = self.experiences[ i + self.NUM_FRAMES - 1][3] dones[i] = self.experiences[ i + self.NUM_FRAMES - 1][4] # Calculate Discounted Reward running_add = 0 discounted_r = np.zeros_like(rewards) for t in reversed(range(0, len(rewards))): if rewards[t] != 0: # pygame_catch specific running_add = 0 running_add = running_add * self.REWARD_DISCOUNT + rewards[t] discounted_r[t] = running_add # Optimize Neural Network _, summary = self.brain.run( ['Optimizer','Summary'], [ ['Observation', prev_states ], ['Actions', actions ], ['Target', discounted_r ] ] ) # TensorBoard self.brain.write( summary = summary, iter = episode ) # Reset Batch self.experiences = deque()
NiloFreitas/Deep-Reinforcement-Learning
reinforcement/players/player_reinforce_rnn_2.py
Python
mit
4,361
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.text; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import org.spongepowered.api.scoreboard.Score; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextStyle; import org.spongepowered.api.text.format.TextStyles; import org.spongepowered.api.text.selector.Selector; import org.spongepowered.api.text.translation.Translatable; import org.spongepowered.api.text.translation.Translation; import java.util.Locale; /** * Utility class to work with and create {@link Text}. */ public final class Texts { private static final TextFactory factory = null; static final Text.Literal EMPTY = new Text.Literal(); private Texts() { } /** * Returns an empty, unformatted {@link Text} instance. * * @return An empty text */ public static Text of() { return EMPTY; } /** * Creates a {@link Text} with the specified plain text. The created message * won't have any formatting or events configured. * * @param content The content of the text * @return The created text * @see Text.Literal */ public static Text.Literal of(String content) { if (checkNotNull(content, "content").isEmpty()) { return EMPTY; } return new Text.Literal(content); } /** * Creates a new unformatted {@link Text.Translatable} with the given * {@link Translation} and arguments. * * @param translation The translation for the text * @param args The arguments for the translation * @return The created text * @see Text.Translatable */ public static Text.Translatable of(Translation translation, Object... args) { return new Text.Translatable(translation, ImmutableList.copyOf(checkNotNull(args, "args"))); } /** * Creates a new unformatted {@link Text.Translatable} from the given * {@link Translatable}. * * @param translatable The translatable for the text * @param args The arguments for the translation * @return The created text * @see Text.Translatable */ public static Text.Translatable of(Translatable translatable, Object... args) { return of(checkNotNull(translatable, "translatable").getTranslation(), args); } /** * Creates a new unformatted {@link Text.Selector} with the given selector. * * @param selector The selector for the text * @return The created text * @see Text.Selector */ public static Text.Selector of(Selector selector) { return new Text.Selector(selector); } /** * Creates a new unformatted {@link Text.Score} with the given score. * * @param score The score for the text * @return The created text * @see Text.Score */ public static Text.Score of(Score score) { return new Text.Score(score); } /** * Builds a {@link Text} from a given array of objects. * * <p>For instance, you can use this like * <code>Texts.of(TextColors.DARK_AQUA, "Hi", TextColors.AQUA, "Bye")</code> * </p> * * <p>This will create the correct {@link Text} instance if the input object * is the input for one of the {@link Text} types or convert the object to a * string otherwise.</p> * * @param objects The object array * @return The built text object */ public static Text of(Object... objects) { TextBuilder builder = builder(); TextColor color = TextColors.NONE; TextStyle style = TextStyles.NONE; for (Object obj : objects) { if (obj instanceof TextColor) { color = (TextColor) obj; } else if (obj instanceof TextStyle) { style = obj.equals(TextStyles.RESET) ? TextStyles.NONE : style.and((TextStyle) obj); } else if (obj instanceof Text) { builder.append((Text) obj); } else if (obj instanceof TextBuilder) { builder.append(((TextBuilder) obj).build()); } else { TextBuilder childBuilder; if (obj instanceof String) { childBuilder = Texts.builder((String) obj); } else if (obj instanceof Translation) { childBuilder = Texts.builder((Translation) obj); } else if (obj instanceof Selector) { childBuilder = Texts.builder((Selector) obj); } else if (obj instanceof Score) { childBuilder = Texts.builder((Score) obj); } else { childBuilder = Texts.builder(String.valueOf(obj)); } builder.append(childBuilder.color(color).style(style).build()); } } return builder.build(); } /** * Creates a {@link TextBuilder} with empty text. * * @return A new text builder with empty text */ public static TextBuilder builder() { return new TextBuilder.Literal(); } /** * Creates a new unformatted {@link TextBuilder.Literal} with the specified * content. * * @param content The content of the text * @return The created text builder * @see Text.Literal * @see TextBuilder.Literal */ public static TextBuilder.Literal builder(String content) { return new TextBuilder.Literal(content); } /** * Creates a new {@link TextBuilder.Literal} with the formatting and actions * of the specified {@link Text} and the given content. * * @param text The text to apply the properties from * @param content The content for the text builder * @return The created text builder * @see Text.Literal * @see TextBuilder.Literal */ public static TextBuilder.Literal builder(Text text, String content) { return new TextBuilder.Literal(text, content); } /** * Creates a new unformatted {@link TextBuilder.Translatable} with the given * {@link Translation} and arguments. * * @param translation The translation for the builder * @param args The arguments for the translation * @return The created text builder * @see Text.Translatable * @see TextBuilder.Translatable */ public static TextBuilder.Translatable builder(Translation translation, Object... args) { return new TextBuilder.Translatable(translation, args); } /** * Creates a new unformatted {@link TextBuilder.Translatable} from the given * {@link Translatable}. * * @param translatable The translatable for the builder * @param args The arguments for the translation * @return The created text builder * @see Text.Translatable * @see TextBuilder.Translatable */ public static TextBuilder.Translatable builder(Translatable translatable, Object... args) { return new TextBuilder.Translatable(translatable, args); } /** * Creates a new {@link TextBuilder.Translatable} with the formatting and * actions of the specified {@link Text} and the given {@link Translation} * and arguments. * * @param text The text to apply the properties from * @param translation The translation for the builder * @param args The arguments for the translation * @return The created text builder * @see Text.Translatable * @see TextBuilder.Translatable */ public static TextBuilder.Translatable builder(Text text, Translation translation, Object... args) { return new TextBuilder.Translatable(text, translation, args); } /** * Creates a new {@link TextBuilder.Translatable} with the formatting and * actions of the specified {@link Text} and the given {@link Translatable}. * * @param text The text to apply the properties from * @param translatable The translatable for the builder * @param args The arguments for the translation * @return The created text builder * @see Text.Translatable * @see TextBuilder.Translatable */ public static TextBuilder.Translatable builder(Text text, Translatable translatable, Object... args) { return new TextBuilder.Translatable(text, translatable, args); } /** * Creates a new unformatted {@link TextBuilder.Selector} with the given * selector. * * @param selector The selector for the builder * @return The created text builder * @see Text.Selector * @see TextBuilder.Selector */ public static TextBuilder.Selector builder(Selector selector) { return new TextBuilder.Selector(selector); } /** * Creates a new {@link TextBuilder.Selector} with the formatting and * actions of the specified {@link Text} and the given selector. * * @param text The text to apply the properties from * @param selector The selector for the builder * @return The created text builder * @see Text.Selector * @see TextBuilder.Selector */ public static TextBuilder.Selector builder(Text text, Selector selector) { return new TextBuilder.Selector(text, selector); } /** * Creates a new unformatted {@link TextBuilder.Score} with the given score. * * @param score The score for the text builder * @return The created text builder * @see Text.Score * @see TextBuilder.Score */ public static TextBuilder.Score builder(Score score) { return new TextBuilder.Score(score); } /** * Creates a new {@link TextBuilder.Score} with the formatting and actions * of the specified {@link Text} and the given score. * * @param text The text to apply the properties from * @param score The score for the text builder * @return The created text builder * @see Text.Score * @see TextBuilder.Score */ public static TextBuilder.Score builder(Text text, Score score) { return new TextBuilder.Score(text, score); } /** * Joins a sequence of text objects together. * * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text join(Text... texts) { return builder().append(texts).build(); } /** * Joins a sequence of text objects together. * * @param texts The texts to join * @return A text object that joins the given text objects */ public static Text join(Iterable<? extends Text> texts) { return builder().append(texts).build(); } /** * Joins a sequence of text objects together along with a separator. * * @param separator The separator * @param texts The text to join * @return A text object that joins the given text objects */ public static Text join(Text separator, Text... texts) { switch (texts.length) { case 0: return of(); case 1: return texts[0]; default: TextBuilder builder = builder(); boolean appendSeparator = false; for (Text text : texts) { if (appendSeparator) { builder.append(separator); } else { appendSeparator = true; } builder.append(text); } return builder.build(); } } /** * Parses the specified JSON text and returns the parsed result. * * @param json The valid JSON text * @return The parsed text * @throws IllegalArgumentException If the JSON is invalid */ public static Text parseJson(String json) throws IllegalArgumentException { return factory.parseJson(json); } /** * Parses the specified JSON text and returns the parsed result. * * <p>Unlike {@link #parseJson(String)} this will ignore some formatting * errors and parse the JSON data more leniently.</p> * * @param json The JSON text * @return The parsed text * @throws IllegalArgumentException If the JSON couldn't be parsed */ public static Text parseJsonLenient(String json) throws IllegalArgumentException { return factory.parseJsonLenient(json); } /** * Returns a plain text representation of the {@link Text} without any * formatting. * * @param text The text to convert * @return The text converted to plain text */ public static String toPlain(Text text) { return factory.toPlain(text); } /** * Returns a JSON representation of the {@link Text} as used in commands. * * @param text The text to convert * @return The text converted to JSON */ public static String toJson(Text text) { return factory.toJson(text); } /** * Returns a plain text representation of the {@link Text} without any * formatting. * * @param text The text to convert * @return The text converted to plain text */ public static String toPlain(Text text, Locale locale) { return factory.toPlain(text, locale); } /** * Returns a JSON representation of the {@link Text} as used in commands. * * @param text The text to convert * @return The text converted to JSON */ public static String toJson(Text text, Locale locale) { return factory.toJson(text, locale); } /** * Returns the default legacy formatting character. * * @return The legacy formatting character * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated public static char getLegacyChar() { return factory.getLegacyChar(); } /** * Creates a Message from a legacy string using the default legacy. * * @param text The text to be converted as a String * @return The converted Message * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated @SuppressWarnings("deprecation") public static Text.Literal fromLegacy(String text) { return fromLegacy(text, getLegacyChar()); } /** * Creates a Message from a legacy string, given a color character. * * @param text The text to be converted as a String * @param color The color character to be replaced * @return The converted Message * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated public static Text.Literal fromLegacy(String text, char color) { return factory.parseLegacyMessage(text, color); } /** * Removes the legacy formatting character from a legacy string. * * @param text The legacy text as a String * @return The stripped text * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated @SuppressWarnings("deprecation") public static String stripCodes(String text) { return stripCodes(text, getLegacyChar()); } /** * Removes the legacy formatting character from a legacy string. * * @param text The legacy text as a String * @param color The color character to be replaced * @return The stripped text * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated public static String stripCodes(String text, char color) { return factory.stripLegacyCodes(text, color); } /** * Replaces the given formatting character with the default legacy * formatting character from a legacy string. * * @param text The legacy text as a String * @param from The color character to be replaced * @return The replaced text * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated @SuppressWarnings("deprecation") public static String replaceCodes(String text, char from) { return replaceCodes(text, from, getLegacyChar()); } /** * Replaces the given formatting character with another given formatting * character from a legacy string. * * @param text The legacy text as a String * @param from The color character to be replaced * @param to The color character to replace with * @return The replaced text * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated public static String replaceCodes(String text, char from, char to) { return factory.replaceLegacyCodes(text, from, to); } /** * Returns a representation of the {@link Text} using the legacy color * codes. * * @param text The text to convert * @return The text converted to the old color codes * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated @SuppressWarnings("deprecation") public static String toLegacy(Text text) { return toLegacy(text, getLegacyChar()); } /** * Returns a representation of the {@link Text} using the legacy color * codes. * * @param text The text to convert * @param code The legacy char to use for the message * @return The text converted to the old color codes * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated public static String toLegacy(Text text, char code) { return factory.toLegacy(text, code); } /** * Returns a representation of the {@link Text} using the legacy color * codes. * * @param text The text to convert * @param code The legacy char to use for the message * @param locale The language to return this representation in * @return The text converted to the old color codes * @deprecated Legacy formatting codes are being phased out of Minecraft */ @Deprecated public static String toLegacy(Text text, char code, Locale locale) { return factory.toLegacy(text, code, locale); } }
gabizou/SpongeAPI
src/main/java/org/spongepowered/api/text/Texts.java
Java
mit
19,598
module SupportEngine class SupportType < ActiveRecord::Base attr_accessible :name, :email has_many :tickets, inverse_of: :support_type # TODO: Detect background job def notify!(ticket) SupportEngine::TicketMailer.notify(self, ticket).deliver end end end
orbitalimpact/SupportEngine
app/models/support_engine/support_type.rb
Ruby
mit
286