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
// spin_box.hpp /* neoGFX Resource Compiler Copyright(C) 2019 Leigh Johnston This program is free software: you can redistribute it and / or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <neogfx/neogfx.hpp> #include <neogfx/gui/widget/spin_box.hpp> #include <neogfx/tools/nrc/ui_element.hpp> namespace neogfx::nrc { template <typename T, ui_element_type SpinBoxType> class basic_spin_box : public ui_element<> { public: basic_spin_box(const i_ui_element_parser& aParser, i_ui_element& aParent) : ui_element<>{ aParser, aParent, SpinBoxType } { add_header("neogfx/gui/widget/spin_box.hpp"); add_data_names({ "minimum", "maximum", "step", "value" }); } public: void parse(const neolib::i_string& aName, const data_t& aData) override { ui_element<>::parse(aName, aData); if (aName == "minimum") iMinimum = get_scalar<T>(aData); else if (aName == "maximum") iMaximum = get_scalar<T>(aData); else if (aName == "step") iStep = get_scalar<T>(aData); else if (aName == "value") iValue = get_scalar<T>(aData); } void parse(const neolib::i_string& aName, const array_data_t& aData) override { ui_element<>::parse(aName, aData); } protected: void emit() const override { } void emit_preamble() const override { emit(" %1% %2%;\n", type_name(), id()); ui_element<>::emit_preamble(); } void emit_ctor() const override { ui_element<>::emit_generic_ctor(); ui_element<>::emit_ctor(); } void emit_body() const override { ui_element<>::emit_body(); if (iMinimum) emit(" %1%.set_minimum(%2%);\n", id(), *iMinimum); if (iMaximum) emit(" %1%.set_maximum(%2%);\n", id(), *iMaximum); if (iStep) emit(" %1%.set_step(%2%);\n", id(), *iStep); if (iMinimum) emit(" %1%.set_value(%2%);\n", id(), *iValue); } protected: using ui_element<>::emit; private: neolib::optional<T> iMinimum; neolib::optional<T> iMaximum; neolib::optional<T> iStep; neolib::optional<T> iValue; }; typedef basic_spin_box<int32_t, ui_element_type::SpinBox> spin_box; typedef basic_spin_box<double, ui_element_type::DoubleSpinBox> double_spin_box; }
FlibbleMr/neogfx
tools/nrc/element_libraries/default/src/spin_box.hpp
C++
lgpl-3.0
3,226
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision$ (Revision of last commit) $Date$ (Date of last commit) $Author$ (Author of last commit) ******************************************************************************/ #include "precompiled_game.h" #pragma hdrstop static bool versioned = RegisterVersionedFile( "$Id$" ); #include "Script_Doc_Export.h" #include "../pugixml/pugixml.hpp" namespace { inline void Write( idFile &out, const idStr &str ) { out.Write( str.c_str(), str.Length() ); } inline void Writeln( idFile &out, const idStr &str ) { out.Write( ( str + "\n" ).c_str(), str.Length() + 1 ); } idStr GetEventArgumentString( const idEventDef &ev ) { idStr out; static const char *gen = "abcdefghijklmnopqrstuvwxyz"; int g = 0; const EventArgs &args = ev.GetArgs(); for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) { out += out.IsEmpty() ? "" : ", "; idTypeDef *type = idCompiler::GetTypeForEventArg( i->type ); // Use a generic variable name "a", "b", "c", etc. if no name present out += va( "%s %s", type->Name(), strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() ); } return out; } inline bool EventIsPublic( const idEventDef &ev ) { const char *eventName = ev.GetName(); if( eventName != NULL && ( eventName[0] == '<' || eventName[0] == '_' ) ) { return false; // ignore all event names starting with '<', these mark internal events } const char *argFormat = ev.GetArgFormat(); int numArgs = strlen( argFormat ); // Check if any of the argument types is invalid before allocating anything for( int arg = 0; arg < numArgs; ++arg ) { idTypeDef *argType = idCompiler::GetTypeForEventArg( argFormat[arg] ); if( argType == NULL ) { return false; } } return true; } idList<idTypeInfo *> GetRespondingTypes( const idEventDef &ev ) { idList<idTypeInfo *> tempList; int numTypes = idClass::GetNumTypes(); for( int i = 0; i < numTypes; ++i ) { idTypeInfo *info = idClass::GetType( i ); if( info->RespondsTo( ev ) ) { tempList.Append( info ); } } idList<idTypeInfo *> finalList; // Remove subclasses from the list, only keep top-level nodes for( int i = 0; i < tempList.Num(); ++i ) { bool isSubclass = false; for( int j = 0; j < tempList.Num(); ++j ) { if( i == j ) { continue; } if( tempList[i]->IsType( *tempList[j] ) ) { isSubclass = true; break; } } if( !isSubclass ) { finalList.Append( tempList[i] ); } } return finalList; } int SortTypesByClassname( idTypeInfo *const *a, idTypeInfo *const *b ) { return idStr::Cmp( ( *a )->classname, ( *b )->classname ); } } ScriptEventDocGenerator::ScriptEventDocGenerator() { for( int i = 0; i < idEventDef::NumEventCommands(); ++i ) { const idEventDef *def = idEventDef::GetEventCommand( i ); _events[std::string( def->GetName() )] = def; } time_t timer = time( NULL ); struct tm *t = localtime( &timer ); _dateStr = va( "%04u-%02u-%02u %02u:%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min ); } // --------- D3 Script ----------- idStr ScriptEventDocGeneratorD3Script::GetEventDocumentation( const idEventDef &ev ) { idStr out = "/**\n"; out += " * "; // Format line breaks in the description idStr desc( ev.GetDescription() ); desc.Replace( "\n", "\n * " ); out += desc; const EventArgs &args = ev.GetArgs(); idStr argDesc; for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) { if( idStr::Length( i->desc ) == 0 ) { continue; } // Format line breaks in the description idStr desc( i->desc ); desc.Replace( "\n", "\n * " ); argDesc += va( "\n * @%s: %s", i->name, desc.c_str() ); } if( !argDesc.IsEmpty() ) { out += "\n * "; out += argDesc; } out += "\n */"; return out; } void ScriptEventDocGeneratorD3Script::WriteDoc( idFile &out ) { Write( out, "#ifndef __TDM_EVENTS__\n" ); Write( out, "#define __TDM_EVENTS__\n\n" ); Write( out, "/**\n" ); Write( out, " * The Dark Mod Script Event Documentation\n" ); Write( out, " * \n" ); Write( out, " * This file has been generated automatically by the tdm_gen_script_event_doc console command.\n" ); Write( out, " * Last update: " + _dateStr + "\n" ); Write( out, " */\n" ); Write( out, "\n" ); Write( out, "// ===== THIS FILE ONLY SERVES FOR DOCUMENTATION PURPOSES, IT'S NOT ACTUALLY READ BY THE GAME =======\n" ); Write( out, "// ===== If you want to force this file to be loaded, change the line below to #if 1 ================\n" ); Write( out, "#if 0\n" ); Write( out, "\n" ); Write( out, "\n" ); for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) { const idEventDef &ev = *i->second; if( !EventIsPublic( ev ) ) { continue; } idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev.GetReturnType() ); idStr signature = GetEventArgumentString( ev ); idStr documentation = GetEventDocumentation( ev ); idStr outStr = va( "\n%s\nscriptEvent %s\t\t%s(%s);\n", documentation.c_str(), returnType->Name(), ev.GetName(), signature.c_str() ); Write( out, outStr ); } Write( out, "\n" ); Write( out, "#endif\n" ); Write( out, "\n" ); Write( out, "\n\n#endif\n" ); } // ------------- Mediawiki ------------- idStr ScriptEventDocGeneratorMediaWiki::GetEventDescription( const idEventDef &ev ) { idStr out = ":"; // Format line breaks in the description idStr desc( ev.GetDescription() ); desc.Replace( "\n", " " ); // no artificial line breaks out += desc; out += "\n"; const EventArgs &args = ev.GetArgs(); idStr argDesc; for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) { if( idStr::Length( i->desc ) == 0 ) { continue; } // Format line breaks in the description idStr desc( i->desc ); desc.Replace( "\n", " " ); // no artificial line breaks argDesc += va( "::''%s'': %s\n", i->name, desc.c_str() ); } if( !argDesc.IsEmpty() ) { //out += "\n:"; out += argDesc; } return out; } idStr ScriptEventDocGeneratorMediaWiki::GetEventDoc( const idEventDef *ev, bool includeSpawnclassInfo ) { idStr out; idTypeDef *returnType = idCompiler::GetTypeForEventArg( ev->GetReturnType() ); idStr signature = GetEventArgumentString( *ev ); idStr description = GetEventDescription( *ev ); idStr outStr = va( "==== scriptEvent %s '''%s'''(%s); ====\n", returnType->Name(), ev->GetName(), signature.c_str() ); out += outStr + "\n"; out += description + "\n"; // Get type response info idList<idTypeInfo *> list = GetRespondingTypes( *ev ); list.Sort( SortTypesByClassname ); if( includeSpawnclassInfo ) { idStr typeInfoStr; for( int t = 0; t < list.Num(); ++t ) { idTypeInfo *type = list[t]; typeInfoStr += ( typeInfoStr.IsEmpty() ) ? "" : ", "; typeInfoStr += "''"; typeInfoStr += type->classname; typeInfoStr += "''"; } typeInfoStr = ":Spawnclasses responding to this event: " + typeInfoStr; out += typeInfoStr + "\n"; } return out; } void ScriptEventDocGeneratorMediaWiki::WriteDoc( idFile &out ) { idStr version = va( "%s %d.%02d, code revision %d", GAME_VERSION, TDM_VERSION_MAJOR, TDM_VERSION_MINOR, RevisionTracker::Instance().GetHighestRevision() ); Writeln( out, "This page has been generated automatically by the tdm_gen_script_event_doc console command." ); Writeln( out, "" ); Writeln( out, "Generated by " + version + ", last update: " + _dateStr ); Writeln( out, "" ); Writeln( out, "{{tdm-scripting-reference-intro}}" ); // Table of contents, but don't show level 4 headlines Writeln( out, "<div class=\"toclimit-4\">" ); // SteveL #3740 Writeln( out, "__TOC__" ); Writeln( out, "</div>" ); Writeln( out, "= TDM Script Event Reference =" ); Writeln( out, "" ); Writeln( out, "== All Events ==" ); Writeln( out, "=== Alphabetic List ===" ); // #3740 Two headers are required here for the toclimit to work. We can't skip a heading level. typedef std::vector<const idEventDef *> EventList; typedef std::map<idTypeInfo *, EventList> SpawnclassEventMap; SpawnclassEventMap spawnClassEventMap; for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) { const idEventDef *ev = i->second; if( !EventIsPublic( *ev ) ) { continue; } Write( out, GetEventDoc( ev, true ) ); idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev ); respTypeList.Sort( SortTypesByClassname ); // Collect info for each spawnclass for( int t = 0; t < respTypeList.Num(); ++t ) { idTypeInfo *type = respTypeList[t]; SpawnclassEventMap::iterator typeIter = spawnClassEventMap.find( type ); // Put the event in the class info map if( typeIter == spawnClassEventMap.end() ) { typeIter = spawnClassEventMap.insert( SpawnclassEventMap::value_type( type, EventList() ) ).first; } typeIter->second.push_back( ev ); } } // Write info grouped by class Writeln( out, "" ); Writeln( out, "== Events by Spawnclass / Entity Type ==" ); for( SpawnclassEventMap::const_iterator i = spawnClassEventMap.begin(); i != spawnClassEventMap.end(); ++i ) { Writeln( out, idStr( "=== " ) + i->first->classname + " ===" ); //Writeln(out, "Events:" + idStr(static_cast<int>(i->second.size()))); for( EventList::const_iterator t = i->second.begin(); t != i->second.end(); ++t ) { Write( out, GetEventDoc( *t, false ) ); } } Writeln( out, "[[Category:Scripting]]" ); } // -------- XML ----------- void ScriptEventDocGeneratorXml::WriteDoc( idFile &out ) { pugi::xml_document doc; idStr version = va( "%d.%02d", TDM_VERSION_MAJOR, TDM_VERSION_MINOR ); time_t timer = time( NULL ); struct tm *t = localtime( &timer ); idStr isoDateStr = va( "%04u-%02u-%02u", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday ); pugi::xml_node eventDocNode = doc.append_child( "eventDocumentation" ); pugi::xml_node eventDocVersion = eventDocNode.append_child( "info" ); eventDocVersion.append_attribute( "game" ).set_value( GAME_VERSION ); eventDocVersion.append_attribute( "tdmversion" ).set_value( version.c_str() ); eventDocVersion.append_attribute( "coderevision" ).set_value( RevisionTracker::Instance().GetHighestRevision() ); eventDocVersion.append_attribute( "date" ).set_value( isoDateStr.c_str() ); for( EventMap::const_iterator i = _events.begin(); i != _events.end(); ++i ) { const idEventDef *ev = i->second; if( !EventIsPublic( *ev ) ) { continue; } pugi::xml_node eventNode = eventDocNode.append_child( "event" ); eventNode.append_attribute( "name" ).set_value( ev->GetName() ); // Description pugi::xml_node evDescNode = eventNode.append_child( "description" ); idStr desc( ev->GetDescription() ); desc.Replace( "\n", " " ); // no artificial line breaks evDescNode.append_attribute( "value" ).set_value( desc.c_str() ); // Arguments static const char *gen = "abcdefghijklmnopqrstuvwxyz"; int g = 0; const EventArgs &args = ev->GetArgs(); for( EventArgs::const_iterator i = args.begin(); i != args.end(); ++i ) { idTypeDef *type = idCompiler::GetTypeForEventArg( i->type ); // Use a generic variable name "a", "b", "c", etc. if no name present pugi::xml_node argNode = eventNode.append_child( "argument" ); argNode.append_attribute( "name" ).set_value( strlen( i->name ) > 0 ? i->name : idStr( gen[g++] ).c_str() ); argNode.append_attribute( "type" ).set_value( type->Name() ); idStr desc( i->desc ); desc.Replace( "\n", " " ); // no artificial line breaks argNode.append_attribute( "description" ).set_value( desc.c_str() ); } idList<idTypeInfo *> respTypeList = GetRespondingTypes( *ev ); respTypeList.Sort( SortTypesByClassname ); // Responding Events pugi::xml_node evRespTypesNode = eventNode.append_child( "respondingTypes" ); for( int t = 0; t < respTypeList.Num(); ++t ) { idTypeInfo *type = respTypeList[t]; pugi::xml_node respTypeNode = evRespTypesNode.append_child( "respondingType" ); respTypeNode.append_attribute( "spawnclass" ).set_value( type->classname ); } } std::stringstream stream; doc.save( stream ); out.Write( stream.str().c_str(), stream.str().length() ); }
revelator/The-Darkmod-Experimental
src/game/script/Script_Doc_Export.cpp
C++
lgpl-3.0
12,622
module Spec module Runner class BacktraceTweaker def clean_up_double_slashes(line) line.gsub!('//','/') end end class NoisyBacktraceTweaker < BacktraceTweaker def tweak_backtrace(error) return if error.backtrace.nil? tweaked = error.backtrace.collect do |line| clean_up_double_slashes(line) line end error.set_backtrace(tweaked) end end # Tweaks raised Exceptions to mask noisy (unneeded) parts of the backtrace class QuietBacktraceTweaker < BacktraceTweaker unless defined?(IGNORE_PATTERNS) root_dir = File.expand_path(File.join(__FILE__, '..', '..', '..', '..')) spec_files = Dir["#{root_dir}/lib/*"].map do |path| subpath = path[root_dir.length..-1] /#{subpath}/ end IGNORE_PATTERNS = spec_files + [ /\/lib\/ruby\//, /bin\/spec:/, /bin\/rcov:/, /lib\/rspec-rails/, /vendor\/rails/, # TextMate's Ruby and RSpec plugins /Ruby\.tmbundle\/Support\/tmruby.rb:/, /RSpec\.tmbundle\/Support\/lib/, /temp_textmate\./, /mock_frameworks\/rspec/, /spec_server/ ] end def tweak_backtrace(error) return if error.backtrace.nil? tweaked = error.backtrace.collect do |message| clean_up_double_slashes(message) kept_lines = message.split("\n").select do |line| IGNORE_PATTERNS.each do |ignore| break if line =~ ignore end end kept_lines.empty?? nil : kept_lines.join("\n") end error.set_backtrace(tweaked.select {|line| line}) end end end end
jmecosta/VSSonarQubeQualityEditorPlugin
MSBuild/Gallio/bin/RSpec/libs/rspec-1.2.7/lib/spec/runner/backtrace_tweaker.rb
Ruby
lgpl-3.0
1,816
<!DOCTYPE html> <html lang="es"> <head> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-N4ZZ9MM');</script> <!-- End Google Tag Manager --> <meta charset="iso-8859-1" /> <title>Performance Paris Internet</title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" /> <link rel="stylesheet" type="text/css" href="../../../bootstrap-3.3.6-dist/css/bootstrap.css" /> <link rel="stylesheet" type="text/css" href="../../../bootstrap-select-1.9.4/dist/css/bootstrap-select.css" /> <link rel="stylesheet" type="text/css" href="../../../estilo.css" /> <link rel="shortcut icon" type="image/png" href="../../../paris.png" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="http://code.jquery.com/jquery-latest.js"></script> <!-- analytics --> <script> /*(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-88784345-1', 'auto'); ga('send', 'pageview');*/ function change_date() { var month = document.getElementById("month").value; var year = document.getElementById("year").value; var historicos = document.getElementsByClassName("tipo_venta"); var neg_div = document.getElementById("neg_div").value; var cantidad_historicos = historicos.length; document.getElementById("plan").href = "../../../ingresos/plan/index.php?month=" + month + "&year=" + year; document.getElementById("filtro_depto").href = "../por_departamento/index.php?month=" + month + "&year=" + year + "&depto=601"; document.getElementById("filtro_negocio_division").href = "index.php?month=" + month + "&year=" + year + "&neg_div="+neg_div; document.getElementById("historico").href = "../../../ingresos/historico/index.php?month=" + month + "&year=" + year; document.getElementById("tipo_pago").href = "../../tipo_pago/index.php?month=" + month + "&year=" + year; for (var i = 0; i < cantidad_historicos; i++) historicos[i].href = "../index.php?month=" + month + "&year=" + year; } </script> </head> <body> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-N4ZZ9MM" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <header class="container"> <nav class="navbar navbar-default"> <div class="btn-group-sm"> <div class="row"> <div class="col-md-12"> <h3 class="text-center"><a href="http://10.95.17.114/paneles"><img src="../../../paris.png" width="140px" height="100px"></a> Ingresos por Tipo Venta, <?php if(isset($_GET['neg_div'])) echo " " . $_GET['neg_div']; else echo " VESTUARIO"; ?></h3></div> </div> <div class="row"> <div class="col-lg-6 col-sm-6"> <h5 class="text-center text-success" style="margin-left: 200px;">Última actualización a las <?php date_default_timezone_set("America/Santiago"); $con = new mysqli('localhost', 'root', '', 'ventas'); $query = "select hora from actualizar"; $res = $con->query($query); $hour = 0; while($row = mysqli_fetch_assoc($res)){ $h = $row['hora']; if(strlen($row['hora']) == 1) $h = "00000" . $h; if(strlen($row['hora']) == 2) $h = "0000" . $h; if(strlen($row['hora']) == 3) $h = "000" . $h; if(strlen($row['hora']) == 4) $h = "00" . $h; if(strlen($row['hora']) == 5) $h = "0" . $row['hora']; $h = new DateTime($h); } echo $h->format("H:i") . " horas."; ?></h5></div> <div class="col-lg-6 col-sm-6"> <a class="btn btn-default btn-sm" href="../../../query.php" style="margin-left: 001px;">Query Ventas<img id="txt" src="../../../images.png"></a> </div> </div> <br> <form action="index.php" method="get" class="row"> <div class="col-lg-2"> <div class="dropdown"> <button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Seleccione Reporte <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li class="dropdown-header">Reporte de Ingresos</li> <!-- Link a Panel Plan --> <li><a id="plan" href="../../../ingresos/plan/index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>">Reporte por Plan</a></li> <!-- Link a Panel Historico --> <li><a id="historico" href="../../../ingresos/historico/index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>">Reporte Histórico</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Reporte de Ingresos por Canal</li> <li><a class="tipo_venta" href="../index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>">Reporte Ingresos Tipo Venta</a></li> <li><a id="tipo_pago" href="../../tipo_pago/index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>">Reporte Ingresos Tipo Pago</a></li> <li role="separator" class="divider"></li> <li><a href="#">Reporte de Indicadores</a></li> </ul> </div> </div> <div class="col-lg-1" style="width: 20%;"> <select name="month" id="month" title="Mes" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();"> <?php $meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"); $cant_meses = count($meses); if(isset($_GET['month'])){ $mes = $_GET['month'] - 1; for ($i = 0; $i < $cant_meses; $i++) { $month_number = $i + 1; if (strlen($month_number) < 2) $month_number = "0" . $month_number; if ($mes == $i) echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>"; else echo "<option value='$month_number'>" . $meses[$i] . "</option>"; } }else{ $mes_actual = date("m") - 1; for ($i = 0; $i < $cant_meses; $i++) { $month_number = $i + 1; if (strlen($month_number) < 2) $month_number = "0" . $month_number; if ($mes_actual == $i) echo "<option value='$month_number' selected='selected'>" . $meses[$i] . "</option>"; else echo "<option value='$month_number'>" . $meses[$i] . "</option>"; } } ?> </select> <select name="year" id="year" title="Año" class="selectpicker" data-style="btn btn-default btn-sm" data-width="100px" onchange="change_date();"> <?php $first_year = 2015; $last_year = date("Y"); if(isset($_GET['year'])){ $this_year = $_GET['year']; for ($i = $first_year; $i <= $last_year; $i++) { if ($i == $this_year) echo "<option value='$i' selected='selected'>$i</option>"; else echo "<option value='$i'>$i</option>"; } }else { for ($i = $first_year; $i <= $last_year; $i++) { if ($i == $last_year) echo "<option value='$i' selected='selected'>$i</option>"; else echo "<option value='$i'>$i</option>"; } } ?> </select> </div> <!-- Div para selección de filtro --> <div class="col-lg-2"> <div class="dropdown"> <button class="btn btn-default btn-sm dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Seleccione Filtro <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu2"> <!-- Link a Panel Historico (Sin Filtro) --> <li><a class="tipo_venta" href="../index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>">Sin Filtro</a></li> <!-- Link a Panel Historico --> <li><a id="filtro_depto" href="../por_departamento/index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>&depto=601">Por Departamento</a></li> <li><a id="filtro_negocio_division" href="index.php?month=<?php if(isset($_GET['month'])) echo $_GET['month']; else echo date(" m ");?>&year=<?php if(isset($_GET['year'])) echo $_GET['year']; else echo date("Y ");?>&neg_div=<?php if(isset($_GET['neg_div'])) echo $_GET['neg_div']; else echo "VESTUARIO";?>">Por Negocio / División</a></li> </ul> </div> </div> <div class="col-lg-2" style="width: 20%;"> <select name="neg_div" id="neg_div" class="selectpicker" data-style="btn btn-default btn-sm" onchange="change_date();"> <?php if(isset($_GET['neg_div'])){ $neg_div_selected = $_GET['neg_div']; $query = "select distinct negocio from depto where negocio <> ''"; $res = $con->query($query); echo "<optgroup label='Negocios'>"; while($row = mysqli_fetch_assoc($res)){ $neg_div = $row['negocio']; if($neg_div_selected == $neg_div) echo "<option value='$neg_div' selected='selected'>$neg_div</option>"; else echo "<option value='$neg_div'>$neg_div</option>"; } echo "</optgroup>"; $query = "select distinct division from depto where division <> ''"; $res = $con->query($query); echo "<optgroup label='Divisiones'>"; while($row = mysqli_fetch_assoc($res)){ $neg_div = $row['division']; if($neg_div_selected == $neg_div) echo "<option value='$neg_div' selected='selected'>$neg_div</option>"; else echo "<option value='$neg_div'>$neg_div</option>"; } echo "</optgroup>"; }else{ $query = "select distinct negocio from depto where negocio <> ''"; $res = $con->query($query); $i = 0; echo "<optgroup label='Negocios'>"; while($row = mysqli_fetch_assoc($res)){ $neg_div = $row['negocio']; if($i == 0) echo "<option value='$neg_div' selected='selected'>$neg_div</option>"; else echo "<option value='$neg_div'>$neg_div</option>"; $i++; } echo "</optgroup>"; $query = "select distinct division from depto where division <> ''"; $res = $con->query($query); echo "<optgroup label='Divisiones'>"; while($row = mysqli_fetch_assoc($res)){ $neg_div = $row['division']; if($neg_div_selected == $neg_div) echo "<option value='$neg_div' selected='selected'>$neg_div</option>"; else echo "<option value='$neg_div'>$neg_div</option>"; } echo "</optgroup>"; } ?> </select> </div> <div class="col-lg-1 col-md-1 col-sm-1" style="width: 140px;" id="act"> <button class="btn btn-primary btn-sm" style="width: 100px;">Actualizar</button> </div> </form> </div> </nav> </header> <table class='table table-bordered table-condensed table-hover'> <thead> <tr> <th rowspan="3" style="background: white;"> <h6 class="text-center"><b>Fecha</b></h6></th> <th colspan="15" rowspan="1" style="background-color: #35388E; color: white;"> <h6 class="text-center"><b>Ingresos Tipo de Venta</b></h6></th> </tr> <tr> <th rowspan="1" colspan="3" style="background-color: #E0E1EE;"> <h6 class="text-center"><b>Ingresos Sitio</b></h6></th> <th rowspan="1" colspan="3" style="background-color: #E0E1EE;"> <h6 class="text-center"><b>Ingresos Fonocompras</b></h6></th> <th rowspan="1" colspan="3" style="background-color: #E0E1EE;"> <h6 class="text-center"><b>Empresa</b></h6></th> <th rowspan="1" colspan="3" style="background-color: #E0E1EE;"> <h6 class="text-center"><b>Ingresos Puntos Cencosud</b></h6></th> <th rowspan="1" colspan="3" style="background-color: #E0E1EE;"> <h6 class="text-center"><b>Total</b></h6></th> </tr> <tr> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Actual</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Anterior</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>% R/Past</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Actual</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Anterior</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>% R/Past</b></h6></th> <th style='background-color: #E0E1EE;'> <h6 class="text-center"><b>$ Actual</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Anterior</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>% R/Past</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Actual</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Anterior</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>% R/Past</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Actual</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>$ Anterior</b></h6></th> <th style="background-color: #E0E1EE;"> <h6 class="text-center"><b>% R/Past</b></h6></th> </tr> </thead> <?php require_once '../../paneles.php'; if(isset($_GET['month']) && isset($_GET['year']) && isset($_GET['neg_div'])){ $month = $_GET['month']; $year = $_GET['year']; $neg_div = $_GET['neg_div']; tipo_venta_por_negocio_division($month, $year, $neg_div, $con); }else{ $month = date("m"); $year = date("Y"); $neg_div = 'VESTUARIO'; tipo_venta_por_negocio_division($month, $year, $neg_div, $con); } ?> </table> <script src="../../../bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="../../../bootstrap-select-1.9.4/js/bootstrap-select.js"></script> </body> </html>
parisopr/ventas
ingresos_por_canal/tipo_venta/por_negocio_division/index.php
PHP
unlicense
25,586
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Randomly generates Secret Santa assignments for a given group. * <p> * All valid possible assignments are equally likely to be generated (uniform distribution). * * @author Michael Zaccardo (mzaccardo@aetherworks.com) */ public class SecretSanta { private static final Random random = new Random(); private static final String[] DEFAULT_NAMES = { "Rob", "Ally", "Angus", "Mike", "Shannon", "Greg", "Lewis", "Isabel" }; public static void main(final String[] args) { final String[] names = getNamesToUse(args); final List<Integer> assignments = generateAssignments(names.length); printAssignmentsWithNames(assignments, names); } private static String[] getNamesToUse(final String[] args) { if (args.length >= 2) { return args; } else { System.out.println("Two or more names were not provided -- using default names.\n"); return DEFAULT_NAMES; } } private static List<Integer> generateAssignments(final int size) { final List<Integer> assignments = generateShuffledList(size); while (!areValidAssignments(assignments)) { Collections.shuffle(assignments, random); } return assignments; } private static List<Integer> generateShuffledList(final int size) { final List<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(i); } Collections.shuffle(list, random); return list; } private static boolean areValidAssignments(final List<Integer> assignments) { for (int i = 0; i < assignments.size(); i++) { if (i == assignments.get(i)) { return false; } } return true; } private static void printAssignmentsWithNames(final List<Integer> assignments, final String[] names) { for (int i = 0; i < assignments.size(); i++) { System.out.println(names[i] + " --> " + names[assignments.get(i)]); } } }
AetherWorks/SecretSanta
java/SecretSanta.java
Java
unlicense
2,008
<?php include '../test/connect.php'; $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); if(isset($_GET['query'])) { $query = $_GET['query']; } else { $query = ""; } if(isset($_GET['type'])) { $type = $_GET['type']; } else { $query = "count"; } if($type == "count"){ $sql = mysql_query("SELECT count(gameid) FROM arcade_games WHERE MATCH(shortname, description, title) AGAINST('$query*' IN BOOLEAN MODE)"); $total = mysql_fetch_array($sql); $num = $total[0]; echo $num; } ?> <table width="300px"> <?php if($type == "results"){ $sql = mysql_query("SELECT shortname, title, description FROM arcade_games WHERE MATCH(shortname, title, description) AGAINST('$query*' IN BOOLEAN MODE)"); while($result_ar = mysql_fetch_array($sql)) { $id = $result_ar['gameid']; $squery = sprintf("SELECT * FROM arcade_highscores WHERE gamename = ('%s') ORDER by score DESC", $id); $sresult = mysql_query($squery); $sresult_ar = mysql_fetch_assoc($sresult); $image = $result_ar['stdimage']; $name = $result_ar['shortname']; $file = $result_ar['file']; $width = $result_ar['width']; $height = $result_ar['height']; $champ = $sresult_ar['username']; $cscore = $sresult_ar['score']; ?> <tr> <td><?php echo "<img src='http://www.12daysoffun.com/hustle/arcade/images/$image' />";?></td> <td><?php echo ucwords($name); echo "<br />"; echo"<a href='#' onClick=\"parent.location.href='gamescreen.php?game=$file&amp;width=$width&amp;height=$height'\">PLAY</a>"; ?></td> <td><?php if ($result_ar['gameid'] = $sresult_ar['gamename']){ echo "<b>Champion: </b>"; echo $champ; echo "<br />"; echo "High Score: "; echo $cscore; }else{ $champ = "None"; $cscore = 0; echo "<b>Champion: </b>"; echo "none"; echo "<br />"; echo "High Score: "; echo 0; } ?> </td> </tr> <?php $i+=1; } //while ?> </table> <? } mysql_close($conn); ?>
dvelle/The-hustle-game-on-facebook-c.2010
hustle/hustle/arcade/search.php
PHP
unlicense
2,075
package com.google.gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; class Gson$FutureTypeAdapter<T> extends TypeAdapter<T> { private TypeAdapter<T> delegate; public T read(JsonReader paramJsonReader) { if (this.delegate == null) throw new IllegalStateException(); return this.delegate.read(paramJsonReader); } public void setDelegate(TypeAdapter<T> paramTypeAdapter) { if (this.delegate != null) throw new AssertionError(); this.delegate = paramTypeAdapter; } public void write(JsonWriter paramJsonWriter, T paramT) { if (this.delegate == null) throw new IllegalStateException(); this.delegate.write(paramJsonWriter, paramT); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.google.gson.Gson.FutureTypeAdapter * JD-Core Version: 0.6.0 */
clilystudio/NetBook
allsrc/com/google/gson/Gson$FutureTypeAdapter.java
Java
unlicense
917
<?php class EtendardVideo extends WP_Widget{ private $error = false; private $novideo = false; public function __construct(){ parent::__construct( 'EtendardVideo', __('Etendard - Video', 'etendard'), array('description'=>__('Add a video from Youtube, Dailymotion or Vimeo.', 'etendard')) ); } public function widget($args, $instance){ echo $args['before_widget']; ?> <?php if (isset($instance['title']) && !empty($instance['title'])){ echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title']; } ?> <?php if (isset($instance['video_link']) && $instance['video_link']!=""){ ?> <div class="widget-video"> <?php echo wp_oembed_get($instance['video_link'], array('width'=>287)); ?> </div> <?php }else{ ?> <p><?php _e('To display a video, please add a Youtube, Dailymotion or Vimeo URL in the widget settings.', 'etendard'); ?></p> <?php } ?> <?php echo $args['after_widget']; } public function form($instance){ if ($this->error){ echo '<div class="error">'; _e('Please enter a valid url', 'etendard'); echo '</div>'; } if ($this->novideo){ echo '<div class="error">'; _e('This video url doesn\'t seem to exist.', 'etendard'); echo '</div>'; } $fields = array("title" => "", "video_link" => ""); if ( isset( $instance[ 'title' ] ) ) { $fields['title'] = $instance[ 'title' ]; } if ( isset( $instance[ 'video_link' ] ) ) { $fields['video_link'] = $instance[ 'video_link' ]; } ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:', 'etendard' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $fields['title'] ); ?>"> </p> <p> <label for="<?php echo $this->get_field_id( 'video_link' ); ?>"><?php _e( 'Video URL (Youtube, Dailymotion or Vimeo):', 'etendard' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'video_link' ); ?>" name="<?php echo $this->get_field_name( 'video_link' ); ?>" type="url" value="<?php echo esc_attr( $fields['video_link'] ); ?>"> </p> <?php } public function update($new_instance, $old_instance){ $new_instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; // Check the video link if(isset($new_instance['video_link']) && !empty($new_instance['video_link']) && !filter_var($new_instance['video_link'], FILTER_VALIDATE_URL)){ $new_instance['video_link'] = $old_instance['video_link']; $this->error = true; }else{ if(!wp_oembed_get($new_instance['video_link'])){ $new_instance['video_link'] = $old_instance['video_link']; $this->novideo = true; }else{ $new_instance['video_link'] = ( ! empty( $new_instance['video_link'] ) ) ? strip_tags( $new_instance['video_link'] ) : ''; } } return $new_instance; } } if (!function_exists('etendard_video_widget_init')){ function etendard_video_widget_init(){ register_widget('EtendardVideo'); } } add_action('widgets_init', 'etendard_video_widget_init');
Offirmo/base-wordpress
backupbuddy_backup/wp-content/themes/Etendard/admin/widgets/video.php
PHP
unlicense
3,281
<?php $canon_options_frame = get_option('canon_options_frame'); ?> <div class="outter-wrapper post-footer feature"> <div class="wrapper"> <div class="clearfix"> <div class="foot left"><?php echo $canon_options_frame['footer_text'] ?></div> <div class="foot right"> <?php if ($canon_options_frame['show_social_icons'] == "checked") { get_template_part('inc/templates/header/template_header_element_social'); } ?> </div> </div> </div> </div>
jameymcelveen/com.flyingtigersrc.www
wp-content/themes/sport/inc/templates/footer/template_footer_post.php
PHP
unlicense
841
package com.smartgwt.mobile.client.widgets; import com.google.gwt.resources.client.ImageResource; public abstract class Action { private ImageResource icon; private int iconSize; private String title; private String tooltip; public Action(String title) { this.title = title; } public Action(ImageResource icon) { this.icon = icon; } public Action(String title, ImageResource icon) { this(title); this.icon = icon; } public Action(String title, ImageResource icon, int iconSize) { this(title, icon); this.iconSize = iconSize; } public Action(String title, ImageResource icon, int iconSize, String tooltip) { this(title, icon, iconSize); this.tooltip = tooltip; } public final ImageResource getIcon() { return icon; } public final int getIconSize() { return iconSize; } public final String getTitle() { return title; } public final String getTooltip() { return tooltip; } public abstract void execute(ActionContext context); }
will-gilbert/SmartGWT-Mobile
mobile/src/main/java/com/smartgwt/mobile/client/widgets/Action.java
Java
unlicense
1,126
class Enrollment < ActiveRecord::Base belongs_to :student belongs_to :course end
TSwimson/GA
week4/tue/active_record_associations/college/app/models/enrollment.rb
Ruby
unlicense
85
import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """Not enough money""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print("UNACCEPTABLE! b id:", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw("100") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == "__main__": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s)
SPbAU-ProgrammingParadigms/materials
python_2/common_objects.py
Python
unlicense
4,690
'use strict'; var app = angular.module('App', ['App.controller']);
mirzadelic/django-social-example
django_social_example/django_app/public/js/app/app.js
JavaScript
unlicense
68
/* ********************************************************************** /* * NOTE: This copyright does *not* cover user programs that use Hyperic * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004-2012], VMware, Inc. * This file is part of Hyperic. * * Hyperic is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. 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 General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.tools.ant; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PropertiesFileMergerTask extends Properties{ private static Method saveConvertMethod ; private String fileContent ; private Map<String,String[]> delta ; private boolean isLoaded ; static { try{ saveConvertMethod = Properties.class.getDeclaredMethod("saveConvert", String.class, boolean.class, boolean.class) ; saveConvertMethod.setAccessible(true) ; }catch(Throwable t) { throw (t instanceof RuntimeException ? (RuntimeException) t: new RuntimeException(t)) ; }//EO catch block }//EO static block public PropertiesFileMergerTask() { this.delta = new HashMap<String, String[]>() ; }//EOM @Override public synchronized Object put(Object key, Object value) { Object oPrevious = null ; try{ oPrevious = super.put(key, value); if(this.isLoaded && !value.equals(oPrevious)) this.delta.put(key.toString(), new String[] { value.toString(), (String) oPrevious}) ; return oPrevious ; }catch(Throwable t) { t.printStackTrace() ; throw new RuntimeException(t) ; }//EO catch block }//EOM @Override public final synchronized Object remove(Object key) { final Object oExisting = super.remove(key); this.delta.remove(key) ; return oExisting ; }//EOM public static final PropertiesFileMergerTask load(final File file) throws IOException { InputStream fis = null, fis1 = null ; try{ if(!file.exists()) throw new IOException(file + " does not exist or is not readable") ; //else final PropertiesFileMergerTask properties = new PropertiesFileMergerTask() ; fis = new FileInputStream(file) ; //first read the content into a string final byte[] arrFileContent = new byte[(int)fis.available()] ; fis.read(arrFileContent) ; properties.fileContent = new String(arrFileContent) ; fis1 = new ByteArrayInputStream(arrFileContent) ; properties.load(fis1); // System.out.println(properties.fileContent); return properties ; }catch(Throwable t) { throw (t instanceof IOException ? (IOException)t : new IOException(t)) ; }finally{ if(fis != null) fis.close() ; if(fis1 != null) fis1.close() ; }//EO catch block }//EOM @Override public synchronized void load(InputStream inStream) throws IOException { try{ super.load(inStream); }finally{ this.isLoaded = true ; }//EO catch block }//EOm public final void store(final File outputFile, final String comments) throws IOException { if(this.delta.isEmpty()) return ; FileOutputStream fos = null ; String key = null, value = null ; Pattern pattern = null ; Matcher matcher = null ; String[] arrValues = null; try{ for(Map.Entry<String,String[]> entry : this.delta.entrySet()) { key = (String) saveConvertMethod.invoke(this, entry.getKey(), true/*escapeSpace*/, true /*escUnicode*/); arrValues = entry.getValue() ; value = (String) saveConvertMethod.invoke(this, arrValues[0], false/*escapeSpace*/, true /*escUnicode*/); //if the arrValues[1] == null then this is a new property if(arrValues[1] == null) { this.fileContent = this.fileContent + "\n" + key + "=" + value ; }else { //pattern = Pattern.compile(key+"\\s*=(\\s*.*\\s*)"+ arrValues[1].replaceAll("\\s+", "(\\\\s*.*\\\\s*)") , Pattern.MULTILINE) ; pattern = Pattern.compile(key+"\\s*=.*\n", Pattern.MULTILINE) ; matcher = pattern.matcher(this.fileContent) ; this.fileContent = matcher.replaceAll(key + "=" + value) ; }//EO else if existing property System.out.println("Adding/Replacing " + key + "-->" + arrValues[1] + " with: " + value) ; }//EO while there are more entries ; fos = new FileOutputStream(outputFile) ; fos.write(this.fileContent.getBytes()) ; }catch(Throwable t) { throw (t instanceof IOException ? (IOException)t : new IOException(t)) ; }finally{ if(fos != null) { fos.flush() ; fos.close() ; }//EO if bw was initialized }//EO catch block }//EOM public static void main(String[] args) throws Throwable { ///FOR DEBUG String s = " 1 2 4 sdf \\\\\nsdfsd" ; final Pattern pattern = Pattern.compile("test.prop2\\s*=.*(?:\\\\?\\s*)(\n)" , Pattern.MULTILINE) ; final Matcher matcher = pattern.matcher("test.prop2="+s) ; System.out.println(matcher.replaceAll("test.prop2=" + "newvalue$1")) ; ///FOR DEBUG if(true) return ; final String path = "/tmp/confs/hq-server-46.conf" ; final File file = new File(path) ; final PropertiesFileMergerTask properties = PropertiesFileMergerTask.load(file) ; /* final Pattern pattern = Pattern.compile("test.prop1\\s*=this(\\s*.*\\s*)is(\\s*.*\\s*)the(\\s*.*\\s*)value" , Pattern.MULTILINE) ; final Matcher matcher = pattern.matcher(properties.fileContent) ; System.out.println( matcher.replaceAll("test.prop1=new value") ) ; System.out.println("\n\n--> " + properties.get("test.prop1")) ;*/ final String overridingConfPath = "/tmp/confs/hq-server-5.conf" ; //final Properties overrdingProperties = new Properties() ; final FileInputStream fis = new FileInputStream(overridingConfPath) ; properties.load(fis) ; fis.close() ; ///properties.putAll(overrdingProperties) ; final String outputPath = "/tmp/confs/output-hq-server.conf" ; final File outputFile = new File(outputPath) ; final String comments = "" ; properties.store(outputFile, comments) ; }//EOM }//EOC
cc14514/hq6
hq-installer/src/main/java/org/hyperic/tools/ant/PropertiesFileMergerTask.java
Java
unlicense
8,153
package com.sochat.client; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PublicKey; import java.security.spec.RSAPublicKeySpec; public class ServerPublicKey { public static PublicKey getServerPublicKey(String publicKeyModulus, String publicKeyExponent) throws GeneralSecurityException { BigInteger modulus = new BigInteger(publicKeyModulus, 16); BigInteger exponent = new BigInteger(publicKeyExponent, 16); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(pubKeySpec); } }
ovaskevich/sochat
src/com/sochat/client/ServerPublicKey.java
Java
unlicense
732
package main type FluxConfig struct { Iam string `toml:"iam"` Url string `toml:"url"` Port int `toml:"port"` Logdir string `toml:"logdir"` Balancer FluxCluster `toml:"cluster"` //Jwts []JwtAuth `toml:"jwt"` } type JwtAuth struct { RequiredClaims []JwtClaim `toml:"claim"` DecryptionSecret string `toml:"secret"` } type JwtClaim struct { Key string `toml:"key"` Value string `toml:"value"` } type FluxCluster struct { Name string `toml:"name"` BalancerAddress string `toml:"address"` BalancerPort int `toml:"port"` Scramble bool `toml:"scramble"` }
zerocruft/flux
config.go
GO
unlicense
645
using UnityEngine; using System.Collections; using System.Collections.Generic; using BeatManagement; public class InitialBuildingEntryAnimation : Task { private TaskManager subtaskManager; private float baseStaggerTime; private float structStaggerTime; private float terrainStaggerTime; private bool run_tasks = false; protected override void Init() { baseStaggerTime = Services.Clock.EighthLength(); structStaggerTime = Services.Clock.SixteenthLength(); terrainStaggerTime = Services.Clock.ThirtySecondLength(); subtaskManager = new TaskManager(); for (int i = 0; i < 2; i++) { Task dropTask = new Wait(baseStaggerTime * i); dropTask.Then(new BuildingDropAnimation(Services.GameManager.Players[i].mainBase)); subtaskManager.Do(dropTask); } for (int i = 0; i < Services.MapManager.structuresOnMap.Count; i++) { Task dropTask = new Wait((structStaggerTime * i) + (baseStaggerTime * 2)); dropTask.Then(new BuildingDropAnimation(Services.MapManager.structuresOnMap[i])); subtaskManager.Do(dropTask); } for (int i = 0; i < Services.MapManager.terrainOnMap.Count; i++) { Task dropTask = new Wait((terrainStaggerTime * i) + (baseStaggerTime * 2)); dropTask.Then(new BuildingDropAnimation(Services.MapManager.terrainOnMap[i])); subtaskManager.Do(dropTask); } // Task waitTask = new Wait((structStaggerTime * Services.MapManager.structuresOnMap.Count) + (baseStaggerTime * 2)); // waitTask.Then(new ActionTask(() => { SetStatus(TaskStatus.Success); })); //subtaskManager.Do(waitTask); Services.Clock.SyncFunction(() => { run_tasks = true; }, Clock.BeatValue.Quarter); } internal override void Update() { if (run_tasks) { subtaskManager.Update(); if (subtaskManager.tasksInProcessCount == 0) SetStatus(TaskStatus.Success); } } }
chrsjwilliams/RTS_Blokus
Assets/Scripts/Pieces/Tasks/InitialBuildingEntryAnimation.cs
C#
unlicense
2,097
// https://github.com/KubaO/stackoverflown/tree/master/questions/html-get-24965972 #include <QtNetwork> #include <functional> void htmlGet(const QUrl &url, const std::function<void(const QString&)> &fun) { QScopedPointer<QNetworkAccessManager> manager(new QNetworkAccessManager); QNetworkReply *response = manager->get(QNetworkRequest(QUrl(url))); QObject::connect(response, &QNetworkReply::finished, [response, fun]{ response->deleteLater(); response->manager()->deleteLater(); if (response->error() != QNetworkReply::NoError) return; auto const contentType = response->header(QNetworkRequest::ContentTypeHeader).toString(); static QRegularExpression re("charset=([!-~]+)"); auto const match = re.match(contentType); if (!match.hasMatch() || 0 != match.captured(1).compare("utf-8", Qt::CaseInsensitive)) { qWarning() << "Content charsets other than utf-8 are not implemented yet:" << contentType; return; } auto const html = QString::fromUtf8(response->readAll()); fun(html); // do something with the data }) && manager.take(); } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); htmlGet({"http://www.google.com"}, [](const QString &body){ qDebug() << body; qApp->quit(); }); return app.exec(); }
KubaO/stackoverflown
questions/html-get-24965972/main.cpp
C++
unlicense
1,330
using System; using System.Collections.Generic; using System.Linq; namespace NetGore { /// <summary> /// Provides helper functions for parsing command-line switches and the arguments that go with /// each of those switches. /// </summary> public static class CommandLineSwitchHelper { /// <summary> /// The name of the primary key. This is the key used for arguments that come before any switches. /// This key is only present if it has any arguments. /// </summary> public const string PrimaryKeyName = "Main"; /// <summary> /// The prefix used to denote a switch. Any word after a word with this prefix that does not /// have this prefix will be considered as an argument to the switch. For example: /// -switch1 arg1 arg2 -switch2 -switch3 arg1 /// </summary> public const string SwitchPrefix = "-"; /// <summary> /// Gets the switches and their arguments from the given string array. /// </summary> /// <param name="args">The array of strings.</param> /// <returns>The switches and their arguments from the given string array.</returns> public static IEnumerable<KeyValuePair<string, string[]>> GetCommands(string[] args) { return GroupValuesToSwitches(args); } /// <summary> /// Gets the switches and their arguments from the given string array. Only switches that can be parsed to /// type <typeparamref name="T"/> will be returned. /// </summary> /// <typeparam name="T">The Type of Enum to use as the key.</typeparam> /// <param name="args">The array of strings.</param> /// <returns>The switches and their arguments from the given string array.</returns> /// <exception cref="MethodAccessException">Generic type <typeparamref name="T"/> must be an Enum.</exception> public static IEnumerable<KeyValuePair<T, string[]>> GetCommandsUsingEnum<T>(string[] args) where T : struct, IComparable, IConvertible, IFormattable { if (!typeof(T).IsEnum) { const string errmsg = "Generic type T (type: {0}) must be an Enum."; throw new MethodAccessException(string.Format(errmsg, typeof(T))); } var items = GetCommands(args); foreach (var item in items) { T parsed; if (EnumHelper<T>.TryParse(item.Key, true, out parsed)) yield return new KeyValuePair<T, string[]>(parsed, item.Value); } } /// <summary> /// Groups the values after a switch to a switch. /// </summary> /// <param name="args">The array of strings.</param> /// <returns>The switches grouped with their values.</returns> static IEnumerable<KeyValuePair<string, string[]>> GroupValuesToSwitches(IList<string> args) { if (args == null || args.Count == 0) return Enumerable.Empty<KeyValuePair<string, string[]>>(); var switchPrefixAsCharArray = SwitchPrefix.ToCharArray(); var ret = new List<KeyValuePair<string, string[]>>(args.Count); var currentKey = PrimaryKeyName; var currentArgs = new List<string>(args.Count); // Iterate through all the strings for (var i = 0; i < args.Count; i++) { var currentArg = args[i]; var currentArgTrimmed = args[i].Trim(); if (currentArgTrimmed.StartsWith(SwitchPrefix, StringComparison.OrdinalIgnoreCase)) { // Empty out the current switch if (currentKey != PrimaryKeyName || currentArgs.Count > 0) ret.Add(new KeyValuePair<string, string[]>(currentKey, currentArgs.ToArray())); // Remove the switch prefix and set as the new key currentKey = currentArgTrimmed.TrimStart(switchPrefixAsCharArray); currentArgs.Clear(); } else { // Add the argument only if its an actual string if (currentArg.Length > 0) currentArgs.Add(currentArg); } } // Empty out the remainder if (currentKey != PrimaryKeyName || currentArgs.Count > 0) ret.Add(new KeyValuePair<string, string[]>(currentKey, currentArgs.ToArray())); return ret; } } }
LAGIdiot/NetGore
NetGore/Core/CommandLineSwitchHelper.cs
C#
unlicense
4,642
package com.elionhaxhi.ribbit.ui; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.elionhaxhi.ribbit.R; import com.elionhaxhi.ribbit.adapters.UserAdapter; import com.elionhaxhi.ribbit.utils.FileHelper; import com.elionhaxhi.ribbit.utils.ParseConstants; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseInstallation; import com.parse.ParseObject; import com.parse.ParsePush; import com.parse.ParseQuery; import com.parse.ParseRelation; import com.parse.ParseUser; import com.parse.SaveCallback; public class RecipientsActivity extends Activity { public static final String TAG=RecipientsActivity.class.getSimpleName(); protected List<ParseUser> mFriends; protected ParseRelation<ParseUser> mFriendsRelation; protected ParseUser mCurrentUser; protected MenuItem mSendMenuItem; protected Uri mMediaUri; protected String mFileType; protected GridView mGridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.user_grid); //setupActionBar(); mGridView =(GridView)findViewById(R.id.friendsGrid); mGridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mGridView.setOnItemClickListener(mOnItemClickListener); TextView emptyTextView = (TextView)findViewById(android.R.id.empty); mGridView.setEmptyView(emptyTextView); mMediaUri = getIntent().getData(); mFileType = getIntent().getExtras().getString(ParseConstants.KEY_FILE_TYPE); } @Override public void onResume(){ super.onResume(); mCurrentUser = ParseUser.getCurrentUser(); mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION); setProgressBarIndeterminateVisibility(true); ParseQuery<ParseUser> query = mFriendsRelation.getQuery(); query.addAscendingOrder(ParseConstants.KEY_USERNAME); query.findInBackground(new FindCallback<ParseUser>(){ @Override public void done(List<ParseUser> friends, ParseException e){ setProgressBarIndeterminateVisibility(false); if(e == null){ mFriends = friends; String [] usernames = new String[mFriends.size()]; int i =0; for(ParseUser user : mFriends){ usernames[i]=user.getUsername(); i++; } if(mGridView.getAdapter() == null){ UserAdapter adapter = new UserAdapter(RecipientsActivity.this, mFriends); mGridView.setAdapter(adapter); } else{ ((UserAdapter)mGridView.getAdapter()).refill(mFriends); } } else{ Log.e(TAG, e.getMessage()); AlertDialog.Builder builder= new AlertDialog.Builder(RecipientsActivity.this); builder.setMessage(e.getMessage()) .setTitle(R.string.error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.reciptient, menu); mSendMenuItem = menu.getItem(0); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch(item.getItemId()){ case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_send: ParseObject message = createMessage(); if(message == null){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.error_selecting_file) .setTitle(R.string.error_selection_file_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } else { send(message); finish(); } return true; } return super.onOptionsItemSelected(item); } protected ParseObject createMessage(){ ParseObject message = new ParseObject(ParseConstants.CLASS_MESSAGE); message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId()); message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername()); message.put(ParseConstants.KEY_RECIPIENT_IDS, getRecipientIds()); message.put(ParseConstants.KEY_FILE_TYPE, mFileType); byte[] fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri); if(fileBytes == null){ return null; } else{ if(mFileType.equalsIgnoreCase(ParseConstants.TYPE_IMAGE)){ fileBytes = FileHelper.reduceImageForUpload(fileBytes); } String fileName = FileHelper.getFileName(this, mMediaUri, mFileType); ParseFile file = new ParseFile(fileName, fileBytes); message.put(ParseConstants.KEY_FILE, file); return message; } } protected ArrayList<String> getRecipientIds(){ ArrayList<String> recipientIds = new ArrayList<String>(); for(int i=0; i< mGridView.getCount(); i++){ if(mGridView.isItemChecked(i)){ recipientIds.add(mFriends.get(i).getObjectId()); } } return recipientIds; } protected void send(ParseObject message){ message.saveInBackground(new SaveCallback(){ @Override public void done(ParseException e){ if(e == null){ //success Toast.makeText(RecipientsActivity.this, R.string.success_message, Toast.LENGTH_LONG).show(); sendPushNotifications(); } else{ AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this); builder.setMessage(R.string.error_sending_message) .setTitle(R.string.error_selection_file_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); } protected OnItemClickListener mOnItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(mGridView.getCheckedItemCount() > 0) { mSendMenuItem.setVisible(true); } else{ mSendMenuItem.setVisible(false); } ImageView checkImageView =(ImageView)findViewById(R.id.checkImageView); if(mGridView.isItemChecked(position)){ //add recipient checkImageView.setVisibility(View.VISIBLE); } else{ //remove the recipient checkImageView.setVisibility(View.INVISIBLE); } } }; protected void sendPushNotifications(){ ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.whereContainedIn(ParseConstants.KEY_USER_ID, getRecipientIds()); //send a push notificaton ParsePush push = new ParsePush(); push.setQuery(query); push.setMessage(getString(R.string.push_message, ParseUser.getCurrentUser().getUsername())); push.sendInBackground(); } }
ElionHaxhi/Ribbit
src/com/elionhaxhi/ribbit/ui/RecipientsActivity.java
Java
unlicense
7,505
<?php /** * Pizza E96 * * @author: Paul Melekhov */ namespace App\Http; /** * Поднятие этого исключения служит сигналом для FrontController о том, * что нужно отобразить страницу с ошибкой HTTP/1.1 400 Bad Request */ class BadRequestException extends Exception { public function __construct($message = "", $code = 0, Exception $previous = null) { parent::__construct($message, $code, $previous); $this->_httpStatusCode = 400; $this->_httpStatusMessage = "Bad Request"; } }
gugglegum/pizza
app/library/Http/BadRequestException.php
PHP
unlicense
592
class PermissionRequired(Exception): """ Exception to be thrown by views which check permissions internally. Takes a single C{perm} argument which defines the permission that caused the exception. """ def __init__(self, perm): self.perm = perm def require_permissions(user, *permissions): for perm in permissions: if not user.has_perm(perm): raise PermissionRequired(perm) class checks_permissions(object): """ Decorator for views which handle C{PermissionRequired} errors and renders the given error view if necessary. The original request and arguments are passed to the error with the additional C{_perm} and C{_view} keyword arguments. """ def __init__(self, view_or_error=None): self.wrapped = callable(view_or_error) error_view = None if self.wrapped: self.view = view_or_error else: error_view = view_or_error if not error_view: from django.conf import settings error_view = settings.PERMISSIONS_VIEW from django.core.urlresolvers import get_callable self.error_view = get_callable(error_view) def __call__(self, view_or_request, *args, **kwargs): if not self.wrapped: self.view = view_or_request def dec(*args, **kwargs): try: return self.view(*args, **kwargs) except PermissionRequired as e: kwargs['_perm'] = e.perm kwargs['_view'] = self.view return self.error_view(*args, **kwargs) return dec(view_or_request, *args, **kwargs) if self.wrapped else dec class permission_required(object): """ Decorator which builds upon the C{checks_permission} decorator to offer the same functionality as the built-in C{django.contrib.auth.decorators.permission_required} decorator but which renders an error view insted of redirecting to the login page. """ def __init__(self, perm, error_view=None): self.perm = perm self.error_view = error_view def __call__(self, view_func): def decorator(request, *args, **kwargs): if not request.user.has_perm(self.perm): raise PermissionRequired(self.perm) return view_func(request, *args, **kwargs) return checks_permissions(self.error_view)(decorator)
AnimeDB/adb-browser-frontend
adb/frontend/auth/decorators.py
Python
unlicense
2,476
package com.intershop.adapter.payment.partnerpay.internal.service.capture; import javax.inject.Inject; import com.google.inject.Injector; import com.intershop.adapter.payment.partnerpay.capi.service.capture.CaptureFactory; import com.intershop.api.service.payment.v1.capability.Capture; public class CaptureFactoryImpl implements CaptureFactory { @Inject private Injector injector; @Override public Capture createCapture() { Capture ret = new CaptureImpl(); injector.injectMembers(ret); return ret; } }
IntershopCommunicationsAG/partnerpay-example
s_payment_partnerpay/ac_payment_partnerpay/javasource/com/intershop/adapter/payment/partnerpay/internal/service/capture/CaptureFactoryImpl.java
Java
unlicense
578
// This Source Code is in the Public Domain per: http://unlicense.org package org.litesoft.commonfoundation.charstreams; /** * A CharSource is like a powerful version of a "char" based Iterator. */ public interface CharSource { /** * Report if there are any more characters available to get(). * <p/> * Similar to Iterator's hasNext(). */ public boolean anyRemaining(); /** * Get the next character (consume it from the stream) or -1 if there are no more characters available. */ public int get(); /** * Get the next character (consume it from the stream) or throw an exception if there are no more characters available. */ public char getRequired(); /** * Return the next character (without consuming it) or -1 if there are no more characters available. */ public int peek(); /** * Return the Next Offset (from the stream) that the peek/get/getRequired would read from (it may be beyond the stream end). */ public int getNextOffset(); /** * Return the Last Offset (from the stream), which the previous get/getRequired read from (it may be -1 if stream has not been successfully read from). */ public int getLastOffset(); /** * Return a string (and consume the characters) from the current position up to (but not including) the position of the 'c' character. OR "" if 'c' is not found (nothing consumed). */ public String getUpTo( char c ); /** * Consume all the spaces (NOT white space) until either there are no more characters or a non space is encountered (NOT consumed). * * @return true if there are more characters. */ public boolean consumeSpaces(); /** * Return a string (and consume the characters) from the current position thru the end of the characters OR up to (but not including) a character that is not a visible 7-bit ascii character (' ' < c <= 126). */ public String getUpToNonVisible7BitAscii(); /** * Consume all the non-visible 7-bit ascii characters (visible c == ' ' < c <= 126) until either there are no more characters or a visible 7-bit ascii character is encountered (NOT consumed). * * @return true if there are more characters. */ public boolean consumeNonVisible7BitAscii(); }
litesoft/LiteSoftCommonFoundation
src/org/litesoft/commonfoundation/charstreams/CharSource.java
Java
unlicense
2,332
package net.simpvp.Jail; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import org.bukkit.Location; /** * Class representing the stored information about a jailed player */ public class JailedPlayer { public UUID uuid; public String playername; public String reason; public String jailer; public Location location; public int jailed_time; public boolean to_be_released; public boolean online; public JailedPlayer(UUID uuid, String playername, String reason, String jailer, Location location, int jailed_time, boolean to_be_released, boolean online) { this.uuid = uuid; this.playername = playername; this.reason = reason; this.jailer = jailer; this.location = location; this.jailed_time = jailed_time; this.to_be_released = to_be_released; this.online = online; } public void add() { Jail.jailed_players.add(this.uuid); } public void insert() { SQLite.insert_player_info(this); } public int get_to_be_released() { int ret = 0; if (this.to_be_released) ret ^= 1; if (!this.online) ret ^= 2; return ret; } /** * Returns a text description of this jailed player. */ public String get_info() { SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, H:m:s"); String msg = this.playername + " (" + this.uuid + ")" + " was jailed on " + sdf.format(new Date(this.jailed_time * 1000L)) + " by " + this.jailer + " for" + this.reason + "."; if (this.to_be_released) { msg += "\nThis player is set to be released"; } return msg; } }
C4K3/Jail
src/main/java/net/simpvp/Jail/JailedPlayer.java
Java
unlicense
1,551
/* * NOTE: This copyright does *not* cover user programs that use HQ * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * This file is part of HQ. * * HQ is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. 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 General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.hq.ui.action.portlet.autoDisc; import org.hyperic.hq.appdef.shared.AIPlatformValue; import org.hyperic.hq.autoinventory.ScanStateCore; import org.hyperic.hq.autoinventory.ScanMethodState; public class AIPlatformWithStatus extends AIPlatformValue { private ScanStateCore state = null; public AIPlatformWithStatus(AIPlatformValue aip, ScanStateCore state) { super(aip); this.state = state; } public boolean getIsAgentReachable() { return state != null; } public boolean getIsScanning() { return state != null && !state.getIsDone(); } public String getStatus() { if (state == null) return "Agent is not responding"; if (state.getGlobalException() != null) { return state.getGlobalException().getMessage(); } ScanMethodState[] methstates = state.getScanMethodStates(); String rval = ""; String status; for (int i = 0; i < methstates.length; i++) { status = methstates[i].getStatus(); if (status != null) rval += status.trim(); } rval = rval.trim(); if (rval.length() == 0) { rval = "Scan starting..."; } return rval; } }
cc14514/hq6
hq-web/src/main/java/org/hyperic/hq/ui/action/portlet/autoDisc/AIPlatformWithStatus.java
Java
unlicense
2,391
#ifndef HAVE_spiral_io_hpp #define HAVE_spiral_io_hpp #include <cstdio> #include "spiral/core.hpp" #include "spiral/string.hpp" namespace spiral { struct IoObj { const ObjTable* otable; std::FILE* stdio; bool close_on_drop; }; auto io_from_val(Bg* bg, Val val) -> IoObj*; auto io_from_obj_ptr(void* obj_ptr) -> IoObj*; auto io_new_from_stdio(Bg* bg, void* sp, std::FILE* stdio, bool close_on_drop) -> IoObj*; void io_stringify(Bg* bg, Buffer* buf, void* obj_ptr); auto io_length(void* obj_ptr) -> uint32_t; auto io_evacuate(GcCtx* gc_ctx, void* obj_ptr) -> Val; void io_scavenge(GcCtx* gc_ctx, void* obj_ptr); void io_drop(Bg* bg, void* obj_ptr); auto io_eqv(Bg* bg, void* l_ptr, void* r_ptr) -> bool; extern const ObjTable io_otable; auto io_open_file(Bg* bg, void* sp, StrObj* path, const char* mode) -> Val; extern "C" { auto spiral_std_io_file_open(Bg* bg, void* sp, uint32_t path) -> uint32_t; auto spiral_std_io_file_create(Bg* bg, void* sp, uint32_t path) -> uint32_t; auto spiral_std_io_file_append(Bg* bg, void* sp, uint32_t path) -> uint32_t; auto spiral_std_io_close(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_flush(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_is_io(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_is_eof(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_is_error(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_stdin(Bg* bg, void* sp) -> uint32_t; auto spiral_std_io_stdout(Bg* bg, void* sp) -> uint32_t; auto spiral_std_io_stderr(Bg* bg, void* sp) -> uint32_t; auto spiral_std_io_write_byte(Bg* bg, void* sp, uint32_t io, uint32_t byte) -> uint32_t; auto spiral_std_io_write(Bg* bg, void* sp, uint32_t io, uint32_t str) -> uint32_t; auto spiral_std_io_write_line(Bg* bg, void* sp, uint32_t io, uint32_t str) -> uint32_t; auto spiral_std_io_read_byte(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_read_str(Bg* bg, void* sp, uint32_t io, uint32_t len) -> uint32_t; auto spiral_std_io_read_all_str(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_read_line(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_read_word(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_read_int(Bg* bg, void* sp, uint32_t io) -> uint32_t; auto spiral_std_io_read_number(Bg* bg, void* sp, uint32_t io) -> uint32_t; } } #endif
honzasp/spiral
rt/include/spiral/io.hpp
C++
unlicense
2,505
package generics.p19; import java.util.Random; import utils.Generator; public class Good { private final int id; private String description; public Good(int id, String description) { this.id = id; this.description = description; } public static Generator<Good> generator = new Generator<Good>() { Random random = new Random(); @Override public Good next() { return new Good(random.nextInt(1000), ""); } }; @Override public String toString() { return "Good: " + id + " " + description; } }
bodydomelight/tij-problems
src/generics/p19/Good.java
Java
unlicense
619
var Theme = (function() { var Theme = function() { }; return Theme; })(); module.exports = Theme;
frostney/dropoff
lib/theme/index.js
JavaScript
unlicense
119
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 15:55:28 2013 @author: dyanna """ import numpy as np from sklearn.svm import SVC def getSample(pointA, pointB, numberOfPoints): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList]) y = sample[:,2] breakpoint = False while not breakpoint: if(len(y[y==-1]) == 0 or len(y[y==1]) == 0): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList]) y = sample[:,2] else: breakpoint = True return sample def getRandomLine(): return list(zip(np.random.uniform(-1,1.00,2),np.random.uniform(-1,1.00,2))) def getPoints(numberOfPoints): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) return pointList def isLeft(a, b, c): return 1 if ((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0])) > 0 else -1; def sign(x): return 1 if x > 0 else -1 def getMisMatchesQP(data, clf): #print(data) data_x = np.c_[data[:,0], data[:,1]] results = clf.predict(data_x) #print(np.sign(results)) print("mismatch ", float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data)) print("score ", clf.score(data_x, data[:,2])) return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data) def doMonteCarloQP(pointa, pointb, clf, nopoint): #print "weights ", weight points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)] #print points dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points]) #print dataset_Monte return getMisMatchesQP(dataset_Monte, clf) def doPLA(sample): w = np.array([0,0,0]) iteration = 0 it = 0 while True:#(it < 10): iteration = iteration + 1 it = it + 1 mismatch = list() for i in sample: #print("point in question ", i , " weight ", w) yy = w[0] + w[1] * i[0] + w[2] * i[1] #print("this is after applying weight to a point ",yy) point = [i[0], i[1], sign(yy)] if any(np.equal(sample, point).all(1)): #print "point not in sample" if(point[2] == -1): mismatch.append((1, (i[0]), (i[1]))) else: mismatch.append((-1, -(i[0]), -(i[1]))) #print " length ", len(mismatch), " mismatch list ",mismatch if(len(mismatch) > 0): #find a random point and update w choiceIndex = np.random.randint(0, len(mismatch)) choice = mismatch[choiceIndex] #print("choice ", choice) w = w + choice #print "new weight ", w else: break #print("this is the iteration ", iteration) #print("this is the weight ", w) #montelist = [monetcarlo((x1,y1),(x2,y2),w,10000) for i in range(5)] #print("Montelist " , montelist) #monteavg = sum([i for i in montelist])/10 return w, iteration def getMisMatches(data, weights): #print data list1 = np.empty(len(data)) list1.fill(weights[0]) results = list1+ weights[1]*data[:,0]+weights[2]*data[:,1] results = -1 * results return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data) def doMonteCarloNP(pointa, pointb, weights, nopoint): #print "weights ", weight points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)] #print points dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points]) #print dataset_Monte return getMisMatches(dataset_Monte, weights) if __name__ == "__main__": '''X = np.array([[-1,-1],[-2,-1], [1,1], [2,1]]) y = np.array([1,1,2,2]) clf = SVC() clf.fit(X,y) print(clf.predict([[-0.8,-1]]))''' #clf = SVC() clf = SVC(C = 1000, kernel = 'linear') monteavgavgQP = list() monteavgavgPLA = list() approxavgQP = list() vectornumberavg = list() predictavg = list() for j in range(1): #clf = SVC(C = 1000, kernel = 'linear') monteavgQP = list() monteavgPLA = list() approxQP = list() vectoravg = list() for k in range(1000): nopoints = 100 line = getRandomLine() sample = getSample(line[0], line[1], nopoints) #print(sample) X = np.c_[sample[:,0], sample[:,1]] y = sample[:,2] #print(y) clf.fit(X,y) #print(clf.score(X,y)) w, it = doPLA(sample) #print(len(clf.support_vectors_)) #print(clf.support_vectors_) #print(clf.support_) vectoravg.append(len(clf.support_vectors_)) #print(clf.predict(clf.support_vectors_)==1) #print(clf.predict(clf.support_vectors_)) #print(clf.coef_) montelistQP = [doMonteCarloQP(line[0], line[1], clf, 500) for i in range(1)] qpMonte = sum(montelistQP)/len(montelistQP) monteavgQP.append(sum(montelistQP)/len(montelistQP)) montelist = [ doMonteCarloNP(line[0], line[1], w, 500) for i in range(1)] plaMonte = sum(montelist)/len(montelist) monteavgPLA.append(plaMonte) if(montelistQP < monteavgPLA): approxQP.append(1) else: approxQP.append(0) #print(sum(monteavgQP)/len(monteavgQP)) #print(sum(monteavgPLA)/len(monteavgPLA)) #print(sum(approxQP)/len(approxQP)) monteavgavgQP.append(sum(monteavgQP)/len(monteavgQP)) monteavgavgPLA.append(sum(monteavgPLA)/len(monteavgPLA)) approxavgQP.append(sum(approxQP)/len(approxQP)) vectornumberavg.append(sum(vectoravg)/len(vectoravg)) print(sum(monteavgavgQP)/len(monteavgavgQP)) print(sum(monteavgavgPLA)/len(monteavgavgPLA)) print("how good is it? ", sum(approxavgQP)/len(approxavgQP)) print("how good is it? ", sum(vectornumberavg)/len(vectornumberavg))
pramodh-bn/learn-data-edx
Week 7/qp.py
Python
unlicense
6,393
const fs = require('fs'); const electron = require('electron'); const cl = require('node-opencl'); const RUN_GAMELOOP_SYNC = true; const GAMETICK_CL = true; const INIT_OPENGL = false; let canvas; // canvas dom element let gl; // opengl context let clCtx; // opencl context let glProgram; // opengl shader program let clProgram; // opencl program let clBuildDevice; let clQueue; // let clKernelMove; let clKernelGol; let clBufferAlive; let clBufferImageData; let inputIndex = 0, outputIndex = 1; let locPosition; // location of position variable in frag shader let locTexCoord; // location of texture coords variable in frag shader let locSampler; // location of sampler in frag shader let vertexCoordBuffer; // buffer for vertext coordinates let texCoordBuffer; // buffer for texture coordinate let texture; // texture let imageData; // uint8array for texture data let textureWidth = 1600; let textureHeight = 900; let gridWidth = 1600; let gridHeight = 900; const bytesPerPixel = 4; // bytes per pixel in imageData: R,G,B,A const pixelTotal = textureWidth * textureHeight; const bytesTotal = pixelTotal * bytesPerPixel; const cellsTotal = gridWidth * gridHeight; let cellNeighbors; const cellAlive = []; const frameTimes = []; let frameTimesIndex = 0; let lastRenderTime; let fps = 0; let fpsDisplay; const FRAMETIMES_TO_KEEP = 10; function init() { (async () => { initDom(); initDrawData(); if (INIT_OPENGL) { initOpenGL(); } initData(); await initOpenCL(); initGame(); initEvents(); startGameLoop(); render(); })(); } function initDom() { canvas = document.getElementById('glscreen'); fpsDisplay = document.getElementById('fps'); } function initDrawData() { imageData = new Uint8Array(bytesTotal); } function initOpenGL() { gl = canvas.getContext('experimental-webgl'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); // init vertex buffer vertexCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexCoordBuffer); gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([ -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0]), gl.STATIC_DRAW ); // ------ SHADER SETUP const vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, fs.readFileSync(__dirname + '/shader-vertex.glsl', 'utf-8')); gl.compileShader(vertexShader); console.log('vertexShaderLog', gl.getShaderInfoLog(vertexShader)); const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fs.readFileSync(__dirname + '/shader-fragment.glsl', 'utf-8')); gl.compileShader(fragmentShader); console.log('fragmentShaderLog', gl.getShaderInfoLog(fragmentShader)); glProgram = gl.createProgram(); gl.attachShader(glProgram, vertexShader); gl.attachShader(glProgram, fragmentShader); gl.linkProgram(glProgram); console.log('glProgramLog', gl.getProgramInfoLog(glProgram)); gl.useProgram(glProgram); // --- locPosition = gl.getAttribLocation(glProgram, 'a_position'); gl.enableVertexAttribArray(locPosition); // provide texture coordinates for the rectangle. locTexCoord = gl.getAttribLocation(glProgram, 'a_texCoord'); gl.enableVertexAttribArray(locTexCoord); // ------ TEXTURE SETUP texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); // init texture to be all solid for (let i = 0; i < pixelTotal; i++) { const offset = i * bytesPerPixel; imageData[offset + 3] = 255; } texture = gl.createTexture(); locSampler = gl.getUniformLocation(glProgram, 'u_sampler'); } function initData() { cellNeighbors = new Uint32Array(cellsTotal * 8); cellAlive[0] = new Uint8Array(cellsTotal); cellAlive[1] = new Uint8Array(cellsTotal); // GOL: Cells let index = 0, indexNeighbors = 0; const maxX = gridWidth - 1; const maxY = gridHeight - 1; for (let y = 0; y < gridHeight; y++) { const prevRow = (y - 1) * gridWidth, thisRow = prevRow + gridWidth, nextRow = thisRow + gridWidth; for (let x = 0; x < gridWidth; x++) { cellNeighbors[indexNeighbors++] = (prevRow + x - 1 + cellsTotal) % cellsTotal; cellNeighbors[indexNeighbors++] = (prevRow + x + cellsTotal) % cellsTotal; cellNeighbors[indexNeighbors++] = (prevRow + x + 1 + cellsTotal) % cellsTotal; cellNeighbors[indexNeighbors++] = (thisRow + x - 1 + cellsTotal) % cellsTotal; cellNeighbors[indexNeighbors++] = (thisRow + x + 1) % cellsTotal; cellNeighbors[indexNeighbors++] = (nextRow + x - 1) % cellsTotal; cellNeighbors[indexNeighbors++] = (nextRow + x) % cellsTotal; cellNeighbors[indexNeighbors++] = (nextRow + x + 1) % cellsTotal; cellAlive[0][index++] = (Math.random() > 0.85) + 0; } } } async function initOpenCL() { // --- Init opencl // Best case we'd init a shared opengl/opencl context here, but node-opencl doesn't currently support that const platforms = cl.getPlatformIDs(); for(let i = 0; i < platforms.length; i++) console.info(`Platform ${i}: ${cl.getPlatformInfo(platforms[i], cl.PLATFORM_NAME)}`); const platform = platforms[0]; const devices = cl.getDeviceIDs(platform, cl.DEVICE_TYPE_ALL); for(let i = 0; i < devices.length; i++) console.info(` Devices ${i}: ${cl.getDeviceInfo(devices[i], cl.DEVICE_NAME)}`); console.info('creating context'); clCtx = cl.createContext([cl.CONTEXT_PLATFORM, platform], devices); // prepare opencl program // const clProgramSource = fs.readFileSync(__dirname + '/program.opencl', 'utf-8'); // GOL const clProgramSource = fs.readFileSync(__dirname + '/gol.opencl', 'utf-8'); clProgram = cl.createProgramWithSource(clCtx, clProgramSource); cl.buildProgram(clProgram); // create kernels // build kernel for first device clBuildDevice = cl.getContextInfo(clCtx, cl.CONTEXT_DEVICES)[0]; console.info('Using device: ' + cl.getDeviceInfo(clBuildDevice, cl.DEVICE_NAME)); try { // clKernelMove = cl.createKernel(clProgram, 'kmove'); clKernelGol = cl.createKernel(clProgram, 'kgol'); } catch(err) { console.error(cl.getProgramBuildInfo(clProgram, clBuildDevice, cl.PROGRAM_BUILD_LOG)); process.exit(-1); } // create buffers const clBufferNeighbors = cl.createBuffer(clCtx, cl.MEM_READ_ONLY, cellNeighbors.byteLength); clBufferAlive = [ cl.createBuffer(clCtx, cl.MEM_READ_WRITE, cellAlive[inputIndex].byteLength), cl.createBuffer(clCtx, cl.MEM_READ_WRITE, cellAlive[outputIndex].byteLength) ]; clBufferImageData = cl.createBuffer(clCtx, cl.MEM_WRITE_ONLY, imageData.byteLength); // will be set when needed so we can swap em // cl.setKernelArg(clKernelGol, 0, 'uchar*', clBufferAlive[0]); // cl.setKernelArg(clKernelGol, 1, 'uchar*', clBufferAlive[1]); cl.setKernelArg(clKernelGol, 2, 'uint*', clBufferNeighbors); cl.setKernelArg(clKernelGol, 3, 'uchar*', clBufferImageData); // create queue if (cl.createCommandQueueWithProperties !== undefined) { clQueue = cl.createCommandQueueWithProperties(clCtx, clBuildDevice, []); // OpenCL 2 } else { clQueue = cl.createCommandQueue(clCtx, clBuildDevice, null); // OpenCL 1.x } process.stdout.write('enqueue writes\n'); cl.enqueueWriteBuffer(clQueue, clBufferAlive[0], true, 0, cellAlive[inputIndex].byteLength, cellAlive[inputIndex], null); cl.enqueueWriteBuffer(clQueue, clBufferAlive[1], true, 0, cellAlive[outputIndex].byteLength, cellAlive[outputIndex], null); process.stdout.write('writes done\n'); } function initGame() { } function initEvents() { window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; }); } // ----------- GAME LOOP let lastLoopTime; const timePerTick = 50; // ms let timeSinceLastLoop = 0; let tickCounter = 0; function startGameLoop() { lastLoopTime = Date.now(); if (!RUN_GAMELOOP_SYNC) { gameLoop(); } } function gameLoop() { const now = Date.now(); timeSinceLastLoop += now - lastLoopTime; lastLoopTime = now; while(timeSinceLastLoop > timePerTick) { if (GAMETICK_CL) { gameTickCl(); } else { gameTick(); } timeSinceLastLoop -= timePerTick; } if (!RUN_GAMELOOP_SYNC) { setTimeout(gameLoop, timePerTick - timeSinceLastLoop); } } function gameTickCl() { process.stdout.write('gametick cl\n'); cl.setKernelArg(clKernelGol, 0, 'uchar*', clBufferAlive[inputIndex]); cl.setKernelArg(clKernelGol, 1, 'uchar*', clBufferAlive[outputIndex]); process.stdout.write('gametick cl 1\n'); cl.enqueueNDRangeKernel(clQueue, clKernelGol, 1, null, [cellsTotal], null); process.stdout.write('gametick cl 2\n'); cl.enqueueReadBuffer(clQueue, clBufferImageData, true, 0, imageData.byteLength, imageData); process.stdout.write('gametick cl done\n'); inputIndex = !inputIndex + 0; outputIndex = !inputIndex + 0; } function gameTick() { tickCounter++; const input = cellAlive[inputIndex]; const output = cellAlive[outputIndex]; for (let i = 0, n = 0; i < cellsTotal; i++) { const sum = input[cellNeighbors[n++]] + input[cellNeighbors[n++]] + input[cellNeighbors[n++]] + input[cellNeighbors[n++]] + input[cellNeighbors[n++]] + input[cellNeighbors[n++]] + input[cellNeighbors[n++]] + input[cellNeighbors[n++]]; // sum < 2 -> !(sum & 4294967294) // sum > 3 -> (sum & 12) 4 bit set OR 8 bit set const newAlive = (sum === 3 || (sum === 2 && input[i])) + 0 output[i] = newAlive; imageData[i * 4] = newAlive * 255; } // set computed value to red inputIndex = !inputIndex + 0; outputIndex = !inputIndex + 0; } // ----------- RENDER function renderOpenGL() { gl.clearColor(1.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); gl.vertexAttribPointer(locPosition, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.vertexAttribPointer(locTexCoord, 2, gl.FLOAT, false, 0, 0); // texture gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, textureWidth, textureHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.bindTexture(gl.TEXTURE_2D, null); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); gl.uniform1i(locSampler, 0); // draw gl.bindBuffer(gl.ARRAY_BUFFER, vertexCoordBuffer); gl.drawArrays(gl.TRIANGLES, 0, 6); // console.log(electron.screen.getCursorScreenPoint()); } function render() { window.requestAnimationFrame(render); if (RUN_GAMELOOP_SYNC) { gameLoop(); } const now = Date.now(); if (lastRenderTime) { frameTimes[frameTimesIndex] = now - lastRenderTime; frameTimesIndex = (frameTimesIndex + 1) % FRAMETIMES_TO_KEEP; if (frameTimes.length >= FRAMETIMES_TO_KEEP) { fps = 1000 * frameTimes.length / frameTimes.reduce((pv, cv) => pv + cv); // do not update every frame if ((frameTimesIndex % 5) === 0) { fpsDisplay.innerHTML = fps.toFixed(2); } } } lastRenderTime = now; if (INIT_OPENGL) { renderOpenGL(); } } init();
JohannesBeranek/electron-pixels
renderer.js
JavaScript
unlicense
11,380
package net.yottabyte.game; import java.awt.*; /** * @author Jason Fagan */ public class BouncyBall { private int x; private int y; private int vx; private int vy; private int radius; private int drag; private int mass; public BouncyBall(int x, int y, int vx, int vy, int radius, int mass, int drag) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.radius = radius; this.mass = mass; this.drag = drag; } public void move(Rectangle rect) { x += vx; y += vy; hitWall(rect); } public void paint(Graphics2D g2d) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.WHITE); g2d.fillOval(x, y, radius, radius); } public void hitWall(Rectangle rect) { if (x <= 0) { x = 0; vx = -(vx * drag); } else if (x + radius >= rect.width) { x = rect.width - radius; vx = -(vx * drag); } if (y < 0) { y = 0; vy = -(vy * drag); } else if (y + (radius * 2) >= rect.height) { y = rect.height - (radius * 2); vy = -(vy * drag); } } // see http://en.wikipedia.org/wiki/Elastic_collision public boolean hasCollidedWith(BouncyBall ball) { int dx = Math.abs(getCenterX() - ball.getCenterX()); int dy = Math.abs(getCenterY() - ball.getCenterY()); double distance = Math.sqrt(dx * dx + dy * dy); return distance <= radius; } public void handleCollision(BouncyBall ball) { int dx = getCenterX() - ball.getCenterX(); int dy = getCenterY() - ball.getCenterY(); // Calculate collision angle double ca = Math.atan2(dy, dx); // Calculate force magnitudes double mgt1 = Math.sqrt(vx * vx + vy * vy); double mgt2 = Math.sqrt(ball.getVx() * ball.getVx() + ball.getVy() * ball.getVy()); // Calculate direction double dir1 = Math.atan2(vy, vx); double dir2 = Math.atan2(ball.getVy(), ball.getVx()); // Calculate new velocities double vx1 = mgt1 * Math.cos(dir1 - ca); double vy1 = mgt1 * Math.sin(dir1 - ca); double vx2 = mgt2 * Math.cos(dir2 - ca); double vy2 = mgt2 * Math.sin(dir2 - ca); double vfx1 = ((mass - ball.getMass()) * vx1 + (ball.getMass() + ball.getMass()) * vx2) / (mass + ball.getMass()); double fvx2 = ((mass + mass) * vx1 + (ball.getMass() - mass) * vx2) / (mass + ball.getMass()); double fvy1 = vy1; double fvy2 = vy2; vx = (int) (Math.cos(ca) * vfx1 + Math.cos(ca + Math.PI / 2) * fvy1); vx = (int) (Math.sin(ca) * vfx1 + Math.sin(ca + Math.PI / 2) * fvy1); ball.setVx((int) (Math.cos(ca) * fvx2 + Math.cos(ca + Math.PI / 2) * fvy2)); ball.setVy((int) (Math.sin(ca) * fvx2 + Math.sin(ca + Math.PI / 2) * fvy2)); } public int getCenterX() { return x - radius / 2; } public int getCenterY() { return y - radius / 2; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getVx() { return vx; } public void setVx(int vx) { this.vx = vx; } public int getVy() { return vy; } public void setVy(int vy) { this.vy = vy; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public int getDrag() { return drag; } public void setDrag(int drag) { this.drag = drag; } public int getMass() { return mass; } public void setMass(int mass) { this.mass = mass; } }
jasonfagan/game-experiments
physics/src/main/java/net/yottabyte/game/BouncyBall.java
Java
unlicense
3,996
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations.Schema; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace ProjetoModelo.Infra.CrossCutting.Identity { public class ApplicationUser : IdentityUser { public ApplicationUser() { Clients = new Collection<Client>(); } public string Name { get; set; } public string Lastname { get; set; } public string Gender { get; set; } public DateTime BirthDate { get; set; } public virtual ICollection<Client> Clients { get; set; } [NotMapped] public string CurrentClientId { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, ClaimsIdentity ext = null) { // Observe que o authenticationType precisa ser o mesmo que foi definido em CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); var claims = new List<Claim>(); if (!string.IsNullOrEmpty(CurrentClientId)) { claims.Add(new Claim("AspNet.Identity.ClientId", CurrentClientId)); } // Adicione novos Claims aqui // // Adicionando Claims externos capturados no login if (ext != null) { await SetExternalProperties(userIdentity, ext); } // Gerenciamento de Claims para informaçoes do usuario //claims.Add(new Claim("AdmRoles", "True")); userIdentity.AddClaims(claims); return userIdentity; } private async Task SetExternalProperties(ClaimsIdentity identity, ClaimsIdentity ext) { if (ext != null) { var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"; // Adicionando Claims Externos no Identity foreach (var c in ext.Claims) { if (!c.Type.StartsWith(ignoreClaim)) if (!identity.HasClaim(c.Type, c.Value)) identity.AddClaim(c); } } } } }
lsilvestres/Exemplos
Arquitetura Modelo DDD/ProjetoModelo.Infra.CrossCutting.Identity/ApplicationUser.cs
C#
unlicense
2,453
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship # demo many to many relationship # http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#many-to-many engine = create_engine('sqlite:///manymany.db') Base = declarative_base() # Association table linking the two tables # Also see: http://docs.sqlalchemy.org/en/rel_0_9/orm/basic_relationships.html#association-object member_club_mapping = Table('member_club_mapping', Base.metadata, Column('member_id', Integer, ForeignKey('member.id')), Column('club_id', Integer, ForeignKey('club.id'))) class Member(Base): __tablename__ = 'member' id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) clubs = relationship('Club', back_populates='members', secondary=member_club_mapping) def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name class Club(Base): __tablename__ = 'club' id = Column(Integer, primary_key=True) name = Column(String) members = relationship('Member', back_populates='clubs', secondary=member_club_mapping) def __init__(self, name): self.name = name # create tables Base.metadata.create_all(engine) # create a Session Session = sessionmaker(bind=engine) session = Session() # Populate member1 = Member('John', 'Doe') club1 = Club('Club dub') club1.members.append(member1) session.add(club1) club2 = Club('Club dub dub') club2.members.append(member1) session.add(club2) club3 = Club('Club dub step') session.add(club3) member2 = Member('Jane', 'Allen') member2.clubs.extend([club1, club2]) session.add(member2) session.commit() # query and print Member res = session.query(Member).all() for member in res: print member.first_name, member.last_name , [club.name for club in member.clubs] # query and print Club res = session.query(Club).all() for club in res: print club.name, [(member.first_name, member.last_name) for member in club.members] print 'After removing members with first name: Jane' # Remove a record record = session.query(Member).filter(Member.first_name == 'Jane').all() for r in record: session.delete(r) session.commit() # query and print Member res = session.query(Member).all() for member in res: print member.first_name, member.last_name , [club.name for club in member.clubs] # query and print res = session.query(Club).all() for club in res: print club.name, [(member.first_name, member.last_name) for member in club.members] print 'After removing the club, Club dub' # Remove a record record = session.query(Club).filter(Club.name == 'Club dub').all() for r in record: session.delete(r) session.commit() # query and print Member res = session.query(Member).all() for member in res: print member.first_name, member.last_name , [club.name for club in member.clubs] # query and print res = session.query(Club).all() for club in res: print club.name, [(member.first_name, member.last_name) for member in club.members]
amitsaha/learning
python/sqla_learning/many_many_relation.py
Python
unlicense
3,275
/* @author Zakai Hamilton @component CoreJson */ screens.core.json = function CoreJson(me, { core, storage }) { me.init = function () { if (me.platform === "server") { me.request = require("request"); } }; me.loadComponent = async function (path, useCache = true) { var period = path.lastIndexOf("."); var component_name = path.substring(period + 1); var package_name = path.substring(0, period); var url = "/packages/code/" + package_name + "/" + package_name + "_" + component_name + ".json"; var json = await me.loadFile(url, useCache); return json; }; me.get = async function (url) { if (me.platform === "server") { return new Promise(resolve => { me.log("requesting: " + url); me.request.get(url, (error, response, body) => { if (error) { resolve({ error }); } else { if (body[0] === "<") { resolve({ error: "response is in an xml format" }); return; } let json = JSON.parse(body); resolve(json); } }); }); } else { return core.message.send_server("core.json.get", url); } }; me.loadFile = async function (path) { let json = {}; if (path && path.startsWith("/")) { path = path.substring(1); } if (!core.util.isOnline()) { json = await storage.local.db.get(me.id, path); if (json) { return json; } } var info = { method: "GET", url: "/" + path }; let buffer = "{}"; try { buffer = await core.http.send(info); } catch (err) { var error = "Cannot load json file: " + path + " err: " + err.message || err; me.log_error(error); } if (buffer) { json = JSON.parse(buffer); } await storage.local.db.set(me.id, path, json); return json; }; me.compare = function (source, target) { if (typeof source !== typeof target) { return false; } if (source === target) { return true; } if (!source && !target) { return true; } if (!source || !target) { return false; } else if (Array.isArray(source)) { var equal = source.length === target.length; if (equal) { target.map((item, index) => { var sourceItem = source[index]; if (!me.compare(sourceItem, item)) { equal = false; } }); } return equal; } else if (typeof source === "object") { var sourceKeys = Object.getOwnPropertyNames(source); var targetKeys = Object.getOwnPropertyNames(target); if (sourceKeys.length !== targetKeys.length) { return false; } for (var i = 0; i < sourceKeys.length; i++) { var propName = sourceKeys[i]; if (source[propName] !== target[propName]) { return false; } } return true; } else { return false; } }; me.traverse = function (root, path, value) { var item = root, parent = root, found = false, name = null; if (root) { item = path.split(".").reduce((node, token) => { parent = node; name = token; if (!node) { return; } return node[token]; }, root); if (typeof item !== "undefined") { value = item; found = true; } } return { parent, item, value, name, found }; }; me.value = function (root, paths, value) { var found = false; Object.entries(paths).forEach(([path, callback]) => { if (found) { return; } var info = me.traverse(root, path, value); if (info.found) { if (callback) { var result = callback(value, path); if (result) { info.value = result; found = true; } } else { value = info.value; found = true; } } }); return value; }; me.union = function (array, property) { return array.filter((obj, pos, arr) => { return arr.map(mapObj => mapObj[property]).indexOf(obj[property]) === pos; }); }; me.intersection = function (arrays, property) { var results = []; results.push(...arrays[0]); for (var array of arrays) { var keys = array.map(mapObj => mapObj[property]); results = results.filter(mapObj => -1 !== keys.indexOf(mapObj[property])); } return results; }; me.processVars = function (object, text, root) { text = text.replace(/\${[^{}]*}/g, function (match) { var path = match.substring(2, match.length - 1); if (path.startsWith("@")) { path = path.substring(1); if (path === "date") { return new Date().toString(); } else { var info = core.property.split(object, path); let item = me.traverse(root, info.value); if (item.found) { return core.property.get(object, info.name, item.value); } return ""; } } let item = me.traverse(root, path); if (item.found) { var value = item.value; if (typeof value === "object") { value = JSON.stringify(value); } return value; } return ""; }); return text; }; me.map = function (root, before, after) { if (before) { root = before(root); } if (Array.isArray(root)) { root = Array.from(root); } else if (root instanceof ArrayBuffer) { root = root.slice(0); } else if (root !== null && typeof root === "object") { root = Object.assign({}, root); } if (typeof root !== "string") { for (var key in root) { root[key] = me.map(root[key], before, after); } } if (after) { root = after(root); } return root; }; me.isValid = function (str) { try { JSON.parse(str); } catch (e) { return false; } return true; }; };
zakaihamilton/screens
packages/code/core/core_json.js
JavaScript
unlicense
7,342
exports = module.exports = addShims; function addShims() { Function.prototype.extend = function(parent) { var child = this; var args = Array.prototype.slice.call(arguments, 0); child.prototype = parent; child.prototype = new (Function.prototype.bind.apply(parent, args))(); child.prototype.constructor = child; var parentProxy = child.prototype.parent = {}; for (var i in parent) { switch(typeof parent[i]) { case 'function': parentProxy[i] = parent[i].bind(child); break; default: parentProxy[i] = parent[i]; } } return this; }; }
cabloo/express-elect-seed
api/src/core/core.shims.js
JavaScript
unlicense
625
<?php if(empty($_POST['tipname'])||empty($_POST['tipid'])) exit; include("../theme/language/en/language.php"); echo $_POST['tipid']."<!-|||->"; switch ($_POST['tipname']) { case 'select_mode_free': echo $lang['tip_free']; break; case 'select_mode_host': echo $lang['tip_host']; break; case 'select_mode_local': echo $lang['tip_local']; break; case 'select_mode_3rd': echo $lang['tip_3rd']; break; case 'param_room_name': echo $lang['tip_room_name']; break; case 'param_host_address': echo $lang['tip_host_address']; break; case 'param_local_address': echo $lang['tip_local_address']; break; case 'integration_yes': echo $lang['tip_integration_yes']; break; case 'integration_no': echo $lang['tip_integration_no']; break; case 'integration_select_mode':echo $lang['tip_integration_mode']; break; case 'integration_select_db':echo $lang['tip_integration_db']; break; case 'param_db_host':echo $lang['tip_param_db_host']; break; case 'param_db_port':echo $lang['tip_param_db_port']; break; case 'param_db_name':echo $lang['tip_param_db_name']; break; case 'param_db_username':echo $lang['tip_param_db_username']; break; case 'param_db_password':echo $lang['tip_param_db_password']; break; case 'param_db_user_table':echo $lang['tip_param_db_user_table']; break; case 'param_uesrname_field':echo $lang['tip_param_uesrname_field']; break; case 'param_pw_field':echo $lang['tip_param_pw_field']; break; case 'enablemd5':echo $lang['tip_param_enablemd5']; break; } ?>
dvelle/The-hustle-game-on-facebook-c.2010
hustle/hustle/nightworld/phpchat/includes/active_tip_word.php
PHP
unlicense
1,509
// stdafx.cpp : source file that includes just the standard includes // GetFolderTime.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
hyller/CodeLibrary
Visual C++ Example/第10章 文件操作与注册表编程/实例238——获取目录的创建时间/GetFolderTime/StdAfx.cpp
C++
unlicense
215
public class RandomColoringDiv2 { public int getCount(int maxR, int maxG, int maxB, int startR, int startG, int startB, int d1, int d2) { int colors = 0; int minR = Math.max(0, startR - d2); int minG = Math.max(0, startG - d2); int minB = Math.max(0, startB - d2); for (int r = minR; r<maxR; r++) { int difR = Math.abs(r - startR); if (difR > d2) break; for (int g = minG; g<maxG; g++) { int difG = Math.abs(g - startG); if (difG > d2) break; for (int b = minB; b<maxB; b++) { int difB = Math.abs(b - startB); if (difB > d2) break; if (difR >= d1 || difG >= d1 || difB >=d1) colors++; } } } return colors; } public static void main(String[] args) { long time; int answer; boolean errors = false; int desiredAnswer; time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(5, 1, 1, 2, 0, 0, 0, 1); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 3; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(4, 2, 2, 0, 0, 0, 3, 3); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 4; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(4, 2, 2, 0, 0, 0, 5, 5); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 0; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(6, 9, 10, 1, 2, 3, 0, 10); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 540; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(6, 9, 10, 1, 2, 3, 4, 10); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 330; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(49, 59, 53, 12, 23, 13, 11, 22); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 47439; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); if (errors) System.out.println("Some of the test cases had errors :-("); else System.out.println("You're a stud (at least on the test data)! :-D "); } } // Powered by [KawigiEdit] 2.0!
mariusj/contests
srm540/src/RandomColoringDiv2.java
Java
unlicense
5,179
import os # Application constants APP_NAME = 'job_offers' INSTALL_DIR = os.path.dirname(os.path.abspath(__file__)) LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' LOG_NAME = os.path.join(INSTALL_DIR, 'job_offers.log') # Testing fixtures JOB_OFFER_FIXTURES = os.path.join(INSTALL_DIR, "fixtures/job_offers.json")
jvazquez/organization
organization/job_offers/constants.py
Python
unlicense
334
/*globals document, setTimeout, clearTimeout, Audio, navigator */ var MallardMayhem = MallardMayhem || {}; (function () { "use strict"; MallardMayhem.Duck = function (options) { var self = this; this.currentTimeout = null; this.domElement = document.createElement('span'); this.currentLocation = 0; this.sounds = {}; this.maxAge = (20 * 1000); this.lifeSpan = null; this.id = options.id || null; this.colour = options.colour || null; this.name = options.name || 'Quacky'; this.direction = 'right'; this.flyTo = function (coords, callback) { var baseClass = 'duck-' + self.colour, randomLocation; switch (typeof coords) { case 'string': coords = coords.split(','); break; case 'function': if (coords.x && coords.y) { coords = [coords.x, coords.y]; } break; } if (!self.currentLocation) { self.domElement.style.top = '0px'; self.domElement.style.left = '0px'; self.currentLocation = [(MallardMayhem.stage.offsetWidth / 2), MallardMayhem.stage.offsetHeight - (self.domElement.style.height * 2)]; } if (self.currentLocation[0] === coords[0] && self.currentLocation[1] === coords[1]) { if (callback) { callback(); } else { randomLocation = MallardMayhem.randomCoord(); self.flyTo(randomLocation); } } else { if (self.currentLocation[1] !== coords[1]) { if (coords[1] > self.currentLocation[1]) { if ((coords[1] - self.currentLocation[1]) < MallardMayhem.animationStep) { self.currentLocation[1] = self.currentLocation[1] + (coords[1] - self.currentLocation[1]); } else { self.currentLocation[1] = self.currentLocation[1] + MallardMayhem.animationStep; } baseClass = baseClass + '-bottom'; } if (coords[1] < self.currentLocation[1]) { if ((self.currentLocation[1] - coords[1]) < MallardMayhem.animationStep) { self.currentLocation[1] = self.currentLocation[1] - (self.currentLocation[1] - coords[1]); } else { self.currentLocation[1] = self.currentLocation[1] - MallardMayhem.animationStep; } baseClass = baseClass + '-top'; } } if (self.currentLocation[0] !== coords[0]) { if (coords[0] > self.currentLocation[0]) { if ((coords[0] - self.currentLocation[0]) < MallardMayhem.animationStep) { self.currentLocation[0] = self.currentLocation[0] + (coords[0] - self.currentLocation[0]); } else { self.currentLocation[0] = self.currentLocation[0] + MallardMayhem.animationStep; } baseClass = baseClass + '-right'; } if (coords[0] < self.currentLocation[0]) { if ((self.currentLocation[0] - coords[0]) < MallardMayhem.animationStep) { self.currentLocation[0] = self.currentLocation[0] - (self.currentLocation[0] - coords[0]); } else { self.currentLocation[0] = self.currentLocation[0] - MallardMayhem.animationStep; } baseClass = baseClass + '-left'; } } self.domElement.style.left = self.currentLocation[0] + 'px'; self.domElement.style.top = self.currentLocation[1] + 'px'; if (self.domElement.className !== baseClass) { self.domElement.className = baseClass; } self.currentTimeout = setTimeout(function () { self.flyTo(coords, callback); }, MallardMayhem.animationSpeed); } }; this.drop = function () { self.currentLocation[1] = self.currentLocation[1] + (MallardMayhem.animationStep * 2); self.domElement.style.top = self.currentLocation[1] + 'px'; if (self.currentLocation[1] < MallardMayhem.stage.offsetHeight - 72) { setTimeout(self.drop, MallardMayhem.animationSpeed); } else { self.sounds.fall.currentLocation = self.sounds.fall.pause(); self.sounds.ground.play(); MallardMayhem.removeDuck(self.id); } }; this.kill = function () { clearTimeout(self.currentTimeout); clearTimeout(self.lifeSpan); self.domElement.className = 'duck-' + self.colour + '-dead'; self.sounds.fall.play(); setTimeout(self.drop, ((1000 / 4) * 3)); }; this.gotShot = function () { self.domElement.removeEventListener('mousedown', self.gotShot); self.domElement.removeEventListener('touchstart', self.gotShot); MallardMayhem.killDuck(self.id); }; this.flapWing = function () { self.sounds.flap.play(); }; this.initialize = function () { self.domElement.id = self.id; self.domElement.setAttribute('class', 'duck-' + self.colour + '-right'); self.domElement.addEventListener('mousedown', self.gotShot); self.domElement.addEventListener('touchstart', self.gotShot); MallardMayhem.stage.appendChild(self.domElement); var randomLocation = MallardMayhem.randomCoord(), format = (navigator.userAgent.indexOf('Firefox') > 1) ? 'ogg' : 'mp3'; self.flyTo(randomLocation); self.lifeSpan = setTimeout(self.flyAway, self.maxAge); self.sounds = { fall : new Audio('./audio/fall.' + format), ground: new Audio('./audio/ground.' + format) }; self.sounds.fall.volume = 0.1; }; this.flyAway = function () { clearTimeout(self.currentTimeout); self.domElement.removeEventListener('mousedown', self.gotShot); self.domElement.removeEventListener('touchstart', self.gotShot); self.domElement.className = 'duck-' + self.colour + '-top'; self.currentLocation[1] = self.currentLocation[1] - (MallardMayhem.animationStep * 3); self.domElement.style.top = self.currentLocation[1] + 'px'; if (self.currentLocation[1] > (-60)) { setTimeout(self.flyAway, MallardMayhem.animationSpeed); } else { MallardMayhem.removeDuck(self.id); } }; this.initialize(); }; }());
HTMLToronto/MallardMayhem
mm/mm.client.duck.js
JavaScript
unlicense
7,282
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace GestionInmobiliaria.RESTServices { using GestionInmobiliaria.BusinessEntity; using GestionInmobiliaria.BusinessLogic; using System.ServiceModel.Web; // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IUnidadInmobiliarias" in both code and config file together. [ServiceContract] public interface IUnidadInmobiliarias { // La UriTemplate correcta debería de estar en plural, es decir, UnidadesInmobiliarias. // EL nombre del servicio UnidadInmobiliarias.svc, puede tener el nombre en singular o como se desee: UnidadInmobiliariaService.svc [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "UnidadInmobiliarias", ResponseFormat = WebMessageFormat.Json)] List<UnidadInmobiliaria> Listar(); [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "UnidadInmobiliarias/{id}", ResponseFormat = WebMessageFormat.Json)] UnidadInmobiliaria Obtener(string id); [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "UnidadInmobiliarias", ResponseFormat = WebMessageFormat.Json)] int Agregar(UnidadInmobiliaria unidadInmobiliaria); [OperationContract] [WebInvoke(Method = "PUT", UriTemplate = "UnidadInmobiliarias", ResponseFormat = WebMessageFormat.Json)] bool Modificar(UnidadInmobiliaria unidadInmobiliaria); [OperationContract] [WebInvoke(Method = "DELETE", UriTemplate = "UnidadInmobiliarias/{id}", ResponseFormat = WebMessageFormat.Json)] bool Eliminar(string id); } }
davidhh20/APPGI-UPC
Source/Services/GestionInmobiliaria.RESTServices/IUnidadInmobiliarias.cs
C#
unlicense
1,770
<?php namespace SKE\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; class CacheClearCommand extends ContainerAwareCommand { protected $cachePath; protected $finder; protected $filesystem; /** * @param $cachePath */ public function setCachePath($cachePath) { $this->cachePath = $cachePath; } /** * @return mixed */ public function getCachePath() { return $this->cachePath; } /** * @param Filesystem $filesystem */ public function setFilesystem(Filesystem $filesystem) { $this->filesystem = $filesystem; } /** * @return Filesystem */ public function getFilesystem() { if(null === $this->filesystem) { $this->setFilesystem( new Filesystem() ); } return $this->filesystem; } /** * @param Finder $finder */ public function setFinder(Finder $finder) { $this->finder = $finder; } /** * @return Finder */ public function getFinder() { if(null === $this->finder) { $this->setFinder( Finder::create() ); } return $this->finder; } /** * Configures the command */ protected function configure() { $this->setName('cache:clear') ->setDescription('Clears the cache'); } /** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void */ protected function execute(InputInterface $input, OutputInterface $output) { $finder = $this->getFinder(); $finder->in($this->getCachePath()); $finder->ignoreDotFiles(true); $filesystem = $this->getFilesystem(); $filesystem->remove($finder); $output->writeln(sprintf("%s <info>success</info>", 'cache:clear')); } }
ooXei1sh/silex-ske-sandbox
src/SKE/Command/CacheClearCommand.php
PHP
unlicense
2,254
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Diagnostics.Tracing; using Diagnostics.Tracing.Parsers; using FastSerialization; using Utilities; using System.IO; using System.Diagnostics.Tracing; namespace Diagnostics.Tracing.Parsers { /// <summary> /// A DynamicTraceEventParser is a parser that understands how to read the embedded manifests that occur in the /// dataStream (System.Diagnostics.Tracing.EventSources do this). /// /// See also code:TDHDynamicTraceEventParser which knows how to read the manifest that are registered globally with /// the machine. /// </summary> public class DynamicTraceEventParser : TraceEventParser { public DynamicTraceEventParser(TraceEventSource source) : base(source) { if (source == null) // Happens during deserialization. return; // Try to retieve persisted state state = (DynamicTraceEventParserState)StateObject; if (state == null) { StateObject = state = new DynamicTraceEventParserState(); dynamicManifests = new Dictionary<Guid, DynamicManifestInfo>(); this.source.RegisterUnhandledEvent(delegate(TraceEvent data) { if (data.ID != (TraceEventID)0xFFFE) return data; // Look up our information. DynamicManifestInfo dynamicManifest; if (!dynamicManifests.TryGetValue(data.ProviderGuid, out dynamicManifest)) { dynamicManifest = new DynamicManifestInfo(); dynamicManifests.Add(data.ProviderGuid, dynamicManifest); } ProviderManifest provider = dynamicManifest.AddChunk(data); // We have a completed manifest, add it to our list. if (provider != null) AddDynamicProvider(provider); return data; }); } else if (allCallbackCalled) { foreach (ProviderManifest provider in state.providers.Values) provider.AddProviderEvents(source, allCallback); } } public override event Action<TraceEvent> All { add { if (state != null) { foreach (ProviderManifest provider in state.providers.Values) provider.AddProviderEvents(source, value); } allCallback += value; allCallbackCalled = true; } remove { throw new Exception("Not supported"); } } /// <summary> /// Returns a list of providers (their manifest) that this TraceParser knows about. /// </summary> public IEnumerable<ProviderManifest> DynamicProviders { get { return state.providers.Values; } } /// <summary> /// Given a manifest describing the provider add its information to the parser. /// </summary> /// <param name="providerManifest"></param> public void AddDynamicProvider(ProviderManifest providerManifest) { // Remember this serialized information. state.providers[providerManifest.Guid] = providerManifest; // If someone as asked for callbacks on every event, then include these too. if (allCallbackCalled) providerManifest.AddProviderEvents(source, allCallback); } /// <summary> /// Utility method that stores all the manifests known to the DynamicTraceEventParser to the directory 'directoryPath' /// </summary> public void WriteAllManifests(string directoryPath) { Directory.CreateDirectory(directoryPath); foreach (var providerManifest in DynamicProviders) { var filePath = Path.Combine(directoryPath, providerManifest.Name + ".manifest.xml"); providerManifest.WriteToFile(filePath); } } /// <summary> /// Utility method that read all the manifests the directory 'directoryPath' into the parser. /// </summary> public void ReadAllManifests(string directoryPath) { foreach (var fileName in Directory.GetFiles(directoryPath, "*.manifest.xml")) { AddDynamicProvider(new ProviderManifest(fileName)); } foreach (var fileName in Directory.GetFiles(directoryPath, "*.man")) { AddDynamicProvider(new ProviderManifest(fileName)); } } #region private // This allows protected members to avoid the normal initization. protected DynamicTraceEventParser(TraceEventSource source, bool noInit) : base(source) { } private class DynamicManifestInfo { internal DynamicManifestInfo() { } byte[][] Chunks; int ChunksLeft; ProviderManifest provider; byte majorVersion; byte minorVersion; ManifestEnvelope.ManifestFormats format; internal unsafe ProviderManifest AddChunk(TraceEvent data) { if (provider != null) return null; // TODO if (data.EventDataLength <= sizeof(ManifestEnvelope) || data.GetByteAt(3) != 0x5B) // magic number return null; ushort totalChunks = (ushort)data.GetInt16At(4); ushort chunkNum = (ushort)data.GetInt16At(6); if (chunkNum >= totalChunks || totalChunks == 0) return null; if (Chunks == null) { format = (ManifestEnvelope.ManifestFormats)data.GetByteAt(0); majorVersion = (byte)data.GetByteAt(1); minorVersion = (byte)data.GetByteAt(2); ChunksLeft = totalChunks; Chunks = new byte[ChunksLeft][]; } else { // Chunks have to agree with the format and version information. if (format != (ManifestEnvelope.ManifestFormats)data.GetByteAt(0) || majorVersion != data.GetByteAt(1) || minorVersion != data.GetByteAt(2)) return null; } if (Chunks[chunkNum] != null) return null; byte[] chunk = new byte[data.EventDataLength - 8]; Chunks[chunkNum] = data.EventData(chunk, 0, 8, chunk.Length); --ChunksLeft; if (ChunksLeft > 0) return null; // OK we have a complete set of chunks byte[] serializedData = Chunks[0]; if (Chunks.Length > 1) { int totalLength = 0; for (int i = 0; i < Chunks.Length; i++) totalLength += Chunks[i].Length; // Concatinate all the arrays. serializedData = new byte[totalLength]; int pos = 0; for (int i = 0; i < Chunks.Length; i++) { Array.Copy(Chunks[i], 0, serializedData, pos, Chunks[i].Length); pos += Chunks[i].Length; } } Chunks = null; // string str = Encoding.UTF8.GetString(serializedData); provider = new ProviderManifest(serializedData, format, majorVersion, minorVersion); provider.ISDynamic = true; return provider; } } DynamicTraceEventParserState state; private Dictionary<Guid, DynamicManifestInfo> dynamicManifests; Action<TraceEvent> allCallback; bool allCallbackCalled; #endregion } /// <summary> /// A ProviderManifest represents the XML manifest associated with teh provider. /// </summary> public class ProviderManifest : IFastSerializable { // create a manifest from a stream or a file /// <summary> /// Read a ProviderManifest from a stream /// </summary> public ProviderManifest(Stream manifestStream, int manifestLen = int.MaxValue) { format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat; int len = Math.Min((int)(manifestStream.Length - manifestStream.Position), manifestLen); serializedManifest = new byte[len]; manifestStream.Read(serializedManifest, 0, len); } /// <summary> /// Read a ProviderManifest from a file. /// </summary> public ProviderManifest(string manifestFilePath) { format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat; serializedManifest = File.ReadAllBytes(manifestFilePath); } // write a manifest to a stream or a file. /// <summary> /// Writes the manifest to 'outputStream' (as UTF8 XML text) /// </summary> public void WriteToStream(Stream outputStream) { outputStream.Write(serializedManifest, 0, serializedManifest.Length); } /// <summary> /// Writes the manifest to a file 'filePath' (as a UTF8 XML) /// </summary> /// <param name="filePath"></param> public void WriteToFile(string filePath) { using (var stream = File.Create(filePath)) WriteToStream(stream); } /// <summary> /// Set if this manifest came from the ETL data stream file. /// </summary> public bool ISDynamic { get; internal set; } // Get at the data in the manifest. public string Name { get { if (!inited) Init(); return name; } } public Guid Guid { get { if (!inited) Init(); return guid; } } /// <summary> /// Retrieve manifest as one big string. /// </summary> public string Manifest { get { if (!inited) Init(); return Encoding.UTF8.GetString(serializedManifest); } } /// <summary> /// Retrieve the manifest as XML /// </summary> public XmlReader ManifestReader { get { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreWhitespace = true; // TODO FIX NOW remove // var manifest = System.Text.Encoding.UTF8.GetString(serializedManifest); // Trace.WriteLine(manifest); System.IO.MemoryStream stream = new System.IO.MemoryStream(serializedManifest); return XmlReader.Create(stream, settings); } } #region private internal ProviderManifest(byte[] serializedManifest, ManifestEnvelope.ManifestFormats format, byte majorVersion, byte minorVersion) { this.serializedManifest = serializedManifest; this.majorVersion = majorVersion; this.minorVersion = minorVersion; this.format = format; } internal void AddProviderEvents(ITraceParserServices source, Action<TraceEvent> callback) { if (error != null) return; if (!inited) Init(); try { Dictionary<string, int> opcodes = new Dictionary<string, int>(); opcodes.Add("win:Info", 0); opcodes.Add("win:Start", 1); opcodes.Add("win:Stop", 2); opcodes.Add("win:DC_Start", 3); opcodes.Add("win:DC_Stop", 4); opcodes.Add("win:Extension", 5); opcodes.Add("win:Reply", 6); opcodes.Add("win:Resume", 7); opcodes.Add("win:Suspend", 8); opcodes.Add("win:Send", 9); opcodes.Add("win:Receive", 240); Dictionary<string, TaskInfo> tasks = new Dictionary<string, TaskInfo>(); Dictionary<string, TemplateInfo> templates = new Dictionary<string, TemplateInfo>(); Dictionary<string, IDictionary<long, string>> maps = null; Dictionary<string, string> strings = new Dictionary<string, string>(); IDictionary<long, string> map = null; List<EventInfo> events = new List<EventInfo>(); bool alreadyReadMyCulture = false; // I read my culture some time in the past (I can igore things) string cultureBeingRead = null; while (reader.Read()) { // TODO I currently require opcodes,and tasks BEFORE events BEFORE templates. // Can be fixed by going multi-pass. switch (reader.Name) { case "event": { int taskNum = 0; Guid taskGuid = Guid; string taskName = reader.GetAttribute("task"); if (taskName != null) { TaskInfo taskInfo; if (tasks.TryGetValue(taskName, out taskInfo)) { taskNum = taskInfo.id; taskGuid = taskInfo.guid; } } else taskName = ""; int eventID = int.Parse(reader.GetAttribute("value")); int opcode = 0; string opcodeName = reader.GetAttribute("opcode"); if (opcodeName != null) { opcodes.TryGetValue(opcodeName, out opcode); // Strip off any namespace prefix. TODO is this a good idea? int colon = opcodeName.IndexOf(':'); if (colon >= 0) opcodeName = opcodeName.Substring(colon + 1); } else { opcodeName = ""; // opcodeName = "UnknownEvent" + eventID.ToString(); } DynamicTraceEventData eventTemplate = new DynamicTraceEventData( callback, eventID, taskNum, taskName, taskGuid, opcode, opcodeName, Guid, Name); events.Add(new EventInfo(eventTemplate, reader.GetAttribute("template"))); // This will be looked up in the string table in a second pass. eventTemplate.MessageFormat = reader.GetAttribute("message"); } break; case "template": { string templateName = reader.GetAttribute("tid"); Debug.Assert(templateName != null); #if DEBUG try { #endif templates.Add(templateName, ComputeFieldInfo(reader.ReadSubtree(), maps)); #if DEBUG } catch (Exception e) { Console.WriteLine("Error: Exception during processing template {0}: {1}", templateName, e.ToString()); throw; } #endif } break; case "opcode": // TODO use message for opcode if it is available so it is localized. opcodes.Add(reader.GetAttribute("name"), int.Parse(reader.GetAttribute("value"))); break; case "task": { TaskInfo info = new TaskInfo(); info.id = int.Parse(reader.GetAttribute("value")); string guidString = reader.GetAttribute("eventGUID"); if (guidString != null) info.guid = new Guid(guidString); tasks.Add(reader.GetAttribute("name"), info); } break; case "valueMap": map = new Dictionary<long, string>(); // value maps use dictionaries goto DoMap; case "bitMap": map = new SortedList<long, string>(); // Bitmaps stored as sorted lists goto DoMap; DoMap: string name = reader.GetAttribute("name"); var mapValues = reader.ReadSubtree(); while (mapValues.Read()) { if (mapValues.Name == "map") { string keyStr = reader.GetAttribute("value"); long key; if (keyStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) key = long.Parse(keyStr.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier); else key = long.Parse(keyStr); string value = reader.GetAttribute("message"); map[key] = value; } } if (maps == null) maps = new Dictionary<string, IDictionary<long, string>>(); maps[name] = map; break; case "resources": { if (!alreadyReadMyCulture) { string desiredCulture = System.Globalization.CultureInfo.CurrentCulture.Name; if (cultureBeingRead != null && string.Compare(cultureBeingRead, desiredCulture, StringComparison.OrdinalIgnoreCase) == 0) alreadyReadMyCulture = true; cultureBeingRead = reader.GetAttribute("culture"); } } break; case "string": if (!alreadyReadMyCulture) strings[reader.GetAttribute("id")] = reader.GetAttribute("value"); break; } } // localize strings for maps. if (maps != null) { foreach (IDictionary<long, string> amap in maps.Values) { foreach (var keyValue in new List<KeyValuePair<long, string>>(amap)) { Match m = Regex.Match(keyValue.Value, @"^\$\(string\.(.*)\)$"); if (m.Success) { string newValue; if (strings.TryGetValue(m.Groups[1].Value, out newValue)) amap[keyValue.Key] = newValue; } } } } // Register all the events foreach (var eventInfo in events) { var event_ = eventInfo.eventTemplate; // Set the template if there is any. if (eventInfo.templateName != null) { var templateInfo = templates[eventInfo.templateName]; event_.payloadNames = templateInfo.payloadNames.ToArray(); event_.payloadFetches = templateInfo.payloadFetches.ToArray(); } else { event_.payloadNames = new string[0]; event_.payloadFetches = new DynamicTraceEventData.PayloadFetch[0]; } // before registering, localize any message format strings. string message = event_.MessageFormat; if (message != null) { // Expect $(STRINGNAME) where STRINGNAME needs to be looked up in the string table // TODO currently we just ignore messages without a valid string name. Is that OK? event_.MessageFormat = null; Match m = Regex.Match(message, @"^\$\(string\.(.*)\)$"); if (m.Success) strings.TryGetValue(m.Groups[1].Value, out event_.MessageFormat); } source.RegisterEventTemplate(event_); } // Create an event for the manifest event itself so it looks pretty in dumps. source.RegisterEventTemplate(new DynamicManifestTraceEventData(callback, this)); } catch (Exception e) { // TODO FIX NOW, log this! Debug.Assert(false, "Exception during manifest parsing"); #if DEBUG Console.WriteLine("Error: Exception during processing of in-log manifest for provider {0}. Symbolic information may not be complete.", Name); #endif error = e; } inited = false; // If we call it again, start over from the begining. } private class EventInfo { public EventInfo(DynamicTraceEventData eventTemplate, string templateName) { this.eventTemplate = eventTemplate; this.templateName = templateName; } public DynamicTraceEventData eventTemplate; public string templateName; }; private class TaskInfo { public int id; public Guid guid; }; private class TemplateInfo { public List<string> payloadNames; public List<DynamicTraceEventData.PayloadFetch> payloadFetches; }; private TemplateInfo ComputeFieldInfo(XmlReader reader, Dictionary<string, IDictionary<long, string>> maps) { var ret = new TemplateInfo(); ret.payloadNames = new List<string>(); ret.payloadFetches = new List<DynamicTraceEventData.PayloadFetch>(); ushort offset = 0; while (reader.Read()) { if (reader.Name == "data") { string inType = reader.GetAttribute("inType"); Type type = GetTypeForManifestTypeName(inType); ushort size = DynamicTraceEventData.SizeOfType(type); // Strings are weird in that they are encoded multiple ways. if (type == typeof(string) && inType == "win:AnsiString") size = DynamicTraceEventData.NULL_TERMINATED | DynamicTraceEventData.IS_ANSI; ret.payloadNames.Add(reader.GetAttribute("name")); IDictionary<long, string> map = null; string mapName = reader.GetAttribute("map"); if (mapName != null && maps != null) maps.TryGetValue(mapName, out map); ret.payloadFetches.Add(new DynamicTraceEventData.PayloadFetch(offset, size, type, map)); if (offset != ushort.MaxValue) { Debug.Assert(size != 0); if (size < DynamicTraceEventData.SPECIAL_SIZES) offset += size; else offset = ushort.MaxValue; } } } return ret; } private static Type GetTypeForManifestTypeName(string manifestTypeName) { switch (manifestTypeName) { // TODO do we want to support unsigned? case "win:Pointer": case "trace:SizeT": return typeof(IntPtr); case "win:Boolean": return typeof(bool); case "win:UInt8": case "win:Int8": return typeof(byte); case "win:UInt16": case "win:Int16": case "trace:Port": return typeof(short); case "win:UInt32": case "win:Int32": case "trace:IPAddr": case "trace:IPAddrV4": return typeof(int); case "trace:WmiTime": case "win:UInt64": case "win:Int64": return typeof(long); case "win:Double": return typeof(double); case "win:Float": return typeof(float); case "win:AnsiString": case "win:UnicodeString": return typeof(string); case "win:GUID": return typeof(Guid); case "win:FILETIME": return typeof(DateTime); default: throw new Exception("Unsupported type " + manifestTypeName); } } #region IFastSerializable Members void IFastSerializable.ToStream(Serializer serializer) { serializer.Write(majorVersion); serializer.Write(minorVersion); serializer.Write((int)format); int count = 0; if (serializedManifest != null) count = serializedManifest.Length; serializer.Write(count); for (int i = 0; i < count; i++) serializer.Write(serializedManifest[i]); } void IFastSerializable.FromStream(Deserializer deserializer) { deserializer.Read(out majorVersion); deserializer.Read(out minorVersion); format = (ManifestEnvelope.ManifestFormats)deserializer.ReadInt(); int count = deserializer.ReadInt(); serializedManifest = new byte[count]; for (int i = 0; i < count; i++) serializedManifest[i] = deserializer.ReadByte(); Init(); } private void Init() { try { reader = ManifestReader; while (reader.Read()) { if (reader.Name == "provider") { guid = new Guid(reader.GetAttribute("guid")); name = reader.GetAttribute("name"); fileName = reader.GetAttribute("resourceFileName"); break; } } if (name == null) throw new Exception("No provider element found in manifest"); } catch (Exception e) { Debug.Assert(false, "Exception during manifest parsing"); name = ""; error = e; } inited = true; } #endregion private XmlReader reader; private byte[] serializedManifest; private byte majorVersion; private byte minorVersion; ManifestEnvelope.ManifestFormats format; private Guid guid; private string name; private string fileName; private bool inited; private Exception error; #endregion } #region internal classes /// <summary> /// DynamicTraceEventData is an event that knows how to take runtime information to parse event fields (and payload) /// /// This meta-data is distilled down to a array of field names and an array of PayloadFetches which contain enough /// information to find the field data in the payload blob. This meta-data is used in the /// code:DynamicTraceEventData.PayloadNames and code:DynamicTraceEventData.PayloadValue methods. /// </summary> public class DynamicTraceEventData : TraceEvent, IFastSerializable { internal DynamicTraceEventData(Action<TraceEvent> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { Action = action; } internal protected event Action<TraceEvent> Action; protected internal override void Dispatch() { if (Action != null) { Action(this); } } public override string[] PayloadNames { get { Debug.Assert(payloadNames != null); return payloadNames; } } public override object PayloadValue(int index) { Type type = payloadFetches[index].type; if (type == null) return "[CANT PARSE]"; int offset = payloadFetches[index].offset; if (offset == ushort.MaxValue) offset = SkipToField(index); if ((uint)offset >= 0x10000) return "[CANT PARSE OFFSET]"; switch (Type.GetTypeCode(type)) { case TypeCode.String: { var size = payloadFetches[index].size; var isAnsi = false; if (size >= SPECIAL_SIZES) { isAnsi = ((size & IS_ANSI) != 0); var format = (size & ~IS_ANSI); if (format == NULL_TERMINATED) { if ((size & IS_ANSI) != 0) return GetUTF8StringAt(offset); else return GetUnicodeStringAt(offset); } else if (format == DynamicTraceEventData.COUNT32_PRECEEDS) size = (ushort)GetInt32At(offset - 4); else if (format == DynamicTraceEventData.COUNT16_PRECEEDS) size = (ushort)GetInt16At(offset - 2); else return "[CANT PARSE STRING]"; } else if (size > 0x8000) { size -= 0x8000; isAnsi = true; } if (isAnsi) return GetFixedAnsiStringAt(size, offset); else return GetFixedUnicodeStringAt(size / 2, offset); } case TypeCode.Boolean: return GetByteAt(offset) != 0; case TypeCode.Byte: return (byte)GetByteAt(offset); case TypeCode.SByte: return (SByte)GetByteAt(offset); case TypeCode.Int16: return GetInt16At(offset); case TypeCode.UInt16: return (UInt16)GetInt16At(offset); case TypeCode.Int32: return GetInt32At(offset); case TypeCode.UInt32: return (UInt32)GetInt32At(offset); case TypeCode.Int64: return GetInt64At(offset); case TypeCode.UInt64: return (UInt64)GetInt64At(offset); case TypeCode.Single: return GetSingleAt(offset); case TypeCode.Double: return GetDoubleAt(offset); default: if (type == typeof(IntPtr)) { if (PointerSize == 4) return (UInt32)GetInt32At(offset); else return (UInt64)GetInt64At(offset); } else if (type == typeof(Guid)) return GetGuidAt(offset); else if (type == typeof(DateTime)) return DateTime.FromFileTime(GetInt64At(offset)); else if (type == typeof(byte[])) { int size = payloadFetches[index].size; if (size >= DynamicTraceEventData.SPECIAL_SIZES) { if (payloadFetches[index].size == DynamicTraceEventData.COUNT32_PRECEEDS) size = GetInt32At(offset - 4); else if (payloadFetches[index].size == DynamicTraceEventData.COUNT16_PRECEEDS) size = (ushort)GetInt16At(offset - 2); else return "[CANT PARSE]"; } var ret = new byte[size]; EventData(ret, 0, offset, ret.Length); return ret; } return "[UNSUPPORTED TYPE]"; } } public override string PayloadString(int index) { object value = PayloadValue(index); var map = payloadFetches[index].map; string ret = null; long asLong; if (map != null) { asLong = (long)((IConvertible)value).ToInt64(null); if (map is SortedList<long, string>) { StringBuilder sb = new StringBuilder(); // It is a bitmap, compute the bits from the bitmap. foreach (var keyValue in map) { if (asLong == 0) break; if ((keyValue.Key & asLong) != 0) { if (sb.Length != 0) sb.Append('|'); sb.Append(keyValue.Value); asLong &= ~keyValue.Key; } } if (asLong != 0) { if (sb.Length != 0) sb.Append('|'); sb.Append(asLong); } else if (sb.Length == 0) sb.Append('0'); ret = sb.ToString(); } else { // It is a value map, just look up the value map.TryGetValue(asLong, out ret); } } if (ret != null) return ret; // Print large long values as hex by default. if (value is long) { asLong = (long)value; goto PrintLongAsHex; } else if (value is ulong) { asLong = (long)(ulong)value; goto PrintLongAsHex; } var asByteArray = value as byte[]; if (asByteArray != null) { StringBuilder sb = new StringBuilder(); var limit = Math.Min(asByteArray.Length, 16); for (int i = 0; i < limit; i++) { var b = asByteArray[i]; sb.Append(HexDigit((b / 16))); sb.Append(HexDigit((b % 16))); } if (limit < asByteArray.Length) sb.Append("..."); return sb.ToString(); } return value.ToString(); PrintLongAsHex: if ((int)asLong != asLong) return "0x" + asLong.ToString("x"); return asLong.ToString(); } private static char HexDigit(int digit) { if (digit < 10) return (char)('0' + digit); else return (char)('A' - 10 + digit); } public override string FormattedMessage { get { if (MessageFormat == null) return null; // TODO is this error handling OK? // Replace all %N with the string value for that parameter. return Regex.Replace(MessageFormat, @"%(\d+)", delegate(Match m) { int index = int.Parse(m.Groups[1].Value) - 1; if ((uint)index < (uint)PayloadNames.Length) return PayloadString(index); else return "<<Out Of Range>>"; }); } } #region private private int SkipToField(int index) { // Find the first field that has a fixed offset. int offset = 0; int cur = index; while (0 < cur) { --cur; offset = payloadFetches[cur].offset; if (offset != ushort.MaxValue) break; } // TODO it probably does pay to remember the offsets in a particular instance, since otherwise the // algorithm is N*N while (cur < index) { ushort size = payloadFetches[cur].size; if (size >= SPECIAL_SIZES) { if (size == NULL_TERMINATED) offset = SkipUnicodeString(offset); else if (size == (NULL_TERMINATED | IS_ANSI)) offset = SkipUTF8String(offset); else if (size == POINTER_SIZE) offset += PointerSize; else if ((size & ~IS_ANSI) == COUNT32_PRECEEDS) offset += GetInt32At(offset - 4); else if ((size & ~IS_ANSI) == COUNT16_PRECEEDS) offset += (ushort)GetInt16At(offset - 2); else return -1; } else offset += size; cur++; } return offset; } internal static ushort SizeOfType(Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.String: return NULL_TERMINATED; case TypeCode.SByte: case TypeCode.Byte: return 1; case TypeCode.UInt16: case TypeCode.Int16: return 2; case TypeCode.UInt32: case TypeCode.Int32: case TypeCode.Boolean: // We follow windows conventions and use 4 bytes for bool. case TypeCode.Single: return 4; case TypeCode.UInt64: case TypeCode.Int64: case TypeCode.Double: case TypeCode.DateTime: return 8; default: if (type == typeof(Guid)) return 16; if (type == typeof(IntPtr)) return POINTER_SIZE; throw new Exception("Unsupported type " + type.Name); // TODO } } internal const ushort IS_ANSI = 1; // A bit mask that represents the string is ASCII // NULL_TERMINATD | IS_ANSI == MaxValue internal const ushort NULL_TERMINATED = ushort.MaxValue - 1; // COUNT32_PRECEEDS | IS_ANSI == MaxValue - 2 internal const ushort COUNT32_PRECEEDS = ushort.MaxValue - 3; // Count is a 32 bit int directly before // COUNT16_PRECEEDS | IS_ANSI == MaxValue -4 internal const ushort COUNT16_PRECEEDS = ushort.MaxValue - 5; // Count is a 16 bit uint directly before internal const ushort POINTER_SIZE = ushort.MaxValue - 14; // It is the pointer size of the target machine. internal const ushort UNKNOWN_SIZE = ushort.MaxValue - 15; // Generic unknown. internal const ushort SPECIAL_SIZES = ushort.MaxValue - 15; // Some room for growth. internal struct PayloadFetch { public PayloadFetch(ushort offset, ushort size, Type type, IDictionary<long, string> map = null) { this.offset = offset; this.size = size; this.type = type; this.map = map; } public ushort offset; // offset == MaxValue means variable size. // TODO come up with a real encoding for variable sized things public ushort size; // See special encodeings above (also size > 0x8000 means fixed lenght ANSI). public IDictionary<long, string> map; public Type type; }; void IFastSerializable.ToStream(Serializer serializer) { serializer.Write((int)eventID); serializer.Write((int)task); serializer.Write(taskName); serializer.Write(taskGuid); serializer.Write((int)opcode); serializer.Write(opcodeName); serializer.Write(providerGuid); serializer.Write(providerName); serializer.Write(MessageFormat); serializer.Write(lookupAsWPP); serializer.Write(payloadNames.Length); foreach (var payloadName in payloadNames) serializer.Write(payloadName); serializer.Write(payloadFetches.Length); foreach (var payloadFetch in payloadFetches) { serializer.Write((short)payloadFetch.offset); serializer.Write((short)payloadFetch.size); if (payloadFetch.type == null) serializer.Write((string)null); else serializer.Write(payloadFetch.type.FullName); serializer.Write((IFastSerializable)null); // This is for the map (eventually) } } void IFastSerializable.FromStream(Deserializer deserializer) { eventID = (TraceEventID)deserializer.ReadInt(); task = (TraceEventTask)deserializer.ReadInt(); deserializer.Read(out taskName); deserializer.Read(out taskGuid); opcode = (TraceEventOpcode)deserializer.ReadInt(); deserializer.Read(out opcodeName); deserializer.Read(out providerGuid); deserializer.Read(out providerName); deserializer.Read(out MessageFormat); deserializer.Read(out lookupAsWPP); int count; deserializer.Read(out count); payloadNames = new string[count]; for (int i = 0; i < count; i++) deserializer.Read(out payloadNames[i]); deserializer.Read(out count); payloadFetches = new PayloadFetch[count]; for (int i = 0; i < count; i++) { payloadFetches[i].offset = (ushort)deserializer.ReadInt16(); payloadFetches[i].size = (ushort)deserializer.ReadInt16(); var typeName = deserializer.ReadString(); if (typeName != null) payloadFetches[i].type = Type.GetType(typeName); IFastSerializable dummy; deserializer.Read(out dummy); // For map when we use it. } } // Fields internal PayloadFetch[] payloadFetches; internal string MessageFormat; // This is in ETW conventions (%N) #endregion } /// <summary> /// This class is only used to pretty-print the manifest event itself. It is pretty special purpose /// </summary> class DynamicManifestTraceEventData : DynamicTraceEventData { internal DynamicManifestTraceEventData(Action<TraceEvent> action, ProviderManifest manifest) : base(action, 0xFFFE, 0, "ManifestData", Guid.Empty, 0, null, manifest.Guid, manifest.Name) { this.manifest = manifest; payloadNames = new string[] { "Format", "MajorVersion", "MinorVersion", "Magic", "TotalChunks", "ChunkNumber" }; payloadFetches = new PayloadFetch[] { new PayloadFetch(0, 1, typeof(byte)), new PayloadFetch(1, 1, typeof(byte)), new PayloadFetch(2, 1, typeof(byte)), new PayloadFetch(3, 1, typeof(byte)), new PayloadFetch(4, 2, typeof(ushort)), new PayloadFetch(6, 2, typeof(ushort)), }; Action += action; } public override StringBuilder ToXml(StringBuilder sb) { int totalChunks = GetInt16At(4); int chunkNumber = GetInt16At(6); if (chunkNumber + 1 == totalChunks) { StringBuilder baseSb = new StringBuilder(); base.ToXml(baseSb); sb.AppendLine(XmlUtilities.OpenXmlElement(baseSb.ToString())); sb.Append(manifest.Manifest); sb.Append("</Event>"); return sb; } else return base.ToXml(sb); } #region private ProviderManifest manifest; #endregion } /// <summary> /// DynamicTraceEventParserState represents the state of a DynamicTraceEventParser that needs to be /// serialied to a log file. It does NOT include information about what events are chosen but DOES contain /// any other necessary information that came from the ETL data file. /// </summary> class DynamicTraceEventParserState : IFastSerializable { public DynamicTraceEventParserState() { providers = new Dictionary<Guid, ProviderManifest>(); } internal Dictionary<Guid, ProviderManifest> providers; #region IFastSerializable Members void IFastSerializable.ToStream(Serializer serializer) { serializer.Write(providers.Count); foreach (ProviderManifest provider in providers.Values) serializer.Write(provider); } void IFastSerializable.FromStream(Deserializer deserializer) { int count; deserializer.Read(out count); for (int i = 0; i < count; i++) { ProviderManifest provider; deserializer.Read(out provider); providers.Add(provider.Guid, provider); } } #endregion } } #endregion
brian-dot-net/writeasync
projects/TraceSample/source/TraceEvent/DynamicTraceEventParser.cs
C#
unlicense
49,945
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/pages/datatables.css"> <link href="<?php echo base_url(); ?>assets/vendors/bootstrapvalidator/css/bootstrapValidator.min.css" rel="stylesheet"> <script type="text/javascript" src="<?php echo base_url(); ?>assets/vendors/bootstrapvalidator/js/bootstrapValidator.min.js"></script> <style> @media(max-width: 1024px) { .radio-inline + .radio-inline, .checkbox-inline + .checkbox-inline { margin-top: 0; margin-left: 8px; } } </style> <div class="row"> <div class="col-md-12"> <!-- First Basic Table strats here--> <div class="panel"> <?php if ($status=='2') { ?> <div class="panel-heading" style="background-color: #2980b9;"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Disetujui </h3> </div> <?php }else if ($status=='1'){ ?> <div class="panel-heading" style="background-color: #f1c40f;"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Proses </h3> </div> <?php }else if ($status=='3'){ ?> <div class="panel-heading" style="background-color: #e74c3c;"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Tidak Disetujui </h3> </div> <?php } ?> <div class="panel-body"> <div class="col-lg-12"> <?php if ($status=='2') { ?> <p>Anda dapat mencetak rekomendasi kecamatan</p> <?php }else if ($status=='1') { ?> <p>Data Anda belum diproses</p> <?php }else if ($status=='3') { ?> <p>Data Anda tidak disetujui oleh kecamatan, silahkan periksa kembali data anda. dan lakukan update.</p> <?php } ?> </div> </div> </div> </div> </div> <form method="post" class="form-horizontal p-10" role="form"> <div class="row"> <div class="col-lg-12"> <!-- First Basic Table strats here--> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Data Pemohon </h3> </div> <div class="panel-body"> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">NIK Pemohon</label> <div class="col-md-9"> <input type="text" class="form-control" name="nik_pemohon" id="nik_pemohon" placeholder="NIK Pemohon" value="<?php echo isset($nik_pemohon)?$nik_pemohon:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Nama Pemohon</label> <div class="col-md-9"> <input type="text" class="form-control" name="nama_pemohon" id="nama_pemohon" placeholder="Nama Pemohon" value="<?php echo isset($nama_pemohon)?$nama_pemohon:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Tempat Lahir</label> <div class="col-md-9"> <input type="text" class="form-control" name="tempat_lahir" id="tempat_lahir" placeholder="Tempat Lahir" value="<?php echo isset($tempat_lahir)?$tempat_lahir:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Tanggal Lahir</label> <div class="col-md-9"> <input type="text" class="form-control tanggal" name="tgl_lahir" id="tgl_lahir" placeholder="Tanggal Lahir" data-date-format="dd-mm-yyyy" value="<?php echo isset($tgl_lahir)?$tgl_lahir:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Pekerjaan</label> <div class="col-md-9"> <input type="text" class="form-control" name="pekerjaan" id="pekerjaan" placeholder="Pekerjaan" value="<?php echo isset($pekerjaan)?$pekerjaan:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">No. Telp</label> <div class="col-md-9"> <input type="text" class="form-control" name="no_telp" id="no_telp" placeholder="No. Telp" value="<?php echo isset($no_telp)?$no_telp:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Negara</label> <div class="col-md-9"> <input type="text" class="form-control" name="negara_pemohon" id="negara_pemohon" placeholder="Negara" value="<?php echo isset($negara_pemohon)?$negara_pemohon:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Alamat</label> <div class="col-md-9"> <textarea rows="3" class="form-control resize_vertical" name="alamat" id="alamat" placeholder="Alamat" readonly><?php echo isset($alamat)?$alamat:''; ?></textarea> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <!-- First Basic Table strats here--> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Data Perusahaan </h3> </div> <div class="panel-body"> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Nama Usaha</label> <div class="col-md-9"> <input type="text" class="form-control" name="nama_usaha" id="nama_usaha" placeholder="Nama Usaha" value="<?php echo isset($nama_usaha)?$nama_usaha:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Jenis Usaha</label> <div class="col-md-9"> <input type="text" class="form-control" name="jenis_usaha" id="jenis_usaha" placeholder="Jenis Usaha" value="<?php echo isset($jenis_usaha)?$jenis_usaha:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Ukuruan Luas</label> <div class="col-md-9"> <input type="text" class="form-control" name="ukuran_luas_usaha" id="ukuran_luas_usaha" placeholder="Ukuran Usaha" value="<?php echo isset($ukuran_luas_usaha)?$ukuran_luas_usaha:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Lokasi</label> <div class="col-md-9"> <input type="text" class="form-control" name="lokasi_usaha" id="lokasi_usaha" placeholder="Lokasi Usaha" value="<?php echo isset($lokasi_usaha)?$lokasi_usaha:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Status Bangunan</label> <div class="col-md-9"> <input type="text" class="form-control" name="status_bangunan_tempat_usaha" id="status_bangunan_tempat_usaha" placeholder="Status Bangunan Tempat Usaha" value="<?php echo isset($status_bangunan_tempat_usaha)?$status_bangunan_tempat_usaha:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">NPWPD</label> <div class="col-md-9"> <input type="text" class="form-control" name="npwpd" id="npwpd" placeholder="NPWPD" value="<?php echo isset($npwpd)?$npwpd:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Klasifikasi Usaha</label> <div class="col-md-9"> <input type="text" class="form-control" name="klasifikasi_usaha" id="klasifikasi_usaha" placeholder="Klasifikasi Usaha" value="<?php echo isset($klasifikasi_usaha)?$klasifikasi_usaha:''; ?>" readonly > </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Retribusi Pertahun Fiskal</label> <div class="col-md-9"> <input type="text" class="form-control" name="retribusi_perthn_f" id="retribusi_perthn_f" placeholder="Retribusi Pertahun Fiskal" value="<?php echo isset($retribusi_perthn_f)?$retribusi_perthn_f:''; ?>" > </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <!-- First Basic Table strats here--> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Jenis Pendaftaran </h3> </div> <div class="panel-body"> <div class="form-group p-10"> <label class="control-label col-md-8" for="text">&nbsp;</label> <div class="col-md-4"> <div class="col-md-6"> <b>Baru</b> </div> <div class="col-md-6"> <b>Ulang</b> </div> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">1. Jenis Pendaftaran </label> <div class="col-md-4"> <?php if ($jenis_permohonan=='baru') { ?> <div class="col-md-6"> <input type="radio" name="jenis_permohonan" class="radio-blue" value="baru" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="jenis_permohonan" class="radio-blue" value="lama" checked="true"> </div> <?php } ?> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <!-- First Basic Table strats here--> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Syarat Umum </h3> </div> <div class="panel-body"> <div class="form-group p-10"> <label class="control-label col-md-8" for="text">&nbsp;</label> <div class="col-md-4"> <div class="col-md-6"> <b>Ada</b> </div> <div class="col-md-6"> <b>Tidak Ada</b> </div> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">1. Fotokopi KTP ( 1 (satu) lembar) </label> <div class="col-md-4"> <?php if ($ktp=='ada') { ?> <div class="col-md-6"> <input type="radio" name="ktp" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="ktp" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">2. Fotocopy Tanda Bukti Hak Atas Tanah </label> <div class="col-md-4"> <?php if ($fc_hak_tanah=='ada') { ?> <div class="col-md-6"> <input type="radio" name="fc_hak_tanah" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="fc_hak_tanah" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">3. Surat Pengantar dari kelurahan/desa </label> <div class="col-md-4"> <?php if ($sp_desa=='ada') { ?> <div class="col-md-6"> <input type="radio" name="sp_desa" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="sp_desa" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">4. Surat Permohonan bermaterai 6000 </label> <div class="col-md-4"> <?php if ($sp_materai=='ada') { ?> <div class="col-md-6"> <input type="radio" name="sp_materai" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="sp_materai" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">5. Denah Lokasi </label> <div class="col-md-4"> <?php if ($denah_lokasi=='ada') { ?> <div class="col-md-6"> <input type="radio" name="denah_lokasi" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="denah_lokasi" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">6. Pas Foto Berwarna 3 x 4 ( 3 (tiga) lembar) </label> <div class="col-md-4"> <?php if ($foto=='ada') { ?> <div class="col-md-6"> <input type="radio" name="foto" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="foto" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">7. Fotocopy PBB </label> <div class="col-md-4"> <?php if ($fc_pbb=='ada') { ?> <div class="col-md-6"> <input type="radio" name="fc_pbb" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="fc_pbb" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">8. Rekomendasi dari UPTD Puskesmas setempat </label> <div class="col-md-4"> <?php if ($rekom_uptd=='ada') { ?> <div class="col-md-6"> <input type="radio" name="rekom_uptd" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="rekom_uptd" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">9. Gambar Bangunan</label> <div class="col-md-4"> <?php if ($gambar_bangunan=='ada') { ?> <div class="col-md-6"> <input type="radio" name="gambar_bangunan" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="gambar_bangunan" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">10. Instalasi air, listrik dan telepon</label> <div class="col-md-4"> <?php if ($instalasi_air=='ada') { ?> <div class="col-md-6"> <input type="radio" name="instalasi_air" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="instalasi_air" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">11. Rekomendasi Lurah/Kepala Desa setempat</label> <div class="col-md-4"> <?php if ($rekom_desa=='ada') { ?> <div class="col-md-6"> <input type="radio" name="rekom_desa" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="rekom_desa" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <!-- First Basic Table strats here--> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Syarat Tambahan Pendaftaran Ulang </h3> </div> <div class="panel-body"> <div class="form-group p-10"> <label class="control-label col-md-8" for="text">&nbsp;</label> <div class="col-md-4"> <div class="col-md-6"> <b>Ada</b> </div> <div class="col-md-6"> <b>Tidak Ada</b> </div> </div> </div> <div class="form-group p-10"> <label class="col-md-8" for="text">1. SIUP Asli </label> <div class="col-md-4"> <?php if ($siup_asli=='ada') { ?> <div class="col-md-6"> <input type="radio" name="siup_asli" class="radio-blue" value="ada" checked="true"> </div> <div class="col-md-6"> &nbsp; </div> <?php }else{ ?> <div class="col-md-6"> &nbsp; </div> <div class="col-md-6"> <input type="radio" name="siup_asli" class="radio-blue" value="tidak ada" checked="true"> </div> <?php } ?> </div> </div> </div> </div> </div> <div class="row"> <div class="col-lg-12"> <!-- First Basic Table strats here--> <div class="panel"> <div class="panel-heading"> <h3 class="panel-title"> <i class="ti-layout-cta-left"></i> Verifikasi dan Data Kecamatan </h3> </div> <div class="panel-body"> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Tanggal Register</label> <div class="col-md-9"> <input type="text" class="form-control tanggal" name="tgl_register" id="tgl_register" placeholder="Tanggal Register" data-date-format="dd-mm-yyyy" value="<?php echo isset($tgl_register)?$tgl_register:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">No. Registrasi</label> <div class="col-md-9"> <input type="text" class="form-control" name="no_register" id="no_register" placeholder="No. Registrasi" value="<?php echo isset($no_register)?$no_register:''; ?>" <?php if ($action=='update') { echo 'readonly'; } ?>> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Nama Petugas Verifikasi</label> <div class="col-md-9"> <input type="text" class="form-control" name="nama_petugas_verifikasi" id="nama_petugas_verifikasi" placeholder="Nama Petugas Verifikasi" value="<?php echo isset($nama_petugas_verifikasi)?$nama_petugas_verifikasi:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Tanggal Verifikasi</label> <div class="col-md-9"> <input type="text" class="form-control tanggal" name="tgl_verifikasi" id="tgl_verifikasi" placeholder="Tanggal Verifikasi" data-date-format="dd-mm-yyyy" value="<?php echo isset($tgl_verifikasi)?$tgl_verifikasi:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">Nama Camat</label> <div class="col-md-9"> <input type="text" class="form-control" name="nama_camat" id="nama_camat" placeholder="Nama Camat" value="<?php echo isset($nama_camat)?$nama_camat:''; ?>" readonly> </div> </div> <div class="form-group p-10"> <label class="control-label col-md-3" for="text">NIP Camat</label> <div class="col-md-9"> <input type="text" class="form-control" name="nip_camat" id="nip_camat" placeholder="NIP Camat" value="<?php echo isset($nip_camat)?$nip_camat:''; ?>" readonly> </div> </div> </div> </div> </div> </div> </form> <div class="col-md-6"> &nbsp; </div> <?php if ($status=='2') { ?> <div class="col-md-2"> <a href='#' class="btn btn-lg btn-primary" onclick="printsurat('<?php echo $id ?>')" ><i class='fa fa-print'></i> Izin</a> </div> <?php }else{ ?> <div class="col-md-2"> &nbsp; </div> <?php } ?> <div class="col-md-2"> <a href='#' class="btn btn-lg btn-primary" onclick="formulir('<?php echo $id ?>')" ><i class='fa fa-print'></i> Formulir</a> </div> <div class="col-md-2"> <a href="<?php echo site_url($this->controller) ?>"> <button style="border-radius: 8;" id="reset" type="button" class="btn btn-lg btn-danger">Kembali</button></a> </div> <?php $this->load->view($this->controller.'_status_view_js'); ?>
NizarHafizulllah/simpatenksb
application/modules/kec_siu/views/kec_siu_status_view.php
PHP
unlicense
29,766
package br.com.tosin.ssd.utils; /** * Created by roger on 11/03/17. */ public class CONSTANTS_DIRECTIONS { public static final String NORTH = "N"; public static final String SOUTH = "S"; public static final String WEST = "W"; public static final String EAST = "E"; public static final String NORTHWEST = "NW"; public static final String NORTHEAST = "NE"; public static final String SOUTH_WEST = "SW"; public static final String SOUTHEAST = "SE"; }
TosinRoger/SmartSystemsDesign
src/br/com/tosin/ssd/utils/CONSTANTS_DIRECTIONS.java
Java
unlicense
526
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Windows.Forms; using IFSExplorer.Properties; namespace IFSExplorer { public partial class MainForm : Form { private static readonly Dictionary<int, int> InitialIndexGuesses = new Dictionary<int, int> { {257040, 50}, {257400, 31}, {282240, 58}, {293760, 50}, {310800, 38}, {440640, 48}, {674240, 23}, {756576, 20}, {820800, 63}, {836752, 11}, {872640, 42}, {906096, 10} }; class SaveFilter { internal readonly string Extensions; private readonly string _name; internal readonly ImageFormat ImageFormat; internal SaveFilter(string extensions, string name, ImageFormat imageFormat) { Extensions = extensions; _name = name; ImageFormat = imageFormat; } public static string ToString(SaveFilter saveFilter) { return string.Format("{0} ({1})|{1}", saveFilter._name, saveFilter.Extensions); } } private static readonly List<SaveFilter> SaveFilters = new List<SaveFilter> { new SaveFilter("*.bmp;*.dib", "24-bit Bitmap", ImageFormat.Bmp), new SaveFilter("*.gif", "GIF", ImageFormat.Gif), new SaveFilter("*.jpg;*.jpeg;*.jfif", "JPEG", ImageFormat.Jpeg), new SaveFilter("*.png", "PNG", ImageFormat.Png), new SaveFilter("*.tif;*.tiff", "TIFF", ImageFormat.Tiff), }; private readonly Dictionary<int, int> _indexGuesses = new Dictionary<int, int>(); private string _indexGuessesFilename; private Stream _currentStream; private FileIndex _currentFileIndex; private DecodedRaw _currentRaw; public MainForm() { InitializeComponent(); saveFileDialog.Filter = string.Join("|", SaveFilters.ConvertAll(SaveFilter.ToString).ToArray()); } private void MainForm_Load(object sender, EventArgs e) { var path = Assembly.GetEntryAssembly().Location; var directoryName = Path.GetDirectoryName(path); if (directoryName == null) { FillInitialGuesses(); return; } _indexGuessesFilename = Path.Combine(directoryName, "index_guesses.txt"); if (!File.Exists(_indexGuessesFilename)) { FillInitialGuesses(); return; } var lines = File.ReadAllLines(_indexGuessesFilename); foreach (var line in lines) { var split = line.Replace(" ", "").Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries); if (split.Length != 2) { continue; } int size, index; if (int.TryParse(split[0], out size) && int.TryParse(split[1], out index)) { _indexGuesses.Add(size, index); } } } private void FillInitialGuesses() { foreach (var initialIndexGuess in InitialIndexGuesses) { _indexGuesses.Add(initialIndexGuess.Key, initialIndexGuess.Value); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { using (var fileStream = File.OpenWrite(_indexGuessesFilename)) using (var streamWriter = new StreamWriter(fileStream)) { foreach (var indexGuess in _indexGuesses) { streamWriter.WriteLine("{0}, {1}", indexGuess.Key, indexGuess.Value); } } } private void browseToolStripMenuItem_Click(object sender, EventArgs e) { var dialogResult = openFileDialog.ShowDialog(); if (dialogResult != DialogResult.OK) { return; } listboxImages.Items.Clear(); if (_currentStream != null) { _currentStream.Close(); } _currentStream = openFileDialog.OpenFile(); var mappings = IFSUtils.ParseIFS(_currentStream); foreach (var mapping in mappings) { listboxImages.Items.Add(new ImageItem(mapping)); } } private void saveSelectedImageToolStripMenuItem_Click(object sender, EventArgs e) { if (_currentRaw == null) { MessageBox.Show( Resources .MainForm_saveSelectedImageToolStripMenuItem_Click_Open_an_IFS_file_and_select_a_valid_image_first_, Resources.MainForm_Bemani_IFS_Explorer, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var dialogResult = saveFileDialog.ShowDialog(); if (dialogResult != DialogResult.OK) { return; } using (var bitmap = DrawToBitmap()) { var saveFilter = SaveFilters[saveFileDialog.FilterIndex - 1]; var fileName = saveFileDialog.FileName; if (fileName.IndexOf('.') == -1) { fileName += string.Format(".{0}", saveFilter.Extensions.Split(';')[0]); } bitmap.Save(fileName, saveFilter.ImageFormat); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); } private void aboutBemaniIFSExplorerToolStripMenuItem_Click(object sender, EventArgs e) { new AboutBox().ShowDialog(); } private void listboxImages_SelectedIndexChanged(object sender, EventArgs e) { updownIndexSelect.Minimum = 0; updownIndexSelect.Value = 0; updownIndexSelect.Maximum = 0; updownIndexSelect.Enabled = true; DrawFileIndex(); } private void updownIndexSelect_ValueChanged(object sender, EventArgs e) { DrawFileIndex(); } private void DrawFileIndex() { var imageItem = listboxImages.SelectedItem as ImageItem; if (imageItem == null) { return; } var fileIndex = imageItem.FileIndex; if (_currentFileIndex != fileIndex) { _currentFileIndex = fileIndex; var rawBytes = IFSUtils.DecompressLSZZ(fileIndex.Read()); try { _currentRaw = IFSUtils.DecodeRaw(rawBytes); } catch (Exception e) { _currentRaw = null; labelStatus.Text = string.Format("Couldn't decode raw #{0}: {1}", fileIndex.EntryNumber, e); return; } } if (_currentRaw == null) { return; } if (updownIndexSelect.Value == 0) { updownIndexSelect.Maximum = _currentRaw.IndexSize - 1; int indexGuess; if (!_indexGuesses.TryGetValue(_currentRaw.RawLength, out indexGuess)) { indexGuess = (int) (((decimal) _currentRaw.IndexSize)/2); } updownIndexSelect.Value = indexGuess; } var index = (int) updownIndexSelect.Value; _indexGuesses[_currentRaw.RawLength] = index; var size = _currentRaw.GetSize(index); labelStatus.Text = string.Format("#{0}: {1} bytes decompresses to {2} bytes (index {3} = {4}x{5})", fileIndex.EntryNumber, fileIndex.Size, _currentRaw.RawLength, index, size.X, size.Y); var oldImage = pictureboxPreview.Image; pictureboxPreview.Image = DrawToBitmap(); if (oldImage != null) { oldImage.Dispose(); } } private Bitmap DrawToBitmap() { var index = (int) updownIndexSelect.Value; var size = _currentRaw.GetSize(index); var bitmap = new Bitmap(size.X, size.Y, PixelFormat.Format32bppArgb); for (var y = 0; y < size.Y; ++y) { for (var x = 0; x < size.X; ++x) { var argb = _currentRaw.GetARGB(index, x, y); var color = Color.FromArgb(argb); bitmap.SetPixel(x, y, color); } } return bitmap; } private class ImageItem { internal readonly FileIndex FileIndex; internal ImageItem(FileIndex fileIndex) { FileIndex = fileIndex; } public override string ToString() { return string.Format("#{0} ({1})", FileIndex.EntryNumber, FileIndex.Size); } } } }
kivikakk/ifsexplorer
IFSExplorer/MainForm.cs
C#
unlicense
9,291
#!/usr/bin/env node var http = require('http'); var moment = require('moment'); var server = undefined; var threshold = undefined; var units = undefined; if (!isValid(process.argv)) { console.error('invalid arguments, expected hostname threshold and units'); process.exit(-1); } var request = http.request('http://' + server + '/api/temperatures', function(response) { var statusCode = response.statusCode; var result = []; var json = undefined; if (statusCode === 200) { response.on('data', function(chunk) { result.push(chunk.toString()); }); response.on('end', function() { json = JSON.parse(result.join('')); analyze(json); }); } }); request.end(); function analyze(data) { var length = data.length; var i, sensorData, sensorId, sensorLog, dates; var analysis; for (i = 0; i < length; i++) { sensorData = data[i]; sensorId = sensorData['_id']; sensorLog = sensorData['value']; dates = sensorLog.map(function(log) { return moment(log.date); }); dates.sort(function(a, b) { return (a < b ? -1 : (a > b ? 1 : 0)); }); analysis = dates.reduce(function(analysis, to) { var from = analysis.previous; var diff; if (analysis.previous) { diff = to.diff(from, units); if (diff > threshold) { analysis.result.push({ diff: diff + ' ' + units, from: from.format('YYMMDDHHmm'), to: to.format('YYMMDDHHmm') }); } } return { previous: to, result: analysis.result }; }, { result: [] }); console.log(sensorId, analysis.result); } } function isValid(args) { if (args.length === 5) { server = args[2]; threshold = parseInt(args[3], 10); units = args[4]; return true; } else { return false; } }
initcz/thermohome-client-rpi
util/analyzeMissingDates.js
JavaScript
unlicense
1,860
using System; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using BFF.DataVirtualizingCollection.PageStorage; using MrMeeseeks.Reactive.Extensions; namespace BFF.DataVirtualizingCollection.DataVirtualizingCollection { internal sealed class SyncDataVirtualizingCollection<T> : DataVirtualizingCollectionBase<T> { private readonly Func<CancellationToken, int> _countFetcher; private readonly IScheduler _notificationScheduler; private readonly IPageStorage<T> _pageStorage; private readonly Subject<Unit> _resetSubject = new(); private int _count; internal SyncDataVirtualizingCollection( Func<int, IPageStorage<T>> pageStoreFactory, Func<CancellationToken, int> countFetcher, IObservable<(int Offset, int PageSize, T[] PreviousPage, T[] Page)> observePageFetches, IDisposable disposeOnDisposal, IScheduler notificationScheduler) : base (observePageFetches, disposeOnDisposal, notificationScheduler) { _countFetcher = countFetcher; _notificationScheduler = notificationScheduler; _count = _countFetcher(CancellationToken.None); _pageStorage = pageStoreFactory(_count); _resetSubject.CompositeDisposalWith(CompositeDisposable); _resetSubject .Subscribe(_ => ResetInner()) .CompositeDisposalWith(CompositeDisposable); } public override int Count => _count; protected override T GetItemInner(int index) { return _pageStorage[index]; } private void ResetInner() { _count = _countFetcher(CancellationToken.None); _pageStorage.Reset(_count); _notificationScheduler.Schedule(Unit.Default, (_, __) => { OnPropertyChanged(nameof(Count)); OnCollectionChangedReset(); OnIndexerChanged(); }); } public override void Reset() => _resetSubject.OnNext(Unit.Default); public override Task InitializationCompleted { get; } = Task.CompletedTask; public override async ValueTask DisposeAsync() { await base.DisposeAsync().ConfigureAwait(false); await _pageStorage.DisposeAsync().ConfigureAwait(false); } } }
Yeah69/BFF.DataVirtualizingCollection
BFF.DataVirtualizingCollection/DataVirtualizingCollection/SyncDataVirtualizingCollection.cs
C#
unlicense
2,505
#!/usr/bin/python # uart-eg01.py # # to run on the other end of the UART # screen /dev/ttyUSB1 115200 import serial def readlineCR(uart): line = b'' while True: byte = uart.read() line += byte if byte == b'\r': return line uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0)
CurtisLeeBolin/Examples_Python
UART01.py
Python
unlicense
567
#include "serverBase.h" int main(int argc, char** argv) { unsigned portNumber = 12943; if(argc >= 2) { portNumber = atoi(argv[1]); } try { asio::io_service io_service; asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), portNumber); TCPServer server(io_service, endpoint); io_service.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
AdamHarter/flaming-octo-wookie
server/server.cpp
C++
unlicense
444
from rec import CourseRecord from score import RoomScore from evaluation import ScheduleEvaluation FULL_HOURS = 8 # 8:00AM - 4:00PM utilization PARTIAL_HOURS = FULL_HOURS * 0.75 #75% HALF_HOURS = FULL_HOURS * 0.50 #50% SPARSE_HOURS = FULL_HOURS * 0.25 #25% class LocationScore: def __init__(self, evals=None): self.evals = evals self.courses = None self.location = None self.daily_weights = {"M": {}, "T": {}, "W": {}, "R": {}, "F": {} ,"S": {}} self.daily_totals = {"M": {}, "T": {}, "W": {}, "R": {}, "F": {} ,"S": {}} self.final_weighted = 0 self.weight_rank = 0 # 0 = worst, 1 = best if evals != None: self.courses = self.evals.get_records() self.location = self.find_location() self.final_weighted = self.calculate_final_weighted_score() def reset_daily_weights(self): for day in ["M", "T", "W", "R", "F", "S"]: self.daily_weights[day] = 0 self.daily_totals[day] = 0 def get_daily_weight(self,day_of_week): return self.daily_weights[day_of_week] def normalize_final_weighted_score(self,minimum,maximum): value = self.final_weighted value -= minimum if maximum - minimum > 0: value /= ( maximum - minimum ) else: value = 0 self.weight_rank = "{0:.2f}".format(value * 10) def calculate_final_weighted_score(self): score_sum = 0.00 score_total = 0.00 #reset daily stuff self.reset_daily_weights() for course, score in self.courses: days = course.rec["DAYS_OF_WEEK"] #score_sum += score.get_weighted_score(course) score_total += 1.00 for day in ["M", "T", "W", "R", "F", "S"]: if day in days: self.daily_weights[day] += score.get_weighted_score(course) self.daily_totals[day] += 1 for day in ["M", "T", "W", "R", "F", "S"]: if self.daily_totals[day] > 0: self.daily_weights[day] /= self.daily_totals[day] self.daily_weights[day] = self.adjust_utilization(self.daily_weights[day],self.daily_totals[day]) score_sum += self.daily_weights[day] else: self.daily_weights[day] = 0 return score_sum / score_total def adjust_utilization(self,weights,totals): max_score = 1.00 if totals >= FULL_HOURS: # 8 Hours or more, give slight boost to score weights *= 1.15 # 15% Boost elif totals >= PARTIAL_HOURS: # Small Penalty weights *= (PARTIAL_HOURS/FULL_HOURS) elif totals >= HALF_HOURS: # Medium Penalty weights *= (HALF_HOURS/FULL_HOURS) elif totals > SPARSE_HOURS: # Large Penalty weights *= (SPARSE_HOURS/FULL_HOURS) else: # Very Large Penalty weights *= (1.00/FULL_HOURS) return weights def get_location(self): return self.location def find_location(self): for course, score in self.courses: location = str( course.rec["BUILDING"] )+ " " + str( course.rec["ROOM"] ) # just need to find the first one, so break after this happens break return location def get_final_weighted_score(self): return self.final_weighted def get_score_rank(self): return self.weight_rank def get_evals(self): return self.evals
jbrackins/scheduling-research
src/location.py
Python
unlicense
3,581
package ua.clinic.tests.integration; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import ua.ibt.clinic.api.DetailsAPI; import ua.ibt.clinic.api.DoctorAPI; import java.text.SimpleDateFormat; import static org.junit.Assert.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by Iryna Tkachova on 11.03.2017. */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class UserdetailsControllerTest { private static final Logger logger = LoggerFactory.getLogger(UserdetailsControllerTest.class); @Autowired private MockMvc mockMvc; @Test public void test_addDetails() throws Exception { logger.debug(">>>>>>>>>> test_addDetails >>>>>>>>>>"); DetailsAPI detailsAPI = new DetailsAPI(); detailsAPI.iduser = Long.valueOf(984844); detailsAPI.numcard = "aa-111"; detailsAPI.name = "Ivan"; detailsAPI.surname = "Ivanenko"; detailsAPI.middlename = "Ivanovich"; detailsAPI.birthday = new SimpleDateFormat("yyyy-MM-dd").parse("2001-10-10"); detailsAPI.sex = "M"; detailsAPI.notes = "test"; ObjectMapper om = new ObjectMapper(); String content = om.writeValueAsString(detailsAPI); MvcResult result = mockMvc.perform(post("/details/set") .accept(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(content) ) .andExpect(status().isOk()) .andReturn(); String reply = result.getResponse().getContentAsString(); DetailsAPI resultData = om.readValue(reply, DetailsAPI.class); assertEquals("Reurn code in not 0",resultData.retcode.longValue(), 0L); } @Test public void test_setDoctor() throws Exception { logger.debug(">>>>>>>>>> test_setDoctor >>>>>>>>>>"); DoctorAPI doctorAPI = new DoctorAPI(); doctorAPI.iduser = Long.valueOf(984844); doctorAPI.tabnumber = Long.valueOf(22222); ObjectMapper om = new ObjectMapper(); String content = om.writeValueAsString(doctorAPI); MvcResult result = mockMvc.perform(post("/doctor/set") .accept(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(content) ) .andExpect(status().isOk()) .andReturn(); String reply = result.getResponse().getContentAsString(); DetailsAPI resultData = om.readValue(reply, DetailsAPI.class); assertEquals("Reurn code in not 0",resultData.retcode.longValue(), 0L); } }
beamka/Polyclinic
Clinic/src/test/java/ua/clinic/tests/integration/UserdetailsControllerTest.java
Java
unlicense
3,482
require 'google_tts/connector' require 'google_tts/query_builder' require 'google_tts/parser' require 'google_tts/mp3writer' module GoogleTts VERSION = "0.1.0" class Client include GoogleTts def initialize(connector = Connector.new, query_builder = QueryBuilder.new, mp3writer = Mp3Writer.new, parser = Parser.new) @connector = connector @parser = parser @query_builder = query_builder @mp3writer = mp3writer end def save(name, text) sentences = @parser.sentences(text) queries = @query_builder.generate_from(*sentences) contents = @connector.get_contents(*queries) @mp3writer.save(name, *contents) end end def self.instantiate(params = {}) proxy = params[:proxy] || @proxy connection = proxy ? Net::HTTP::Proxy(proxy[:host], proxy[:port]) : Net::HTTP lang = params[:lang] || :en output = params[:output] || "out" Client.new(Connector.new(connection), QueryBuilder.new(lang), Mp3Writer.new(output)) end def self.with_random_proxy(_params = {}) @proxy = ProxyFetcher.random_proxy self end end
filipesperandio/google_tts2
lib/google_tts.rb
Ruby
unlicense
1,167
"""redblue_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^red/', include('apps.red_app.urls', namespace='red_namespace')), url(r'^blue/', include('apps.blue_app.urls', namespace='blue_namespace')), url(r'^admin/', admin.site.urls), ]
thinkAmi-sandbox/Django_iis_global_static_sample
redblue_project/urls.py
Python
unlicense
991
using UnityEngine; using UnityEngine.SceneManagement; public class ShowModeA : MonoBehaviour { public Texture AModeTexture; public Texture BModeTexture; private PlayerControllerBMode playerControllerBMode; private GameController gameController; void Start () { InitPlayerController(); InitGameController(); UpdateModeAndTexture(); } void InitPlayerController() { GameObject playerGameObject = GameObject.FindGameObjectWithTag("Player"); if (playerGameObject != null) playerControllerBMode = playerGameObject.GetComponent<PlayerControllerBMode>(); else Debug.Log("Error: Player no encontrado."); } private void InitGameController() { GameObject gameControllerObject = GameObject.FindGameObjectWithTag("GameController"); if (gameControllerObject != null) gameController = gameControllerObject.GetComponent<GameController>(); else Debug.Log("Error: Game Controller no encontrado."); } public void UpdateModeAndTexture(){ if (PlayerPrefs.GetInt("active_mode", 1) == 2) { GetComponent<Renderer>().material.SetTexture("_MainTex", AModeTexture); playerControllerBMode.enabled = true; gameController.InitHighscore(); gameController.ChangeBackground(2); } else { GetComponent<Renderer>().material.SetTexture("_MainTex", BModeTexture); playerControllerBMode.enabled = false; gameController.InitHighscore(); gameController.ChangeBackground(1); } } }
Maximetinu/No-Mans-Flappy-Unity
Assets/Scripts/MenuButtons/ShowModeA.cs
C#
unlicense
1,678
/* * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; /** * Miscellaneous collection utility methods. * Mainly for internal use within the framework. * * @author Juergen Hoeller * @author Rob Harrop * @since 1.1.3 */ public abstract class CollectionUtils { /** * Return <code>true</code> if the supplied Collection is <code>null</code> * or empty. Otherwise, return <code>false</code>. * @param collection the Collection to check * @return whether the given Collection is empty */ public static boolean isEmpty(Collection collection) { return (collection == null || collection.isEmpty()); } /** * Return <code>true</code> if the supplied Map is <code>null</code> * or empty. Otherwise, return <code>false</code>. * @param map the Map to check * @return whether the given Map is empty */ public static boolean isEmpty(Map map) { return (map == null || map.isEmpty()); } /** * Convert the supplied array into a List. A primitive array gets * converted into a List of the appropriate wrapper type. * <p>A <code>null</code> source value will be converted to an * empty List. * @param source the (potentially primitive) array * @return the converted List result * @see ObjectUtils#toObjectArray(Object) */ public static List arrayToList(Object source) { return Arrays.asList(ObjectUtils.toObjectArray(source)); } /** * Merge the given array into the given Collection. * @param array the array to merge (may be <code>null</code>) * @param collection the target Collection to merge the array into */ public static void mergeArrayIntoCollection(Object array, Collection collection) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } Object[] arr = ObjectUtils.toObjectArray(array); for (int i = 0; i < arr.length; i++) { collection.add(arr[i]); } } /** * Merge the given Properties instance into the given Map, * copying all properties (key-value pairs) over. * <p>Uses <code>Properties.propertyNames()</code> to even catch * default properties linked into the original Properties instance. * @param props the Properties instance to merge (may be <code>null</code>) * @param map the target Map to merge the properties into */ public static void mergePropertiesIntoMap(Properties props, Map map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } if (props != null) { for (Enumeration en = props.propertyNames(); en.hasMoreElements();) { String key = (String) en.nextElement(); map.put(key, props.getProperty(key)); } } } /** * Check whether the given Iterator contains the given element. * @param iterator the Iterator to check * @param element the element to look for * @return <code>true</code> if found, <code>false</code> else */ public static boolean contains(Iterator iterator, Object element) { if (iterator != null) { while (iterator.hasNext()) { Object candidate = iterator.next(); if (ObjectUtils.nullSafeEquals(candidate, element)) { return true; } } } return false; } /** * Check whether the given Enumeration contains the given element. * @param enumeration the Enumeration to check * @param element the element to look for * @return <code>true</code> if found, <code>false</code> else */ public static boolean contains(Enumeration enumeration, Object element) { if (enumeration != null) { while (enumeration.hasMoreElements()) { Object candidate = enumeration.nextElement(); if (ObjectUtils.nullSafeEquals(candidate, element)) { return true; } } } return false; } /** * Check whether the given Collection contains the given element instance. * <p>Enforces the given instance to be present, rather than returning * <code>true</code> for an equal element as well. * @param collection the Collection to check * @param element the element to look for * @return <code>true</code> if found, <code>false</code> else */ public static boolean containsInstance(Collection collection, Object element) { if (collection != null) { for (Iterator it = collection.iterator(); it.hasNext();) { Object candidate = it.next(); if (candidate == element) { return true; } } } return false; } /** * Return <code>true</code> if any element in '<code>candidates</code>' is * contained in '<code>source</code>'; otherwise returns <code>false</code>. * @param source the source Collection * @param candidates the candidates to search for * @return whether any of the candidates has been found */ public static boolean containsAny(Collection source, Collection candidates) { if (isEmpty(source) || isEmpty(candidates)) { return false; } for (Iterator it = candidates.iterator(); it.hasNext();) { if (source.contains(it.next())) { return true; } } return false; } /** * Return the first element in '<code>candidates</code>' that is contained in * '<code>source</code>'. If no element in '<code>candidates</code>' is present in * '<code>source</code>' returns <code>null</code>. Iteration order is * {@link Collection} implementation specific. * @param source the source Collection * @param candidates the candidates to search for * @return the first present object, or <code>null</code> if not found */ public static Object findFirstMatch(Collection source, Collection candidates) { if (isEmpty(source) || isEmpty(candidates)) { return null; } for (Iterator it = candidates.iterator(); it.hasNext();) { Object candidate = it.next(); if (source.contains(candidate)) { return candidate; } } return null; } /** * Find a single value of the given type in the given Collection. * @param collection the Collection to search * @param type the type to look for * @return a value of the given type found if there is a clear match, * or <code>null</code> if none or more than one such value found */ public static Object findValueOfType(Collection collection, Class type) { if (isEmpty(collection)) { return null; } Object value = null; for (Iterator it = collection.iterator(); it.hasNext();) { Object obj = it.next(); if (type == null || type.isInstance(obj)) { if (value != null) { // More than one value found... no clear single value. return null; } value = obj; } } return value; } /** * Find a single value of one of the given types in the given Collection: * searching the Collection for a value of the first type, then * searching for a value of the second type, etc. * @param collection the collection to search * @param types the types to look for, in prioritized order * @return a value of one of the given types found if there is a clear match, * or <code>null</code> if none or more than one such value found */ public static Object findValueOfType(Collection collection, Class[] types) { if (isEmpty(collection) || ObjectUtils.isEmpty(types)) { return null; } for (int i = 0; i < types.length; i++) { Object value = findValueOfType(collection, types[i]); if (value != null) { return value; } } return null; } /** * Determine whether the given Collection only contains a single unique object. * @param collection the Collection to check * @return <code>true</code> if the collection contains a single reference or * multiple references to the same instance, <code>false</code> else */ public static boolean hasUniqueObject(Collection collection) { if (isEmpty(collection)) { return false; } boolean hasCandidate = false; Object candidate = null; for (Iterator it = collection.iterator(); it.hasNext();) { Object elem = it.next(); if (!hasCandidate) { hasCandidate = true; candidate = elem; } else if (candidate != elem) { return false; } } return true; } }
codeApeFromChina/resource
frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/util/CollectionUtils.java
Java
unlicense
8,998
#define LOG_MODULE PacketLogModuleIgmpLayer #include "IgmpLayer.h" #include "PacketUtils.h" #include "Logger.h" #include <string.h> #include "EndianPortable.h" namespace pcpp { /************* * IgmpLayer *************/ IgmpLayer::IgmpLayer(IgmpType type, const IPv4Address& groupAddr, uint8_t maxResponseTime, ProtocolType igmpVer) { m_DataLen = getHeaderSizeByVerAndType(igmpVer, type); m_Data = new uint8_t[m_DataLen]; memset(m_Data, 0, m_DataLen); m_Protocol = igmpVer; setType(type); if (groupAddr.isValid()) setGroupAddress(groupAddr); getIgmpHeader()->maxResponseTime = maxResponseTime; } void IgmpLayer::setGroupAddress(const IPv4Address& groupAddr) { igmp_header* hdr = getIgmpHeader(); hdr->groupAddress = groupAddr.toInt(); } IgmpType IgmpLayer::getType() const { uint8_t type = getIgmpHeader()->type; if (type < (uint8_t)IgmpType_MembershipQuery || (type > (uint8_t)IgmpType_LeaveGroup && type < (uint8_t)IgmpType_MulticastTracerouteResponse) || (type > (uint8_t)IgmpType_MulticastTraceroute && type < (uint8_t)IgmpType_MembershipReportV3) || (type > (uint8_t)IgmpType_MembershipReportV3 && type < (uint8_t)IgmpType_MulticastRouterAdvertisement) || type > IgmpType_MulticastRouterTermination) return IgmpType_Unknown; return (IgmpType)type; } void IgmpLayer::setType(IgmpType type) { if (type == IgmpType_Unknown) return; igmp_header* hdr = getIgmpHeader(); hdr->type = type; } ProtocolType IgmpLayer::getIGMPVerFromData(uint8_t* data, size_t dataLen, bool& isQuery) { isQuery = false; if (dataLen < 8 || data == NULL) return UnknownProtocol; switch ((int)data[0]) { case IgmpType_MembershipReportV2: case IgmpType_LeaveGroup: return IGMPv2; case IgmpType_MembershipReportV1: return IGMPv1; case IgmpType_MembershipReportV3: return IGMPv3; case IgmpType_MembershipQuery: { isQuery = true; if (dataLen >= sizeof(igmpv3_query_header)) return IGMPv3; if (data[1] == 0) return IGMPv1; else return IGMPv2; } default: return UnknownProtocol; } } uint16_t IgmpLayer::calculateChecksum() { ScalarBuffer<uint16_t> buffer; buffer.buffer = (uint16_t*)getIgmpHeader(); buffer.len = getHeaderLen(); return computeChecksum(&buffer, 1); } size_t IgmpLayer::getHeaderSizeByVerAndType(ProtocolType igmpVer, IgmpType igmpType) const { if (igmpVer == IGMPv1 || igmpVer == IGMPv2) return sizeof(igmp_header); if (igmpVer == IGMPv3) { if (igmpType == IgmpType_MembershipQuery) return sizeof(igmpv3_query_header); else if (igmpType == IgmpType_MembershipReportV3) return sizeof(igmpv3_report_header); } return 0; } std::string IgmpLayer::toString() const { std::string igmpVer = ""; switch (getProtocol()) { case IGMPv1: igmpVer = "1"; break; case IGMPv2: igmpVer = "2"; break; default: igmpVer = "3"; } std::string msgType; switch (getType()) { case IgmpType_MembershipQuery: msgType = "Membership Query"; break; case IgmpType_MembershipReportV1: msgType = "Membership Report"; break; case IgmpType_DVMRP: msgType = "DVMRP"; break; case IgmpType_P1Mv1: msgType = "PIMv1"; break; case IgmpType_CiscoTrace: msgType = "Cisco Trace"; break; case IgmpType_MembershipReportV2: msgType = "Membership Report"; break; case IgmpType_LeaveGroup: msgType = "Leave Group"; break; case IgmpType_MulticastTracerouteResponse: msgType = "Multicast Traceroute Response"; break; case IgmpType_MulticastTraceroute: msgType = "Multicast Traceroute"; break; case IgmpType_MembershipReportV3: msgType = "Membership Report"; break; case IgmpType_MulticastRouterAdvertisement: msgType = "Multicast Router Advertisement"; break; case IgmpType_MulticastRouterSolicitation: msgType = "Multicast Router Solicitation"; break; case IgmpType_MulticastRouterTermination: msgType = "Multicast Router Termination"; break; default: msgType = "Unknown"; break; } std::string result = "IGMPv" + igmpVer + " Layer, " + msgType + " message"; return result; } /************* * IgmpV1Layer *************/ void IgmpV1Layer::computeCalculateFields() { igmp_header* hdr = getIgmpHeader(); hdr->checksum = 0; hdr->checksum = htobe16(calculateChecksum()); hdr->maxResponseTime = 0; } /************* * IgmpV2Layer *************/ void IgmpV2Layer::computeCalculateFields() { igmp_header* hdr = getIgmpHeader(); hdr->checksum = 0; hdr->checksum = htobe16(calculateChecksum()); } /****************** * IgmpV3QueryLayer ******************/ IgmpV3QueryLayer::IgmpV3QueryLayer(uint8_t* data, size_t dataLen, Layer* prevLayer, Packet* packet) : IgmpLayer(data, dataLen, prevLayer, packet, IGMPv3) { } IgmpV3QueryLayer::IgmpV3QueryLayer(const IPv4Address& multicastAddr, uint8_t maxResponseTime, uint8_t s_qrv) : IgmpLayer(IgmpType_MembershipQuery, multicastAddr, maxResponseTime, IGMPv3) { getIgmpV3QueryHeader()->s_qrv = s_qrv; } uint16_t IgmpV3QueryLayer::getSourceAddressCount() const { return be16toh(getIgmpV3QueryHeader()->numOfSources); } IPv4Address IgmpV3QueryLayer::getSourceAddressAtIndex(int index) const { uint16_t numOfSources = getSourceAddressCount(); if (index < 0 || index >= numOfSources) return IPv4Address(); // verify numOfRecords is a reasonable number that points to data within the packet int ptrOffset = index * sizeof(uint32_t) + sizeof(igmpv3_query_header); if (ptrOffset + sizeof(uint32_t) > getDataLen()) return IPv4Address(); uint8_t* ptr = m_Data + ptrOffset; return IPv4Address(*(uint32_t*)ptr); } size_t IgmpV3QueryLayer::getHeaderLen() const { uint16_t numOfSources = getSourceAddressCount(); int headerLen = numOfSources * sizeof(uint32_t) + sizeof(igmpv3_query_header); // verify numOfRecords is a reasonable number that points to data within the packet if ((size_t)headerLen > getDataLen()) return getDataLen(); return (size_t)headerLen; } void IgmpV3QueryLayer::computeCalculateFields() { igmpv3_query_header* hdr = getIgmpV3QueryHeader(); hdr->checksum = 0; hdr->checksum = htobe16(calculateChecksum()); } bool IgmpV3QueryLayer::addSourceAddress(const IPv4Address& addr) { return addSourceAddressAtIndex(addr, getSourceAddressCount()); } bool IgmpV3QueryLayer::addSourceAddressAtIndex(const IPv4Address& addr, int index) { uint16_t sourceAddrCount = getSourceAddressCount(); if (index < 0 || index > (int)sourceAddrCount) { PCPP_LOG_ERROR("Cannot add source address at index " << index << ", index is out of bounds"); return false; } size_t offset = sizeof(igmpv3_query_header) + index * sizeof(uint32_t); if (offset > getHeaderLen()) { PCPP_LOG_ERROR("Cannot add source address at index " << index << ", index is out of packet bounds"); return false; } if (!extendLayer(offset, sizeof(uint32_t))) { PCPP_LOG_ERROR("Cannot add source address at index " << index << ", didn't manage to extend layer"); return false; } memcpy(m_Data + offset, addr.toBytes(), sizeof(uint32_t)); getIgmpV3QueryHeader()->numOfSources = htobe16(sourceAddrCount+1); return true; } bool IgmpV3QueryLayer::removeSourceAddressAtIndex(int index) { uint16_t sourceAddrCount = getSourceAddressCount(); if (index < 0 || index > (int)sourceAddrCount-1) { PCPP_LOG_ERROR("Cannot remove source address at index " << index << ", index is out of bounds"); return false; } size_t offset = sizeof(igmpv3_query_header) + index * sizeof(uint32_t); if (offset >= getHeaderLen()) { PCPP_LOG_ERROR("Cannot remove source address at index " << index << ", index is out of packet bounds"); return false; } if (!shortenLayer(offset, sizeof(uint32_t))) { PCPP_LOG_ERROR("Cannot remove source address at index " << index << ", didn't manage to shorten layer"); return false; } getIgmpV3QueryHeader()->numOfSources = htobe16(sourceAddrCount-1); return true; } bool IgmpV3QueryLayer::removeAllSourceAddresses() { size_t offset = sizeof(igmpv3_query_header); size_t numOfBytesToShorted = getHeaderLen() - offset; if (!shortenLayer(offset, numOfBytesToShorted)) { PCPP_LOG_ERROR("Cannot remove all source addresses, didn't manage to shorten layer"); return false; } getIgmpV3QueryHeader()->numOfSources = 0; return true; } /******************* * IgmpV3ReportLayer *******************/ uint16_t IgmpV3ReportLayer::getGroupRecordCount() const { return be16toh(getReportHeader()->numOfGroupRecords); } igmpv3_group_record* IgmpV3ReportLayer::getFirstGroupRecord() const { // check if there are group records at all if (getHeaderLen() <= sizeof(igmpv3_report_header)) return NULL; uint8_t* curGroupPtr = m_Data + sizeof(igmpv3_report_header); return (igmpv3_group_record*)curGroupPtr; } igmpv3_group_record* IgmpV3ReportLayer::getNextGroupRecord(igmpv3_group_record* groupRecord) const { if (groupRecord == NULL) return NULL; // prev group was the last group if ((uint8_t*)groupRecord + groupRecord->getRecordLen() - m_Data >= (int)getHeaderLen()) return NULL; igmpv3_group_record* nextGroup = (igmpv3_group_record*)((uint8_t*)groupRecord + groupRecord->getRecordLen()); return nextGroup; } void IgmpV3ReportLayer::computeCalculateFields() { igmpv3_report_header* hdr = getReportHeader(); hdr->checksum = 0; hdr->checksum = htobe16(calculateChecksum()); } igmpv3_group_record* IgmpV3ReportLayer::addGroupRecordAt(uint8_t recordType, const IPv4Address& multicastAddress, const std::vector<IPv4Address>& sourceAddresses, int offset) { if (offset > (int)getHeaderLen()) { PCPP_LOG_ERROR("Cannot add group record, offset is out of layer bounds"); return NULL; } size_t groupRecordSize = sizeof(igmpv3_group_record) + sizeof(uint32_t)*sourceAddresses.size(); if (!extendLayer(offset, groupRecordSize)) { PCPP_LOG_ERROR("Cannot add group record, cannot extend layer"); return NULL; } uint8_t* groupRecordBuffer = new uint8_t[groupRecordSize]; memset(groupRecordBuffer, 0, groupRecordSize); igmpv3_group_record* newGroupRecord = (igmpv3_group_record*)groupRecordBuffer; newGroupRecord->multicastAddress = multicastAddress.toInt(); newGroupRecord->recordType = recordType; newGroupRecord->auxDataLen = 0; newGroupRecord->numOfSources = htobe16(sourceAddresses.size()); int srcAddrOffset = 0; for (std::vector<IPv4Address>::const_iterator iter = sourceAddresses.begin(); iter != sourceAddresses.end(); iter++) { memcpy(newGroupRecord->sourceAddresses + srcAddrOffset, iter->toBytes(), sizeof(uint32_t)); srcAddrOffset += sizeof(uint32_t); } memcpy(m_Data + offset, groupRecordBuffer, groupRecordSize); delete[] groupRecordBuffer; getReportHeader()->numOfGroupRecords = htobe16(getGroupRecordCount() + 1); return (igmpv3_group_record*)(m_Data + offset); } igmpv3_group_record* IgmpV3ReportLayer::addGroupRecord(uint8_t recordType, const IPv4Address& multicastAddress, const std::vector<IPv4Address>& sourceAddresses) { return addGroupRecordAt(recordType, multicastAddress, sourceAddresses, (int)getHeaderLen()); } igmpv3_group_record* IgmpV3ReportLayer::addGroupRecordAtIndex(uint8_t recordType, const IPv4Address& multicastAddress, const std::vector<IPv4Address>& sourceAddresses, int index) { int groupCnt = (int)getGroupRecordCount(); if (index < 0 || index > groupCnt) { PCPP_LOG_ERROR("Cannot add group record, index " << index << " out of bounds"); return NULL; } size_t offset = sizeof(igmpv3_report_header); igmpv3_group_record* curRecord = getFirstGroupRecord(); for (int i = 0; i < index; i++) { if (curRecord == NULL) { PCPP_LOG_ERROR("Cannot add group record, cannot find group record at index " << i); return NULL; } offset += curRecord->getRecordLen(); curRecord = getNextGroupRecord(curRecord); } return addGroupRecordAt(recordType, multicastAddress, sourceAddresses, (int)offset); } bool IgmpV3ReportLayer::removeGroupRecordAtIndex(int index) { int groupCnt = (int)getGroupRecordCount(); if (index < 0 || index >= groupCnt) { PCPP_LOG_ERROR("Cannot remove group record, index " << index << " is out of bounds"); return false; } size_t offset = sizeof(igmpv3_report_header); igmpv3_group_record* curRecord = getFirstGroupRecord(); for (int i = 0; i < index; i++) { if (curRecord == NULL) { PCPP_LOG_ERROR("Cannot remove group record at index " << index << ", cannot find group record at index " << i); return false; } offset += curRecord->getRecordLen(); curRecord = getNextGroupRecord(curRecord); } if (!shortenLayer((int)offset, curRecord->getRecordLen())) { PCPP_LOG_ERROR("Cannot remove group record at index " << index << ", cannot shorted layer"); return false; } getReportHeader()->numOfGroupRecords = htobe16(groupCnt-1); return true; } bool IgmpV3ReportLayer::removeAllGroupRecords() { int offset = (int)sizeof(igmpv3_report_header); if (!shortenLayer(offset, getHeaderLen()-offset)) { PCPP_LOG_ERROR("Cannot remove all group records, cannot shorted layer"); return false; } getReportHeader()->numOfGroupRecords = 0; return true; } /********************* * igmpv3_group_record *********************/ uint16_t igmpv3_group_record::getSourceAddressCount() const { return be16toh(numOfSources); } IPv4Address igmpv3_group_record::getSourceAddressAtIndex(int index) const { uint16_t numOfRecords = getSourceAddressCount(); if (index < 0 || index >= numOfRecords) return IPv4Address(); int offset = index * sizeof(uint32_t); const uint8_t* ptr = sourceAddresses + offset; return IPv4Address(*(uint32_t*)ptr); } size_t igmpv3_group_record::getRecordLen() const { uint16_t numOfRecords = getSourceAddressCount(); int headerLen = numOfRecords * sizeof(uint32_t) + sizeof(igmpv3_group_record); return (size_t)headerLen; } }
seladb/PcapPlusPlus
Packet++/src/IgmpLayer.cpp
C++
unlicense
14,266
#include "line_modification.hh" #include "buffer.hh" #include "unit_tests.hh" namespace Kakoune { static LineModification make_line_modif(const Buffer::Change& change) { LineCount num_added = 0, num_removed = 0; if (change.type == Buffer::Change::Insert) { num_added = change.end.line - change.begin.line; // inserted a new line at buffer end but end coord is on same line if (change.at_end and change.end.column != 0) ++num_added; } else { num_removed = change.end.line - change.begin.line; // removed last line, but end coord is on same line if (change.at_end and change.end.column != 0) ++num_removed; } // modified a line if (not change.at_end and (change.begin.column != 0 or change.end.column != 0)) { ++num_removed; ++num_added; } return { change.begin.line, change.begin.line, num_removed, num_added }; } Vector<LineModification> compute_line_modifications(const Buffer& buffer, size_t timestamp) { Vector<LineModification> res; for (auto& buf_change : buffer.changes_since(timestamp)) { auto change = make_line_modif(buf_change); auto pos = std::upper_bound(res.begin(), res.end(), change.new_line, [](const LineCount& l, const LineModification& c) { return l < c.new_line; }); if (pos != res.begin()) { auto& prev = *(pos-1); if (change.new_line <= prev.new_line + prev.num_added) { --pos; const LineCount removed_from_previously_added_by_pos = clamp(pos->new_line + pos->num_added - change.new_line, 0_line, std::min(pos->num_added, change.num_removed)); pos->num_removed += change.num_removed - removed_from_previously_added_by_pos; pos->num_added += change.num_added - removed_from_previously_added_by_pos; } else { change.old_line -= prev.diff(); pos = res.insert(pos, change); } } else pos = res.insert(pos, change); auto next = pos + 1; auto diff = buf_change.end.line - buf_change.begin.line; if (buf_change.type == Buffer::Change::Erase) { auto delend = std::upper_bound(next, res.end(), change.new_line + change.num_removed, [](const LineCount& l, const LineModification& c) { return l < c.new_line; }); for (auto it = next; it != delend; ++it) { const LineCount removed_from_previously_added_by_it = std::min(it->num_added, change.new_line + change.num_removed - it->new_line); pos->num_removed += it->num_removed - removed_from_previously_added_by_it; pos->num_added += it->num_added - removed_from_previously_added_by_it; } next = res.erase(next, delend); for (auto it = next; it != res.end(); ++it) it->new_line -= diff; } else { for (auto it = next; it != res.end(); ++it) it->new_line += diff; } } return res; } bool operator==(const LineModification& lhs, const LineModification& rhs) { return std::tie(lhs.old_line, lhs.new_line, lhs.num_removed, lhs.num_added) == std::tie(rhs.old_line, rhs.new_line, rhs.num_removed, rhs.num_added); } UnitTest test_line_modifications{[]() { { Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\n"); auto ts = buffer.timestamp(); buffer.erase(buffer.iterator_at({1, 0}), buffer.iterator_at({2, 0})); auto modifs = compute_line_modifications(buffer, ts); kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 1 COMMA 1 COMMA 1 COMMA 0 }); } { Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\n"); auto ts = buffer.timestamp(); buffer.insert(buffer.iterator_at({1, 7}), "line 3"); auto modifs = compute_line_modifications(buffer, ts); kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 2 COMMA 2 COMMA 0 COMMA 1 }); } { Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\nline 3\n"); auto ts = buffer.timestamp(); buffer.insert(buffer.iterator_at({1, 4}), "hoho\nhehe"); buffer.erase(buffer.iterator_at({0, 0}), buffer.iterator_at({1, 0})); auto modifs = compute_line_modifications(buffer, ts); kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 2 COMMA 2 }); } { Buffer buffer("test", Buffer::Flags::None, "line 1\nline 2\nline 3\nline 4\n"); auto ts = buffer.timestamp(); buffer.erase(buffer.iterator_at({0,0}), buffer.iterator_at({3,0})); buffer.insert(buffer.iterator_at({1,0}), "newline 1\nnewline 2\nnewline 3\n"); buffer.erase(buffer.iterator_at({0,0}), buffer.iterator_at({1,0})); { auto modifs = compute_line_modifications(buffer, ts); kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 4 COMMA 3 }); } buffer.insert(buffer.iterator_at({3,0}), "newline 4\n"); { auto modifs = compute_line_modifications(buffer, ts); kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 4 COMMA 4 }); } } { Buffer buffer("test", Buffer::Flags::None, "line 1\n"); auto ts = buffer.timestamp(); buffer.insert(buffer.iterator_at({0,0}), "n"); buffer.insert(buffer.iterator_at({0,1}), "e"); buffer.insert(buffer.iterator_at({0,2}), "w"); auto modifs = compute_line_modifications(buffer, ts); kak_assert(modifs.size() == 1 && modifs[0] == LineModification{ 0 COMMA 0 COMMA 1 COMMA 1 }); } }}; }
alpha123/kakoune
src/line_modification.cc
C++
unlicense
6,123
#ifndef __NETWORKBALANCER_HPP #define __NETWORKBALANCER_HPP #include <stdlib.h> namespace Network { class NetworkBalancer { public: /** * @brief NetworkBalancer Class constructor */ NetworkBalancer(); /** * @brief sendTroughBalancer Sends a buffer through an automatically chosen output channel, * trying to balance the output * @param Buffer Reference to buffer to be sent * @param length Length of buffer * @return Output channel chosen */ int sendTroughBalancer( const char *Buffer, int length ); /* @brief Total number of output channels */ const static int MAX_OUTPUTS = 4; private: /** * @brief calculateOutputChannel Calculates an output channel following the strategy * stated in this class * @return Calculated output channel, a number between 1 and 4 */ int calculateOutputChannel(); private: /** * @brief The BALANCE_STRATEGY enum Enumerated class containing the strategies that can be * chosen for this class to produce the output */ enum class BALANCE_STRATEGY { ROUNDROBIN4, RANDOM }; /* @brief theLastOutput Contains the last chosen channel */ int theLastOutput; /* @brief theChosenStrategy Currently chosen strategy */ BALANCE_STRATEGY theChosenStrategy; }; } #endif // __NETWORKBALANCER_HPP
magfernandez/TIDTest
src/Network/NetworkBalancer.hpp
C++
unlicense
1,492
/** * This is a demo class * * @author Ravi */ public class Demo { /** * This is the main method * * @param args */ public static void main(String[] args) { System.out.println("This is a demo."); } }
PatchRowcester/LearningJava
Demo/src/Demo.java
Java
unlicense
239
energies = dict() energies[81] = -3.17 # Ammoniadimer.xyz energies[82] = -5.02 # Waterdimer.xyz energies[83] = -1.50 # BenzeneMethanecomplex.xyz energies[84] = -18.61 # Formicaciddimer.xyz energies[85] = -15.96 # Formamidedimer.xyz energies[86] = -20.65 # Uracildimerhbonded.xyz energies[87] = -16.71 # 2pyridoxine2aminopyridinecomplex.xyz energies[88] = -16.37 # AdeninethymineWatsonCrickcomplex.xyz energies[89] = -0.53 # Methanedimer.xyz energies[90] = -1.51 # Ethenedimer.xyz energies[91] = -2.73 # Benzenedimerparalleldisplaced.xyz energies[92] = -4.42 # Pyrazinedimer.xyz energies[93] = -10.12 # Uracildimerstack.xyz energies[94] = -5.22 # Indolebenzenecomplexstack.xyz energies[95] = -12.23 # Adeninethyminecomplexstack.xyz energies[96] = -1.53 # Etheneethynecomplex.xyz energies[97] = -3.28 # Benzenewatercomplex.xyz energies[98] = -2.35 # Benzeneammoniacomplex.xyz energies[99] = -4.46 # BenzeneHCNcomplex.xyz energies[100] = -2.74 # BenzenedimerTshaped.xyz energies[101] = -5.73 # IndolebenzeneTshapecomplex.xyz energies[102] = -7.05 # Phenoldimer.xyz names = dict() names[81] = "Ammoniadimer.xyz" names[82] = "Waterdimer.xyz" names[83] = "BenzeneMethanecomplex.xyz" names[84] = "Formicaciddimer.xyz" names[85] = "Formamidedimer.xyz" names[86] = "Uracildimerhbonded.xyz" names[87] = "2pyridoxine2aminopyridinecomplex.xyz" names[88] = "AdeninethymineWatsonCrickcomplex.xyz" names[89] = "Methanedimer.xyz" names[90] = "Ethenedimer.xyz" names[91] = "Benzenedimerparalleldisplaced.xyz" names[92] = "Pyrazinedimer.xyz" names[93] = "Uracildimerstack.xyz" names[94] = "Indolebenzenecomplexstack.xyz" names[95] = "Adeninethyminecomplexstack.xyz" names[96] = "Etheneethynecomplex.xyz" names[97] = "Benzenewatercomplex.xyz" names[98] = "Benzeneammoniacomplex.xyz" names[99] = "BenzeneHCNcomplex.xyz" names[100] = "BenzenedimerTshaped.xyz" names[101] = "IndolebenzeneTshapecomplex.xyz" names[102] = "Phenoldimer.xyz"
andersx/s22-charmm
structures/ref.py
Python
unlicense
2,038
export class InvalidTimeValueError extends Error { constructor(unit: string, providedValue: number) { super(`Cannot create a valid time with provided ${unit} value: ${providedValue}`); } }
rizadh/scheduler
src/InvalidTimeValueError.ts
TypeScript
unlicense
197
avatar = function(x){ this.x = x; this.y = 0; this.prevY = 0; this.velocity_x = 0; this.velocity_y = 0; this.img = loadImage("stickman.png"); this.crouch = loadImage("crouch.png"); this.width = 16; this.standingHeight=64; this.crouchHeight=44; this.height = this.standingHeight; this.collisionCheck = []; }; avatar.prototype.addCollisionCheck = function(item){ this.collisionCheck.push(item); //console.log("add "+item); } avatar.prototype.removeCollisionCheck = function(item){ this.collisionCheck.splice( this.collisionCheck.indexOf(item), 1); //console.log("remove mushroom"); } avatar.prototype.platformCheck = function(){ this.talajon=false; if(this.y<=0){ this.y=0; this.velocity_y=0; this.talajon=true; } for(var i in elements.es){ if(elements.es[i] instanceof platform){ var p=elements.es[i]; if(p.x<this.x +this.width && p.x+p.width > this.x){ if(this.prevY>=p.y && this.y<=p.y){ this.y=p.y; this.velocity_y=0; this.talajon=true; } } } } } avatar.prototype.death = function(){ new Audio(explosionSound.src).play(); life--; lifeText.text = "Life: "+life; if(life <= 0) gameOver(); this.x = 0; this.y = 0; } avatar.prototype.spikeCheck = function(){ for(var i in elements.es){ if(elements.es[i] instanceof spike){ var p=elements.es[i]; if(p.x<this.x +this.width && p.x+p.width > this.x){ /*console.log("player.y = "+this.y); console.log("spike.y = "+p.y); console.log("spike.height = "+p.height); console.log("player.height = "+this.height);*/ if(p.y<this.y+this.height && p.y+p.height-3 > this.y){ this.death(); } } } } } avatar.prototype.mushroomCheck = function(){ for(var i in elements.es){ if(elements.es[i] instanceof mushroom){ var p=elements.es[i]; if(p.x<=this.x +this.width && p.x+p.width >= this.x){ /*console.log("player.y = "+this.y); console.log("spike.y = "+p.y); console.log("spike.height = "+p.height); console.log("player.height = "+this.height);*/ if(p.y<=this.y+this.height && p.y+p.height >= this.y){ if(this.prevY>p.y+p.height) { p.death(); }else { this.death(); } } } } } } avatar.prototype.logic = function(){ var speedX = 5; if(keys[KEY_RIGHT]){ this.x += speedX; }if(keys[KEY_LEFT]){ this.x -= speedX; } this.prevY = this.y; this.y += this.velocity_y; if(keys[KEY_UP] && this.talajon){ this.velocity_y = 14; this.y += 0.001; } this.platformCheck(); //this.spikeCheck(); //this.mushroomCheck(); //collision Test for(var i in this.collisionCheck){ var p = this.collisionCheck[i]; if(p.x<this.x +this.width && p.x+p.width > this.x){ if(p.y<this.y+this.height && p.y+p.height > this.y){ p.collide(this); } } } if(!this.talajon){ this.velocity_y-=1; } if(keys[KEY_DOWN]){ this.currentImg=this.crouch; this.height=this.crouchHeight; }else{ this.currentImg=this.img; this.height=this.standingHeight; } }; avatar.prototype.draw=function(context, t){ context.drawImage(this.currentImg, t.tX(this.x), t.tY(this.y)-this.standingHeight); };
rizsi/szakkor2014
orak/sa-23/avatar.js
JavaScript
unlicense
3,166
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * SYSTEM/FS/FAT.H * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef FAT_H_INCLUDED #define FAT_H_INCLUDED #include <FORMATTING.H> typedef struct _FAT121632_BPB { uint8_t OEMName[8]; uint16_t BytesPerSector; uint8_t SectorsPerCluster; uint16_t ReservedSectors; uint8_t NumberOfFats; uint16_t NumDirEntries; uint16_t NumSectors; uint8_t Media; uint16_t SectorsPerFat; uint16_t SectorsPerTrack; uint16_t HeadsPerCyl; uint32_t HiddenSectors; uint32_t LongSectors; }__attribute__((packed)) FATBPB, *PFATBPB; typedef struct _FAT1216_BPB_EXT { uint8_t DriveNumber; uint8_t Flags; uint8_t Signiture; uint32_t Serial; char VolumeLable[11]; char SysIDString[8]; }__attribute__((packed)) FAT1216BPBEXT, *PFAT1216BPBEXT; typedef struct _FAT32_BPB_EXT { uint32_t SectorsPerFat32; uint16_t Flags; uint16_t Version; uint32_t RootCluster; uint16_t InfoCluster; uint16_t BackupBoot; uint16_t Reserved[6]; uint8_t DriveNumber; uint8_t flag; uint8_t Signiture; uint32_t Serial; char VolumeLable[11]; char SysIDString[8]; }__attribute__((packed)) FAT32BPBEXT, *PFAT32BPBEXT; typedef struct _FAT1216_BS { uint8_t Ignore[3]; //first 3 bytes are ignored FATBPB Bpb; FAT1216BPBEXT BpbExt; uint8_t Filler[448]; //needed to make struct 512 bytes uint16_t BootSig; }__attribute__((packed)) FAT1216BS, *PFAT1216BS; typedef struct _FAT32_BS { uint8_t Ignore[3]; //first 3 bytes are ignored FATBPB Bpb; FAT32BPBEXT BpbExt; uint8_t Filler[420]; //needed to make struct 512 bytes uint16_t BootSig; }__attribute__((packed)) FAT32BS, *PFAT32BS; typedef struct _FAT_DIRECTORY { uint8_t Filename[11]; uint8_t Attrib; uint8_t Reserved; uint8_t TimeCreatedMs; uint16_t TimeCreated; uint16_t DateCreated; uint16_t DateLastAccessed; uint16_t FirstClusterHiBytes; uint16_t LastModTime; uint16_t LastModDate; uint16_t FirstCluster; uint32_t FileSize; }__attribute__((packed)) FATDIR, *PFATDIR; typedef struct _FAT_DIR_SECTOR { FATDIR DIRENT[16]; } DIRSEC, *PDIRSEC; typedef struct _TEMP_DIR { DIRSEC Sector[4096]; } TDIR, *PTDIR; void _FAT_init(void); #endif
basicfreak/BOS
0.0.1/SRC/SYSTEM/FS/FAT.H
C++
unlicense
2,287
#include "Union.h" bool Union::contains(const Vector2D& point) const { for (auto&& figure : figures) if (figure->contains(point)) return true; return false; } Figure* Union::createCopy() const { return new Union(*this); } std::ostream &operator<<(std::ostream& os, const Union* un) { return un->serializeFigures(os); } std::istream &operator>>(std::istream& is, Union*& un) { std::vector<Figure*> figures = FigureGroup::unserializeFigures(is); un = new Union(figures); return is; }
Lyrositor/insa
3if/oo/tp-oo_4/src/Union.cpp
C++
unlicense
535
#include "com_object.hpp" #include <Windows.h> namespace pw { com_object::com_object() { CoInitializeEx(nullptr, COINIT_MULTITHREADED); } com_object::~com_object() { CoUninitialize(); } }
phwitti/cmdhere
src/base/com_object.cpp
C++
unlicense
231
package crashreporter.api; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Registry for API provider objects. * * @author Richard */ public class Registry { private static final Map<String, PastebinProvider> pastebinProviders = new HashMap<String, PastebinProvider>(); private static final Map<String, Class<? extends NotificationProvider>> notificationProviders = new HashMap<String, Class<? extends NotificationProvider>>(); /** * Register a {@link PastebinProvider}. * * @param id ID name for the provider, used in the config file * @param provider The provider */ public static void registerPastebinProvider(String id, PastebinProvider provider) { if (pastebinProviders.containsKey(id)) throw new IllegalArgumentException("Pastebin provider " + id + " already registered by " + pastebinProviders.get(id) + " when registering " + provider); pastebinProviders.put(id, provider); } /** * Get a {@link PastebinProvider} by its ID. * * @param id ID name for the provider * @return The provider, or null if there is no such provider */ public static PastebinProvider getPastebinProvider(String id) { return pastebinProviders.get(id); } /** * Get a list of {@link PastebinProvider}s, the first one being the user's preferred pastebin. * * @return List of providers */ public static List<PastebinProvider> getPastebinProviders() { List<PastebinProvider> providers = new ArrayList<PastebinProvider>(pastebinProviders.size()); // first the preferred one PastebinProvider preferred = CallHandler.instance.getPastebin(); if (preferred != null) providers.add(preferred); // then the rest providers.addAll(pastebinProviders.values()); return providers; } /** * Get a map of all {@link PastebinProvider}s, in no particular order. * * @return Map of providers */ public static Map<String, PastebinProvider> getAllPastebinProviders() { return Collections.unmodifiableMap(pastebinProviders); } /** * Register a {@link NotificationProvider} class. * * @param id ID name for the provider, used in the config file * @param provider The provider class */ public static void registerNotificationProvider(String id, Class<? extends NotificationProvider> provider) { if (notificationProviders.containsKey(id)) throw new IllegalArgumentException("Notification provider " + id + " already registered by " + notificationProviders.get(id) + " when registering " + provider); notificationProviders.put(id, provider); } /** * Get a {@link NotificationProvider} class by its ID. * * @param id ID name for the provider class * @return The provider class, or null if there is no such provider */ public static Class<? extends NotificationProvider> getNotificationProvider(String id) { return notificationProviders.get(id); } /** * Get a list of {@link NotificationProvider} classes. * * @return List of provider classes * @see CallHandler#getActiveNotificationProviders() */ public static List<Class<? extends NotificationProvider>> getNotificationProviders() { List<Class<? extends NotificationProvider>> providers = new ArrayList<Class<? extends NotificationProvider>>(notificationProviders.size()); providers.addAll(notificationProviders.values()); return providers; } /** * Get a map of all {@link NotificationProvider} classes. * * @return Map of provider classes * @see CallHandler#getActiveNotificationProviders() */ public static Map<String, Class<? extends NotificationProvider>> getAllNotificationProviders() { return Collections.unmodifiableMap(notificationProviders); } }
richardg867/CrashReporter
src/crashreporter/api/Registry.java
Java
unlicense
3,754
package gui.dragndrop; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.Stage; public class DragAndDrop extends Application { public void start(Stage stage) { AnchorPane root = new AnchorPane(); Label source = new Label("DRAG ME"); source.setLayoutX(50); source.setLayoutY(100); source.setScaleX(2.0); source.setScaleY(2.0); root.getChildren().add(source); Label target = new Label("DROP HERE"); target.setLayoutX(250); target.setLayoutY(100); target.setScaleX(2.0); target.setScaleY(2.0); root.getChildren().add(target); source.setOnDragDetected(e->onDragDetected(e)); target.setOnDragOver(e->onDragOver(e)); target.setOnDragEntered(e->onDragEntered(e)); target.setOnDragExited(e->onDragExited(e)); target.setOnDragDropped(e->onDragDropped(e)); source.setOnDragDone(e->onDragDone(e)); Scene scene = new Scene(root, 400, 200); stage.setScene(scene); stage.setTitle("Drag and Drop"); stage.show(); } private void onDragDetected(MouseEvent e) { System.out.println("onDragDetected"); Label source = (Label)e.getSource(); Dragboard db = source.startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString(source.getText()); db.setContent(content); } private void onDragOver(DragEvent e) { System.out.println("onDragOver"); Label target = (Label)e.getSource(); if(e.getGestureSource() != target && e.getDragboard().hasString()) { e.acceptTransferModes(TransferMode.COPY_OR_MOVE); } } private void onDragEntered(DragEvent e) { System.out.println("onDragEntered"); Label target = (Label)e.getSource(); if(e.getGestureSource() != target && e.getDragboard().hasString()) { target.setTextFill(Color.RED); } } private void onDragExited(DragEvent e) { System.out.println("onDragExited"); Label target = (Label)e.getSource(); target.setTextFill(Color.BLACK); } private void onDragDropped(DragEvent e) { System.out.println("onDragDropped"); Label target = (Label)e.getSource(); Dragboard db = e.getDragboard(); boolean success = false; if(db.hasString()) { target.setText(db.getString()); success = true; } e.setDropCompleted(success); } private void onDragDone(DragEvent e) { System.out.println("onDragDone"); Label source = (Label)e.getSource(); if (e.getTransferMode() == TransferMode.MOVE) { source.setText(""); } } public static void main(String[] args) { launch(args); } }
KonstantinTwardzik/Graphical-User-Interfaces
CodeExamples/src/gui/dragndrop/DragAndDrop.java
Java
unlicense
3,091
var leaderboard2 = function(data) { return data.data.sort(function(a,b){return b.points-a.points;}); }; function liCreate(name,points) { var li = $('<li>'+name+'</li>'); li.append('<span>'+points+'</span>'); } $(document).ready(function() { // var sorted = leaderboard2(data); // for (var i=0; i<sorted.length; i++) { // $('body').append('<div><p>'+sorted[i].name+' '+sorted[i].points+'</p></div>') // } // //problem here is with repeated DOM manipulation var studentArray = []; $.getJSON('http://192.168.1.35:8000/data.json').success(function(data){ //using '$.getJSON' as opposed to $.ajax specifies //also, include both success and error handler to account for asynchrony. //i.e., if/when SUCCESS, execute some code block; if ERROR, execute another. console.log(data); var sorted = leaderboard2(data); for (var i=0; i<sorted.length; i++) { var student = ('<div><p>'+sorted[i].name+' '+sorted[i].points+'</p></div>'); studentArray.push(student); } //^^ FIXED!!! Append entire array ^^ console.log(studentArray); $('body').append(studentArray); }) .error(function(error){ console.log(error); }); });
sherylpeebee/redditClone
own-playground/karma/script.js
JavaScript
unlicense
1,196
package lcd2usb import ( "errors" "fmt" "github.com/schleibinger/sio" ) type cmd byte const ( cmdPrefix cmd = 0xfe cmdBacklightOn = 0x42 cmdBacklightOff = 0x46 cmdBrightnes = 0x99 // brightnes cmdContrast = 0x50 // contrast cmdAutoscrollOn = 0x51 cmdAutoscrollOff = 0x52 cmdClearScreen = 0x58 cmdChangeSplash = 0x40 // Write number of chars for splash cmdCursorPosition = 0x47 // x, y cmdHome = 0x48 cmdCursorBack = 0x4c cmdCursorForward = 0x4d cmdUnderlineOn = 0x4a cmdUnderlineOff = 0x4b cmdBlockOn = 0x53 cmdBlockOff = 0x54 cmdBacklightColor = 0xd0 // r, g, b cmdLCDSize = 0xd1 // cols, rows cmdCreateChar = 0x4e cmdSaveChar = 0xc1 cmdLoadChar = 0xc0 ) type Device struct { rows uint8 cols uint8 p *sio.Port } func Open(name string, rows, cols uint8) (*Device, error) { p, err := sio.Open(name, 9600) if err != nil { return nil, err } d := &Device{ rows: rows, cols: cols, p: p, } if err = d.send(cmdLCDSize, cols, rows); err != nil { return nil, err } return d, nil } func (d *Device) Close() error { if d.p != nil { err := d.p.Close() d.p = nil return err } return nil } func (d *Device) Write(buf []byte) (n int, err error) { if d.p == nil { return 0, errors.New("writing to closed deviced") } return d.p.Write(buf) } func (d *Device) send(c cmd, args ...byte) error { _, err := d.Write(append([]byte{byte(cmdPrefix), byte(c)}, args...)) return err } func (d *Device) Backlight(on bool) error { if on { return d.send(cmdBacklightOn) } else { return d.send(cmdBacklightOff) } } func (d *Device) Brightnes(set uint8) error { return d.send(cmdBrightnes, set) } func (d *Device) Contrast(set uint8) error { return d.send(cmdContrast, set) } func (d *Device) Autoscroll(on bool) error { if on { return d.send(cmdAutoscrollOn) } else { return d.send(cmdAutoscrollOff) } } func (d *Device) Clear() error { return d.send(cmdClearScreen) } func (d *Device) ChangeSplash(set []byte) error { cells := int(d.rows) * int(d.cols) if len(set) > cells { return fmt.Errorf("wrong number of characters: expected %d", cells) } return d.send(cmdChangeSplash, set...) } func (d *Device) CursorPosition(x, y uint8) error { if x > d.cols || y > d.rows { return fmt.Errorf("setting cursor out of bounds") } return d.send(cmdCursorPosition, x, y) } func (d *Device) Home() error { return d.send(cmdHome) } func (d *Device) CursorBack() error { return d.send(cmdCursorBack) } func (d *Device) CursorForward() error { return d.send(cmdCursorForward) } func (d *Device) Underline(on bool) error { if on { return d.send(cmdUnderlineOn) } else { return d.send(cmdUnderlineOff) } } func (d *Device) Block(on bool) error { if on { return d.send(cmdBlockOn) } else { return d.send(cmdBlockOff) } } func (d *Device) Color(r, g, b uint8) error { return d.send(cmdBacklightColor, r, g, b) }
Merovius/go-misc
lcd2usb/main.go
GO
unlicense
3,074
public class Student { private String namn; private int födelseår, status, id; public Student(){} public String getNamn() { return namn; } public void setNamn(String nyNamn) { namn=nyNamn; } public int getId() { return id; } public void setId(int nyId) { id=nyId; } public int getStatus() { return status; } public void setStatus(int nyStatus) { status=nyStatus; } public int getFödelseår() { return födelseår; } public void setFödelseår(int nyFödelseår) { födelseår=nyFödelseår; } public String print() { return namn+"\t"+id+"\t"+födelseår; } }
andreasaronsson/introduktion_till_informatik
tebrakod/Student.java
Java
apache-2.0
589
package com.jerry.controller; import com.jerry.model.TBanquet; import com.jerry.service.BanquetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/banquet") public class BanquetController { @Autowired BanquetService banquetService; @GetMapping("/listBanquetByRestaurantId") public List<TBanquet> listBanquetByRestaurantId(String restaurantId) { return banquetService.listBanquetByRestaurantId(restaurantId); } @GetMapping("/findOne") public TBanquet findOne(String banquetId) { return banquetService.findOne(banquetId); } }
luoyefeiwu/learn_java
jpa/src/main/java/com/jerry/controller/BanquetController.java
Java
apache-2.0
840
/*! * Ext JS Library 3.4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.dd.DragTracker * @extends Ext.util.Observable * A DragTracker listens for drag events on an Element and fires events at the start and end of the drag, * as well as during the drag. This is useful for components such as {@link Ext.slider.MultiSlider}, where there is * an element that can be dragged around to change the Slider's value. * DragTracker provides a series of template methods that should be overridden to provide functionality * in response to detected drag operations. These are onBeforeStart, onStart, onDrag and onEnd. * See {@link Ext.slider.MultiSlider}'s initEvents function for an example implementation. */ Ext.dd.DragTracker = Ext.extend(Ext.util.Observable, { /** * @cfg {Boolean} active * Defaults to <tt>false</tt>. */ active: false, /** * @cfg {Number} tolerance * Number of pixels the drag target must be moved before dragging is considered to have started. Defaults to <tt>5</tt>. */ tolerance: 5, /** * @cfg {Boolean/Number} autoStart * Defaults to <tt>false</tt>. Specify <tt>true</tt> to defer trigger start by 1000 ms. * Specify a Number for the number of milliseconds to defer trigger start. */ autoStart: false, constructor : function(config){ Ext.apply(this, config); this.addEvents( /** * @event mousedown * @param {Object} this * @param {Object} e event object */ 'mousedown', /** * @event mouseup * @param {Object} this * @param {Object} e event object */ 'mouseup', /** * @event mousemove * @param {Object} this * @param {Object} e event object */ 'mousemove', /** * @event dragstart * @param {Object} this * @param {Object} e event object */ 'dragstart', /** * @event dragend * @param {Object} this * @param {Object} e event object */ 'dragend', /** * @event drag * @param {Object} this * @param {Object} e event object */ 'drag' ); this.dragRegion = new Ext.lib.Region(0,0,0,0); if(this.el){ this.initEl(this.el); } Ext.dd.DragTracker.superclass.constructor.call(this, config); }, initEl: function(el){ this.el = Ext.get(el); el.on('mousedown', this.onMouseDown, this, this.delegate ? {delegate: this.delegate} : undefined); }, destroy : function(){ this.el.un('mousedown', this.onMouseDown, this); delete this.el; }, onMouseDown: function(e, target){ if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){ this.startXY = this.lastXY = e.getXY(); this.dragTarget = this.delegate ? target : this.el.dom; if(this.preventDefault !== false){ e.preventDefault(); } Ext.getDoc().on({ scope: this, mouseup: this.onMouseUp, mousemove: this.onMouseMove, selectstart: this.stopSelect }); if(this.autoStart){ this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this, [e]); } } }, onMouseMove: function(e, target){ // HACK: IE hack to see if button was released outside of window. */ if(this.active && Ext.isIE && !e.browserEvent.button){ e.preventDefault(); this.onMouseUp(e); return; } e.preventDefault(); var xy = e.getXY(), s = this.startXY; this.lastXY = xy; if(!this.active){ if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){ this.triggerStart(e); }else{ return; } } this.fireEvent('mousemove', this, e); this.onDrag(e); this.fireEvent('drag', this, e); }, onMouseUp: function(e) { var doc = Ext.getDoc(), wasActive = this.active; doc.un('mousemove', this.onMouseMove, this); doc.un('mouseup', this.onMouseUp, this); doc.un('selectstart', this.stopSelect, this); e.preventDefault(); this.clearStart(); this.active = false; delete this.elRegion; this.fireEvent('mouseup', this, e); if(wasActive){ this.onEnd(e); this.fireEvent('dragend', this, e); } }, triggerStart: function(e) { this.clearStart(); this.active = true; this.onStart(e); this.fireEvent('dragstart', this, e); }, clearStart : function() { if(this.timer){ clearTimeout(this.timer); delete this.timer; } }, stopSelect : function(e) { e.stopEvent(); return false; }, /** * Template method which should be overridden by each DragTracker instance. Called when the user first clicks and * holds the mouse button down. Return false to disallow the drag * @param {Ext.EventObject} e The event object */ onBeforeStart : function(e) { }, /** * Template method which should be overridden by each DragTracker instance. Called when a drag operation starts * (e.g. the user has moved the tracked element beyond the specified tolerance) * @param {Ext.EventObject} e The event object */ onStart : function(xy) { }, /** * Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected. * @param {Ext.EventObject} e The event object */ onDrag : function(e) { }, /** * Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed * (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button) * @param {Ext.EventObject} e The event object */ onEnd : function(e) { }, /** * Returns the drag target * @return {Ext.Element} The element currently being tracked */ getDragTarget : function(){ return this.dragTarget; }, getDragCt : function(){ return this.el; }, getXY : function(constrain){ return constrain ? this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY; }, getOffset : function(constrain){ var xy = this.getXY(constrain), s = this.startXY; return [s[0]-xy[0], s[1]-xy[1]]; }, constrainModes: { 'point' : function(xy){ if(!this.elRegion){ this.elRegion = this.getDragCt().getRegion(); } var dr = this.dragRegion; dr.left = xy[0]; dr.top = xy[1]; dr.right = xy[0]; dr.bottom = xy[1]; dr.constrainTo(this.elRegion); return [dr.left, dr.top]; } } });
ahwxl/cms
icms/src/main/webapp/res/extjs/src/dd/DragTracker.js
JavaScript
apache-2.0
7,637
<?php /** * @link https://www.humhub.org/ * @copyright Copyright (c) 2015 HumHub GmbH & Co. KG * @license https://www.humhub.com/licences */ namespace humhub\modules\content\widgets; /** * Delete Link for Wall Entries * * This widget will attached to the WallEntryControlsWidget and displays * the "Delete" Link to the Content Objects. * * @package humhub.modules_core.wall.widgets * @since 0.5 */ class DeleteLink extends \yii\base\Widget { /** * @var \humhub\modules\content\components\ContentActiveRecord */ public $content = null; /** * Executes the widget. */ public function run() { if ($this->content->content->canDelete()) { return $this->render('deleteLink', array( 'model' => $this->content->content->object_model, 'id' => $this->content->content->object_id )); } } } ?>
calonso-conabio/intranet
protected/humhub/modules/content/widgets/DeleteLink.php
PHP
apache-2.0
931
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package net.gcolin.jmx.console.embedded; import net.gcolin.jmx.console.JmxHtml; import net.gcolin.jmx.console.JmxProcessException; import net.gcolin.jmx.console.JmxResult; import net.gcolin.jmx.console.JmxTool; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A Jmx servlet with bootstrap style. * * @author Gael COLIN * */ public class BootStrapJmxServlet extends HttpServlet { private static final long serialVersionUID = 7998004606230901933L; protected transient JmxTool tool; protected transient JmxHtml html; @Override public void init() throws ServletException { tool = new JmxTool(); html = new JmxHtml() { protected String getButtonCss() { return "btn btn-primary"; } protected String getInputTextClass() { return "form-control"; } protected String getFormClass() { return "form-inline"; } protected String getSelectClass() { return "form-control"; } protected String getMenuUlClass() { return "menu"; } @Override protected String getTableClass() { return "table table-bordered"; } protected void writeCss(Writer writer) throws IOException { writer.write("<link href=\"/css/bootstrap.min.css\" rel=\"stylesheet\" />"); writer.write("<link href=\"/css/bootstrap-theme.min.css\" rel=\"stylesheet\" />"); writer.write("<style type='text/css'>.menu li.active>a{font-weight:bold}" + ".col{display:table-cell}.space{padding-left:16px;}</style>"); } }; } @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, String> parameters = new HashMap<String, String>(); for (Object elt : req.getParameterMap().entrySet()) { Entry<String, String[]> entry = (Entry<String, String[]>) elt; parameters.put(entry.getKey(), entry.getValue()[0]); } JmxResult result; try { result = tool.build(parameters); } catch (JmxProcessException ex) { throw new ServletException(ex); } result.setRequestUri(req.getRequestURI()); result.setQueryParams(req.getQueryString()); resp.setContentType("text/html"); html.write(result, parameters, resp.getWriter()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
gcolin/jmx-web-console
jmx-embedded/src/main/java/net/gcolin/jmx/console/embedded/BootStrapJmxServlet.java
Java
apache-2.0
3,657
/** * Copyright 2014 TangoMe Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tango.logstash.flume.redis.sink.serializer; import org.apache.flume.Event; import org.apache.flume.conf.Configurable; import org.apache.flume.conf.ConfigurableComponent; public interface Serializer extends Configurable, ConfigurableComponent { /** * Serialize an event for storage in Redis * * @param event * Event to serialize * @return Serialized data */ byte[] serialize(Event event) throws RedisSerializerException; }
DevOps-TangoMe/flume-redis
flume-redis-sink/src/main/java/com/tango/logstash/flume/redis/sink/serializer/Serializer.java
Java
apache-2.0
1,070
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * Classic splitter of OutputStream. Named after the unix 'tee' * command. It allows a stream to be branched off so there * are now two streams. * */ public class TeeOutputStream extends ProxyOutputStream { /** the second OutputStream to write to */ protected OutputStream branch; //TODO consider making this private /** * Constructs a TeeOutputStream. * @param out the main OutputStream * @param branch the second OutputStream */ public TeeOutputStream(final OutputStream out, final OutputStream branch) { super(out); this.branch = branch; } /** * Write the bytes to both streams. * @param b the bytes to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(final byte[] b) throws IOException { super.write(b); this.branch.write(b); } /** * Write the specified bytes to both streams. * @param b the bytes to write * @param off The start offset * @param len The number of bytes to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(final byte[] b, final int off, final int len) throws IOException { super.write(b, off, len); this.branch.write(b, off, len); } /** * Write a byte to both streams. * @param b the byte to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(final int b) throws IOException { super.write(b); this.branch.write(b); } /** * Flushes both streams. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { super.flush(); this.branch.flush(); } /** * Closes both output streams. * * If closing the main output stream throws an exception, attempt to close the branch output stream. * * If closing the main and branch output streams both throw exceptions, which exceptions is thrown by this method is * currently unspecified and subject to change. * * @throws IOException * if an I/O error occurs */ @Override public void close() throws IOException { try { super.close(); } finally { this.branch.close(); } } }
pimtegelaar/commons-io-test3
src/main/java/org/apache/commons/io/output/TeeOutputStream.java
Java
apache-2.0
3,320
package org.renjin.primitives; import org.renjin.eval.Context; import org.renjin.eval.EvalException; import org.renjin.primitives.annotations.processor.ArgumentException; import org.renjin.primitives.annotations.processor.ArgumentIterator; import org.renjin.primitives.annotations.processor.WrapperRuntime; import org.renjin.primitives.files.Files; import org.renjin.sexp.BuiltinFunction; import org.renjin.sexp.DoubleVector; import org.renjin.sexp.Environment; import org.renjin.sexp.FunctionCall; import org.renjin.sexp.IntVector; import org.renjin.sexp.LogicalVector; import org.renjin.sexp.PairList; import org.renjin.sexp.SEXP; import org.renjin.sexp.StringVector; public class R$primitive$file$access extends BuiltinFunction { public R$primitive$file$access() { super("file.access"); } public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) { try { ArgumentIterator argIt = new ArgumentIterator(context, environment, args); SEXP s0 = argIt.evalNext(); SEXP s1 = argIt.evalNext(); if (!argIt.hasNext()) { return this.doApply(context, environment, s0, s1); } throw new EvalException("file.access: too many arguments, expected at most 2."); } catch (ArgumentException e) { throw new EvalException(context, "Invalid argument: %s. Expected:\n\tfile.access(character, integer(1))", e.getMessage()); } catch (EvalException e) { e.initContext(context); throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new EvalException(e); } } public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) { try { if ((args.length) == 2) { return doApply(context, environment, args[ 0 ], args[ 1 ]); } } catch (EvalException e) { e.initContext(context); throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new EvalException(e); } throw new EvalException("file.access: max arity is 2"); } public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) { return R$primitive$file$access.doApply(context, environment, call, argNames, args); } public static SEXP doApply(Context context, Environment environment, SEXP arg0, SEXP arg1) throws Exception { if ((arg0 instanceof StringVector)&&(((arg1 instanceof IntVector)||(arg1 instanceof DoubleVector))||(arg1 instanceof LogicalVector))) { return Files.fileAccess(context, ((StringVector) arg0), WrapperRuntime.convertToInt(arg1)); } else { throw new EvalException(String.format("Invalid argument:\n\tfile.access(%s, %s)\n\tExpected:\n\tfile.access(character, integer(1))", arg0 .getTypeName(), arg1 .getTypeName())); } } }
bedatadriven/renjin-statet
org.renjin.core/src-gen/org/renjin/primitives/R$primitive$file$access.java
Java
apache-2.0
3,115
using System.Diagnostics; namespace Lucene.Net.Index { using Lucene.Net.Util; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Filters the incoming reader and makes all documents appear deleted. /// </summary> public class AllDeletedFilterReader : FilterAtomicReader { internal readonly IBits LiveDocs_Renamed; public AllDeletedFilterReader(AtomicReader @in) : base(@in) { LiveDocs_Renamed = new Bits.MatchNoBits(@in.MaxDoc); Debug.Assert(MaxDoc == 0 || HasDeletions); } public override IBits LiveDocs { get { return LiveDocs_Renamed; } } public override int NumDocs { get { return 0; } } } }
laimis/lucenenet
src/Lucene.Net.TestFramework/Index/AllDeletedFilterReader.cs
C#
apache-2.0
1,641
package files import ( "bytes" "io" "io/ioutil" "strings" "github.com/golang/protobuf/proto" "github.com/octavore/nagax/util/errors" uuid "github.com/satori/go.uuid" "github.com/willnorris/imageproxy" "github.com/ketchuphq/ketchup/proto/ketchup/models" ) func (m *Module) Upload(filename string, wr io.Reader) (*models.File, error) { // files are assigned a random id when stored to discourage manual renaming of files filename = strings.TrimPrefix(filename, "/") file, err := m.DB.GetFileByName(filename) if err != nil { return nil, errors.Wrap(err) } if file == nil || file.GetUuid() == "" { file = &models.File{ Uuid: proto.String(uuid.NewV4().String()), Name: proto.String(filename), } } err = m.store.Upload(file.GetUuid(), wr) if err != nil { return nil, errors.Wrap(err) } err = m.DB.UpdateFile(file) if err != nil { return nil, errors.Wrap(err) } return file, nil } // Get returns a reader, and nil, nil if file is not found func (m *Module) Get(filename string) (io.ReadCloser, error) { filename = strings.TrimPrefix(filename, "/") file, err := m.DB.GetFileByName(filename) if err != nil { return nil, errors.Wrap(err) } if file == nil { return nil, nil } return m.store.Get(file.GetUuid()) } // Get returns a reader, and nil, nil if file is not found func (m *Module) Delete(uuid string) error { file, err := m.DB.GetFile(uuid) if err != nil { return errors.Wrap(err) } if file == nil { return nil } err = m.DB.DeleteFile(file) if err != nil { return errors.Wrap(err) } return m.store.Delete(file.GetUuid()) } // GetWithTransform attempts to transform the image func (m *Module) GetWithTransform(filename string, optStr string) (io.ReadCloser, error) { filename = strings.TrimPrefix(filename, "/") r, err := m.Get(filename) if r == nil || err != nil || optStr == "" { return r, err } defer r.Close() data, err := ioutil.ReadAll(r) if err != nil { return nil, errors.Wrap(err) } opts := imageproxy.ParseOptions(optStr) output, err := imageproxy.Transform(data, opts) if err != nil { return nil, errors.Wrap(err) } return ioutil.NopCloser(bytes.NewBuffer(output)), nil }
ketchuphq/ketchup
server/files/actions.go
GO
apache-2.0
2,177
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict'; const name = "status-completed"; const pathData = "M256 0q53 0 99.5 20T437 75t55 81.5 20 99.5-20 99.5-55 81.5-81.5 55-99.5 20-99.5-20T75 437t-55-81.5T0 256t20-99.5T75 75t81.5-55T256 0zM128 256q-14 0-23 9t-9 23q0 12 9 23l64 64q11 9 23 9 13 0 23-9l192-192q9-11 9-23 0-13-9.5-22.5T384 128q-12 0-23 9L192 307l-41-42q-10-9-23-9z"; const ltr = false; const collection = "SAP-icons-v5"; const packageName = "@ui5/webcomponents-icons"; Icons.registerIcon(name, { pathData, ltr, collection, packageName }); var pathDataV4 = { pathData }; return pathDataV4; });
SAP/openui5
src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/icons/v5/status-completed.js
JavaScript
apache-2.0
673
package com.yueny.demo.downlatch.holder; import java.util.List; import java.util.Vector; import org.apache.commons.collections4.CollectionUtils; import com.yueny.demo.downlatch.bo.RecoverResult; /** * @author yueny09 <deep_blue_yang@163.com> * * @DATE 2016年3月22日 下午1:15:25 * */ public class TransResultHolder { private final List<RecoverResult> failList = new Vector<RecoverResult>(); private Integer recoverCount = 0; private final List<String> succList = new Vector<String>(); public synchronized void addResults(final List<RecoverResult> resultList) { if (!CollectionUtils.isEmpty(resultList)) { recoverCount += resultList.size(); for (final RecoverResult recoverResult : resultList) { if (recoverResult.isSucc()) { succList.add(recoverResult.getTransId()); } else { failList.add(recoverResult); } } } } public synchronized List<RecoverResult> getFailList() { return failList; } public synchronized Integer getRecoverCount() { return recoverCount; } public synchronized List<String> getSuccList() { return succList; } }
yueny/pra
exec/src/main/java/com/yueny/demo/downlatch/holder/TransResultHolder.java
Java
apache-2.0
1,149
using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web.Http; using Divergent.Sales.Data.Context; namespace Divergent.Sales.API.Controllers { [RoutePrefix("api/orders")] public class OrdersController : ApiController { private readonly ISalesContext _context; public OrdersController(ISalesContext context) { _context = context; } [HttpGet] public IEnumerable<dynamic> Get(int p = 0, int s = 10) { var orders = _context.Orders .Include(i => i.Items) .Include(i => i.Items.Select(x => x.Product)) .ToArray(); return orders .Skip(p * s) .Take(s) .Select(o => new { o.Id, o.CustomerId, ProductIds = o.Items.Select(i => i.Product.Id), ItemsCount = o.Items.Count }); } } }
jbogard/Workshop.Microservices
exercises/src/01 CompositeUI/after/Divergent.Sales.API/Controllers/OrdersController.cs
C#
apache-2.0
1,038
from google.appengine.ext import db class Stuff (db.Model): owner = db.UserProperty(required=True, auto_current_user=True) pulp = db.BlobProperty() class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) avatar = db.BlobProperty() date = db.DateTimeProperty(auto_now_add=True) class Placebo(db.Model): developer = db.StringProperty() OID = db.StringProperty() concept = db.StringProperty() category = db.StringProperty() taxonomy = db.StringProperty() taxonomy_version = db.StringProperty() code = db.StringProperty() descriptor = db.StringProperty()
0--key/lib
portfolio/2009_GoogleAppEngine/apps/0--key/models.py
Python
apache-2.0
651
package io.github.mayunfei.simple; /** * Created by mayunfei on 17-9-7. */ public class OrientationUtils { }
MaYunFei/TXLiveDemo
app/src/main/java/io/github/mayunfei/simple/OrientationUtils.java
Java
apache-2.0
113
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LCL.Domain.Model; using LCL.Domain.Specifications; namespace LCL.Domain.Repositories.Specifications { public class SalesOrderIDEqualsSpecification : Specification<SalesOrder> { private readonly Guid orderID; public SalesOrderIDEqualsSpecification(Guid orderID) { this.orderID = orderID; } public override System.Linq.Expressions.Expression<Func<SalesOrder, bool>> GetExpression() { return p => p.ID == orderID; } } }
luomingui/LCLFramework
LCLDemo/LCL.Domain/Specifications/SalesOrderIDEqualsSpecification.cs
C#
apache-2.0
635
/* * Swift Parallel Scripting Language (http://swift-lang.org) * Code from Java CoG Kit Project (see notice below) with modifications. * * Copyright 2005-2014 University of Chicago * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //---------------------------------------------------------------------- //This code is developed as part of the Java CoG Kit project //The terms of the license can be found at http://www.cogkit.org/license //This message may not be removed or altered. //---------------------------------------------------------------------- /* * Created on Mar 28, 2014 */ package org.griphyn.vdl.mapping.nodes; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import k.thr.LWThread; import org.griphyn.vdl.karajan.Pair; import org.griphyn.vdl.mapping.DSHandle; import org.griphyn.vdl.mapping.DuplicateMappingChecker; import org.griphyn.vdl.mapping.HandleOpenException; import org.griphyn.vdl.mapping.Mapper; import org.griphyn.vdl.mapping.Path; import org.griphyn.vdl.mapping.RootHandle; import org.griphyn.vdl.mapping.file.FileGarbageCollector; import org.griphyn.vdl.type.Field; import org.griphyn.vdl.type.Types; public class RootClosedMapDataNode extends AbstractClosedDataNode implements ArrayHandle, RootHandle { private int line = -1; private LWThread thread; private Mapper mapper; private Map<Comparable<?>, DSHandle> values; public RootClosedMapDataNode(Field field, Map<?, ?> values, DuplicateMappingChecker dmChecker) { super(field); setValues(values); if (getType().itemType().hasMappedComponents()) { this.mapper = new InitMapper(dmChecker); } } private void setValues(Map<?, ?> m) { values = new HashMap<Comparable<?>, DSHandle>(); for (Map.Entry<?, ? extends Object> e : m.entrySet()) { Comparable<?> k = (Comparable<?>) e.getKey(); Object n = e.getValue(); if (n instanceof DSHandle) { values.put(k, (DSHandle) n); } else if (n instanceof String) { values.put(k, NodeFactory.newNode(Field.Factory.createField(k, Types.STRING), getRoot(), this, n)); } else if (n instanceof Integer) { values.put(k, NodeFactory.newNode(Field.Factory.createField(k, Types.INT), getRoot(), this, n)); } else if (n instanceof Double) { values.put(k, NodeFactory.newNode(Field.Factory.createField(k, Types.FLOAT), getRoot(), this, n)); } else { throw new RuntimeException( "An array variable can only be initialized by a list of DSHandle or primitive values"); } } } @Override public RootHandle getRoot() { return this; } @Override public DSHandle getParent() { return null; } @Override public Path getPathFromRoot() { return Path.EMPTY_PATH; } @Override public void init(Mapper mapper) { if (!getType().itemType().hasMappedComponents()) { return; } if (mapper == null) { initialized(); } else { this.getInitMapper().setMapper(mapper); this.mapper.initialize(this); } } @Override public void mapperInitialized(Mapper mapper) { synchronized(this) { this.mapper = mapper; } initialized(); } protected void initialized() { if (variableTracer.isEnabled()) { variableTracer.trace(thread, line, getName() + " INITIALIZED " + mapper); } } public synchronized Mapper getMapper() { if (mapper instanceof InitMapper) { return ((InitMapper) mapper).getMapper(); } else { return mapper; } } @Override public int getLine() { return line; } @Override public void setLine(int line) { this.line = line; } @Override public void setThread(LWThread thread) { this.thread = thread; } @Override public LWThread getThread() { return thread; } @Override public String getName() { return (String) getField().getId(); } @Override protected AbstractDataNode getParentNode() { return null; } @Override public Mapper getActualMapper() { return mapper; } @Override public void closeArraySizes() { // already closed } @Override public Object getValue() { return values; } @Override public Map<Comparable<?>, DSHandle> getArrayValue() { return values; } @Override public boolean isArray() { return true; } @Override public Iterable<List<?>> entryList() { final Iterator<Map.Entry<Comparable<?>, DSHandle>> i = values.entrySet().iterator(); return new Iterable<List<?>>() { @Override public Iterator<List<?>> iterator() { return new Iterator<List<?>>() { @Override public boolean hasNext() { return i.hasNext(); } @Override public List<?> next() { Map.Entry<Comparable<?>, DSHandle> e = i.next(); return new Pair<Object>(e.getKey(), e.getValue()); } @Override public void remove() { i.remove(); } }; } }; } @Override protected Object getRawValue() { return values; } @Override protected void getFringePaths(List<Path> list, Path myPath) throws HandleOpenException { for (Map.Entry<Comparable<?>, DSHandle> e : values.entrySet()) { DSHandle h = e.getValue(); if (h instanceof AbstractDataNode) { AbstractDataNode ad = (AbstractDataNode) h; ad.getFringePaths(list, myPath.addLast(e.getKey())); } else { list.addAll(h.getFringePaths()); } } } @Override public void getLeaves(List<DSHandle> list) throws HandleOpenException { for (Map.Entry<Comparable<?>, DSHandle> e : values.entrySet()) { DSHandle h = e.getValue(); if (h instanceof AbstractDataNode) { AbstractDataNode ad = (AbstractDataNode) h; ad.getLeaves(list); } else { list.addAll(h.getLeaves()); } } } @Override public int arraySize() { return values.size(); } @Override protected void clean0() { FileGarbageCollector.getDefault().clean(this); super.clean0(); } @Override protected void finalize() throws Throwable { if (!isCleaned()) { clean(); } super.finalize(); } }
swift-lang/swift-k
src/org/griphyn/vdl/mapping/nodes/RootClosedMapDataNode.java
Java
apache-2.0
7,772
var baseClone = require('./_baseClone'); /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, false, true, customizer); } module.exports = cloneWith;
ionutbarau/petstore
petstore-app/src/main/resources/static/node_modules/bower/lib/node_modules/lodash/cloneWith.js
JavaScript
apache-2.0
1,117
/* * #! * Ontopoly Editor * #- * Copyright (C) 2001 - 2013 The Ontopia Project * #- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * !# */ package ontopoly.components; import java.util.Objects; import net.ontopia.topicmaps.core.OccurrenceIF; import ontopoly.model.FieldInstance; import ontopoly.models.FieldValueModel; import ontopoly.pages.AbstractOntopolyPage; import ontopoly.validators.ExternalValidation; import ontopoly.validators.RegexValidator; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.Model; public class FieldInstanceNumberField extends TextField<String> { private FieldValueModel fieldValueModel; private String oldValue; private String cols = "20"; public FieldInstanceNumberField(String id, FieldValueModel fieldValueModel) { super(id); this.fieldValueModel = fieldValueModel; OccurrenceIF occ = (OccurrenceIF)fieldValueModel.getObject(); this.oldValue = (occ == null ? null : occ.getValue()); setModel(new Model<String>(oldValue)); add(new RegexValidator(this, fieldValueModel.getFieldInstanceModel()) { @Override protected String getRegex() { return "^[-+]?\\d+(\\.\\d+)?$"; } @Override protected String resourceKeyInvalidValue() { return "validators.RegexValidator.number"; } }); // validate field using registered validators ExternalValidation.validate(this, oldValue); } public void setCols(int cols) { this.cols = Integer.toString(cols); } @Override protected void onComponentTag(ComponentTag tag) { tag.setName("input"); tag.put("type", "text"); tag.put("size", cols); super.onComponentTag(tag); } @Override protected void onModelChanged() { super.onModelChanged(); String newValue = (String)getModelObject(); if (Objects.equals(newValue, oldValue)) return; AbstractOntopolyPage page = (AbstractOntopolyPage)getPage(); FieldInstance fieldInstance = fieldValueModel.getFieldInstanceModel().getFieldInstance(); if (fieldValueModel.isExistingValue() && oldValue != null) fieldInstance.removeValue(oldValue, page.getListener()); if (newValue != null && !newValue.equals("")) { fieldInstance.addValue(newValue, page.getListener()); fieldValueModel.setExistingValue(newValue); } oldValue = newValue; } }
ontopia/ontopia
ontopoly-editor/src/main/java/ontopoly/components/FieldInstanceNumberField.java
Java
apache-2.0
2,944
/********************************************************************** Copyright (c) 2006 Erik Bengtson and others. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Contributors: ... **********************************************************************/ package org.jpox.samples.types.stringbuffer; /** * Object with a StringBuffer. */ public class StringBufferHolder { StringBuffer sb = new StringBuffer(); public StringBuffer getStringBuffer() { return sb; } public void setStringBuffer(StringBuffer sb) { this.sb = sb; } public void appendText(String text) { // Since DataNucleus doesn't support updates to the contents of a StringBuffer we replace it StringBuffer sb2 = new StringBuffer(sb.append(text)); sb = sb2; } public String getText() { return sb.toString(); } }
hopecee/texsts
samples/src/java/org/jpox/samples/types/stringbuffer/StringBufferHolder.java
Java
apache-2.0
1,432
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.importexport.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.importexport.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * CancelJobRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CancelJobRequestMarshaller implements Marshaller<Request<CancelJobRequest>, CancelJobRequest> { public Request<CancelJobRequest> marshall(CancelJobRequest cancelJobRequest) { if (cancelJobRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } Request<CancelJobRequest> request = new DefaultRequest<CancelJobRequest>(cancelJobRequest, "AmazonImportExport"); request.addParameter("Action", "CancelJob"); request.addParameter("Version", "2010-06-01"); request.setHttpMethod(HttpMethodName.POST); if (cancelJobRequest.getJobId() != null) { request.addParameter("JobId", StringUtils.fromString(cancelJobRequest.getJobId())); } if (cancelJobRequest.getAPIVersion() != null) { request.addParameter("APIVersion", StringUtils.fromString(cancelJobRequest.getAPIVersion())); } return request; } }
aws/aws-sdk-java
aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/transform/CancelJobRequestMarshaller.java
Java
apache-2.0
2,038
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.personalize.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DescribeAlgorithm" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeAlgorithmRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the algorithm to describe. * </p> */ private String algorithmArn; /** * <p> * The Amazon Resource Name (ARN) of the algorithm to describe. * </p> * * @param algorithmArn * The Amazon Resource Name (ARN) of the algorithm to describe. */ public void setAlgorithmArn(String algorithmArn) { this.algorithmArn = algorithmArn; } /** * <p> * The Amazon Resource Name (ARN) of the algorithm to describe. * </p> * * @return The Amazon Resource Name (ARN) of the algorithm to describe. */ public String getAlgorithmArn() { return this.algorithmArn; } /** * <p> * The Amazon Resource Name (ARN) of the algorithm to describe. * </p> * * @param algorithmArn * The Amazon Resource Name (ARN) of the algorithm to describe. * @return Returns a reference to this object so that method calls can be chained together. */ public DescribeAlgorithmRequest withAlgorithmArn(String algorithmArn) { setAlgorithmArn(algorithmArn); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAlgorithmArn() != null) sb.append("AlgorithmArn: ").append(getAlgorithmArn()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeAlgorithmRequest == false) return false; DescribeAlgorithmRequest other = (DescribeAlgorithmRequest) obj; if (other.getAlgorithmArn() == null ^ this.getAlgorithmArn() == null) return false; if (other.getAlgorithmArn() != null && other.getAlgorithmArn().equals(this.getAlgorithmArn()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAlgorithmArn() == null) ? 0 : getAlgorithmArn().hashCode()); return hashCode; } @Override public DescribeAlgorithmRequest clone() { return (DescribeAlgorithmRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/DescribeAlgorithmRequest.java
Java
apache-2.0
3,808
package libgbust import ( "io/ioutil" "net/http" "net/url" "unicode/utf8" ) // CheckDir is used to execute a directory check func (a *Attacker) CheckDir(word string) *Result { end, err := url.Parse(word) if err != nil { return &Result{ Msg: "[!] failed to parse word", Err: err, } } fullURL := a.config.URL.ResolveReference(end) req, err := http.NewRequest("GET", fullURL.String(), nil) if err != nil { return &Result{ Msg: "[!] failed to create new request", Err: err, } } for _, cookie := range a.config.Cookies { req.Header.Set("Cookie", cookie) } resp, err := a.client.Do(req) if err != nil { return &Result{ Err: err, Msg: "[!] failed to do request", } } defer resp.Body.Close() length := new(int64) if resp.ContentLength <= 0 { body, err := ioutil.ReadAll(resp.Body) if err == nil { *length = int64(utf8.RuneCountInString(string(body))) } } else { *length = resp.ContentLength } return &Result{ StatusCode: resp.StatusCode, Size: length, URL: resp.Request.URL, } }
kkirsche/gbust
libgbust/check.go
GO
apache-2.0
1,062
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.s4.comm.zk; import org.apache.s4.comm.core.CommEventCallback; import org.apache.s4.comm.core.DefaultWatcher; import org.apache.s4.comm.core.TaskManager; import org.apache.s4.comm.util.JSONUtil; import org.apache.s4.comm.util.ConfigParser.Cluster.ClusterType; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.log4j.Logger; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.data.Stat; public class ZkTaskManager extends DefaultWatcher implements TaskManager { static Logger logger = Logger.getLogger(ZkTaskManager.class); String tasksListRoot; String processListRoot; public ZkTaskManager(String address, String ClusterName, ClusterType clusterType) { this(address, ClusterName, clusterType, null); } /** * Constructor of TaskManager * * @param address * @param ClusterName */ public ZkTaskManager(String address, String ClusterName, ClusterType clusterType, CommEventCallback callbackHandler) { super(address, callbackHandler); this.root = "/" + ClusterName + "/" + clusterType.toString(); this.tasksListRoot = root + "/task"; this.processListRoot = root + "/process"; } /** * This will block the process thread from starting the task, when it is * unblocked it will return the data stored in the task node. This data can * be used by the This call assumes that the tasks are already set up * * @return Object containing data related to the task */ @Override public Object acquireTask(Map<String, String> customTaskData) { while (true) { synchronized (mutex) { try { Stat tExists = zk.exists(tasksListRoot, false); if (tExists == null) { logger.error("Tasks znode:" + tasksListRoot + " not setup.Going to wait"); tExists = zk.exists(tasksListRoot, true); if (tExists == null) { mutex.wait(); } continue; } Stat pExists = zk.exists(processListRoot, false); if (pExists == null) { logger.error("Process root znode:" + processListRoot + " not setup.Going to wait"); pExists = zk.exists(processListRoot, true); if (pExists == null) { mutex.wait(); } continue; } // setting watch true to tasks node will trigger call back // if there is any change to task node, // this is useful to add additional tasks List<String> tasks = zk.getChildren(tasksListRoot, true); List<String> processes = zk.getChildren(processListRoot, true); if (processes.size() < tasks.size()) { ArrayList<String> tasksAvailable = new ArrayList<String>(); for (int i = 0; i < tasks.size(); i++) { tasksAvailable.add("" + i); } if (processes != null) { for (String s : processes) { String taskId = s.split("-")[1]; tasksAvailable.remove(taskId); } } // try pick up a random task Random random = new Random(); int id = Integer.parseInt(tasksAvailable.get(random.nextInt(tasksAvailable.size()))); String pNode = processListRoot + "/" + "task-" + id; String tNode = tasksListRoot + "/" + "task-" + id; Stat pNodeStat = zk.exists(pNode, false); if (pNodeStat == null) { Stat tNodeStat = zk.exists(tNode, false); byte[] bytes = zk.getData(tNode, false, tNodeStat); Map<String, Object> map = (Map<String, Object>) JSONUtil.getMapFromJson(new String(bytes)); // if(!map.containsKey("address")){ // map.put("address", // InetAddress.getLocalHost().getHostName()); // } if (customTaskData != null) { for (String key : customTaskData.keySet()) { if (!map.containsKey(key)) { map.put(key, customTaskData.get(key)); } } } map.put("taskSize", "" + tasks.size()); map.put("tasksRootNode", tasksListRoot); map.put("processRootNode", processListRoot); String create = zk.create(pNode, JSONUtil.toJsonString(map) .getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); logger.info("Created process Node:" + pNode + " :" + create); return map; } } else { // all the tasks are taken up, will wait for the logger.info("No task available to take up. Going to wait"); mutex.wait(); } } catch (KeeperException e) { logger.info("Warn:mostly ignorable " + e.getMessage(), e); } catch (InterruptedException e) { logger.info("Warn:mostly ignorable " + e.getMessage(), e); } } } } }
s4/s4
s4-comm/src/main/java/org/apache/s4/comm/zk/ZkTaskManager.java
Java
apache-2.0
7,311
package chatty.util.api; import chatty.Helper; import chatty.util.DateTime; import java.util.LinkedHashMap; import java.util.Locale; import java.util.logging.Logger; /** * Holds the current info (name, viewers, title, game) of a stream, as well * as a history of the same information and stuff like when the info was * last requested, whether it's currently waiting for an API response etc. * * @author tduva */ public class StreamInfo { private static final Logger LOGGER = Logger.getLogger(StreamInfo.class.getName()); /** * All lowercase name of the stream */ public final String stream; /** * Correctly capitalized name of the stream. May be null if no set. */ private String display_name; private long lastUpdated = 0; private long lastStatusChange = 0; private String status = ""; private String game = ""; private int viewers = 0; private long startedAt = -1; private long lastOnline = -1; private long startedAtWithPicnic = -1; private boolean online = false; private boolean updateSucceeded = false; private int updateFailedCounter = 0; private boolean requested = false; private boolean followed = false; /** * The time the stream was changed from online -> offline, so recheck if * that actually is correct after some time. If this is -1, then do nothing. * Should be set to -1 with EVERY update (received data), except when it's * not already -1 on the change from online -> offline (to avoid request * spam if recheckOffline() is always true). */ private long recheckOffline = -1; // When the viewer stats where last calculated private long lastViewerStats; // How long at least between viewer stats calculations private static final int VIEWERSTATS_DELAY = 30*60*1000; // How long a stats range can be at most private static final int VIEWERSTATS_MAX_LENGTH = 35*60*1000; private static final int RECHECK_OFFLINE_DELAY = 10*1000; /** * Maximum length in seconds of what should count as a PICNIC (short stream * offline period), to set the online time with PICNICs correctly. */ private static final int MAX_PICNIC_LENGTH = 600; /** * The current full status (title + game), updated when new data is set. */ private String currentFullStatus; private String prevFullStatus; private final LinkedHashMap<Long,StreamInfoHistoryItem> history = new LinkedHashMap<>(); private int expiresAfter = 300; private final StreamInfoListener listener; public StreamInfo(String stream, StreamInfoListener listener) { this.listener = listener; this.stream = stream.toLowerCase(Locale.ENGLISH); } private void streamInfoUpdated() { if (listener != null) { listener.streamInfoUpdated(this); } } public void setRequested() { this.requested = true; } public boolean isRequested() { return requested; } private void streamInfoStatusChanged() { lastStatusChange = System.currentTimeMillis(); if (listener != null) { listener.streamInfoStatusChanged(this, getFullStatus()); } } @Override public String toString() { return "Online: "+online+ " Status: "+status+ " Game: "+game+ " Viewers: "+viewers; } public String getFullStatus() { return currentFullStatus; } private String makeFullStatus() { if (online) { String fullStatus = status; if (status == null) { fullStatus = "No stream title set"; } if (game != null) { fullStatus += " ("+game+")"; } return fullStatus; } else if (!updateSucceeded) { return ""; } else { return "Stream offline"; } } public String getStream() { return stream; } /** * The correctly capitalized name of the stream, or the all lowercase name * if correctly capitalized name is not set. * * @return The correctly capitalized name or all lowercase name */ public String getDisplayName() { return display_name != null ? display_name : stream; } /** * Whether a correctly capitalized name is set, which if true is returned * by {@see getDisplayName()}. * * @return true if a correctly capitalized name is set, false otherwise */ public boolean hasDisplayName() { return display_name != null; } /** * Sets the correctly capitalized name for this stream. * * @param name The correctly capitalized name */ public void setDisplayName(String name) { this.display_name = name; } /** * Set stream info from followed streams request. * * @param status The current stream title * @param game The current game being played * @param viewers The current viewercount * @param startedAt The timestamp when the stream was started, -1 if not set */ public void setFollowed(String status, String game, int viewers, long startedAt) { //System.out.println(status); followed = true; boolean saveToHistory = false; if (hasExpired()) { saveToHistory = true; } set(status, game, viewers, startedAt, saveToHistory); } /** * Set stream info from a regular stream info request. * * @param status The current stream title * @param game The current game being played * @param viewers The current viewercount * @param startedAt The timestamp when the stream was started, -1 if not set */ public void set(String status, String game, int viewers, long startedAt) { set(status, game, viewers, startedAt, true); } /** * This should only be used when the update was successful. * * @param status The current title of the stream * @param game The current game * @param viewers The current viewercount * @param startedAt The timestamp when the stream was started, -1 if not set * @param saveToHistory Whether to save the data to history */ private void set(String status, String game, int viewers, long startedAt, boolean saveToHistory) { this.status = Helper.trim(Helper.removeLinebreaks(status)); this.game = Helper.trim(game); this.viewers = viewers; // Always set to -1 (do nothing) when stream is set as online, but also // output a message if necessary if (recheckOffline != -1) { if (this.startedAt < startedAt) { LOGGER.info("StreamInfo " + stream + ": Stream not offline anymore"); } else { LOGGER.info("StreamInfo " + stream + ": Stream not offline"); } } recheckOffline = -1; if (lastOnlineAgo() > MAX_PICNIC_LENGTH) { // Only update online time with PICNICs when offline time was long // enough (of course also depends on what stream data Chatty has) this.startedAtWithPicnic = startedAt; } this.startedAt = startedAt; this.lastOnline = System.currentTimeMillis(); this.online = true; if (saveToHistory) { addHistoryItem(System.currentTimeMillis(),new StreamInfoHistoryItem(viewers, status, game)); } setUpdateSucceeded(true); } public void setExpiresAfter(int expiresAfter) { this.expiresAfter = expiresAfter; } public void setUpdateFailed() { setUpdateSucceeded(false); } private void setUpdateSucceeded(boolean succeeded) { updateSucceeded = succeeded; setUpdated(); if (succeeded) { updateFailedCounter = 0; } else { updateFailedCounter++; if (recheckOffline != -1) { // If an offline check is pending and the update failed, then // just set as offline now (may of course not be accurate at all // anymore). LOGGER.warning("StreamInfo "+stream+": Update failed, delayed setting offline"); setOffline(); } } currentFullStatus = makeFullStatus(); if (succeeded && !currentFullStatus.equals(prevFullStatus) || lastUpdateLongAgo()) { prevFullStatus = currentFullStatus; streamInfoStatusChanged(); } // Call at the end, so stuff is already updated streamInfoUpdated(); } public void setOffline() { // If switching from online to offline if (online && recheckOffline == -1) { LOGGER.info("Waiting to recheck offline status for " + stream); recheckOffline = System.currentTimeMillis(); } else { if (recheckOffline != -1) { //addHistoryItem(recheckOffline, new StreamInfoHistoryItem()); LOGGER.info("Offline after check: "+stream); } recheckOffline = -1; this.online = false; addHistoryItem(System.currentTimeMillis(), new StreamInfoHistoryItem()); } setUpdateSucceeded(true); } /** * Whether to recheck the offline status by requesting the stream status * again earlier than usual. * * @return true if it should be checked, false otherwise */ public boolean recheckOffline() { return recheckOffline != -1 && System.currentTimeMillis() - recheckOffline > RECHECK_OFFLINE_DELAY; } public boolean getFollowed() { return followed; } public boolean getOnline() { return this.online; } /** * The time the stream was started. As always, this may contain stale data * if the stream info is not valid or the stream offline. * * @return The timestamp or -1 if no time was received */ public long getTimeStarted() { return startedAt; } /** * The time the stream was started, including short disconnects (max 10 * minutes). If there was no disconnect, then the time is equal to * getTimeStarted(). As always, this may contain stale data if the stream * info is not valid or the stream offline. * * @return The timestamp or -1 if not time was received or the time is * invalid */ public long getTimeStartedWithPicnic() { return startedAtWithPicnic; } /** * How long ago the stream was last online. If the stream was never seen as * online this session, then a huge number will be returned. * * @return The number of seconds that have passed since the stream was last * seen as online */ public long lastOnlineAgo() { return (System.currentTimeMillis() - lastOnline) / 1000; } public long getLastOnlineTime() { return lastOnline; } private void setUpdated() { lastUpdated = System.currentTimeMillis() / 1000; requested = false; } // Getters /** * Gets the status stored for this stream. May not be correct, check * isValid() before using any data. * * @return */ public String getStatus() { return status; } /** * Gets the title stored for this stream, which is the same as the status, * unless the status is null. As opposed to getStatus() this never returns * null. * * @return */ public String getTitle() { if (status == null) { return "No stream title set"; } return status; } /** * Gets the game stored for this stream. May not be correct, check * isValid() before using any data. * * @return */ public String getGame() { return game; } /** * Gets the viewers stored for this stream. May not be correct, check * isValid() before using any data. * * @return */ public int getViewers() { return viewers; } /** * Calculates the number of seconds that passed after the last update * * @return Number of seconds that have passed after the last update */ public long getUpdatedDelay() { return (System.currentTimeMillis() / 1000) - lastUpdated; } /** * Checks if the info should be updated. The stream info takes longer * to expire when there were failed attempts at downloading the info from * the API. This only affects hasExpired(), not isValid(). * * @return true if the info should be updated, false otherwise */ public boolean hasExpired() { return getUpdatedDelay() > expiresAfter * (1+ updateFailedCounter / 2); } /** * Checks if the info is valid, taking into account if the last request * succeeded and how old the data is. * * @return true if the info can be used, false otherwise */ public boolean isValid() { if (!updateSucceeded || getUpdatedDelay() > expiresAfter*2) { return false; } return true; } public boolean lastUpdateLongAgo() { if (updateSucceeded && getUpdatedDelay() > expiresAfter*4) { return true; } return false; } /** * Returns the number of seconds the last status change is ago. * * @return */ public long getStatusChangeTimeAgo() { return (System.currentTimeMillis() - lastStatusChange) / 1000; } public long getStatusChangeTime() { return lastStatusChange; } private void addHistoryItem(Long time, StreamInfoHistoryItem item) { synchronized(history) { history.put(time, item); } } public LinkedHashMap<Long,StreamInfoHistoryItem> getHistory() { synchronized(history) { return new LinkedHashMap<>(history); } } /** * Create a summary of the viewercount in the interval that hasn't been * calculated yet (delay set as a constant). * * @param force Get stats even if the delay hasn't passed yet. * @return */ public ViewerStats getViewerStats(boolean force) { synchronized(history) { if (lastViewerStats == 0 && !force) { // No stats output yet, so assume current time as start, so // it's output after the set delay lastViewerStats = System.currentTimeMillis() - 5000; } long timePassed = System.currentTimeMillis() - lastViewerStats; if (!force && timePassed < VIEWERSTATS_DELAY) { return null; } long startAt = lastViewerStats+1; // Only calculate the max length if (timePassed > VIEWERSTATS_MAX_LENGTH) { startAt = System.currentTimeMillis() - VIEWERSTATS_MAX_LENGTH; } int min = -1; int max = -1; int total = 0; int count = 0; long firstTime = -1; long lastTime = -1; StringBuilder b = new StringBuilder(); // Initiate with -2, because -1 already means offline int prevViewers = -2; for (long time : history.keySet()) { if (time < startAt) { continue; } // Start doing anything for values >= startAt // Update so that it contains the last value that was looked at // at the end of this method lastViewerStats = time; int viewers = history.get(time).getViewers(); // Append to viewercount development String if (prevViewers > -1 && viewers != -1) { // If there is a prevViewers set and if online int diff = viewers - prevViewers; if (diff >= 0) { b.append("+"); } b.append(Helper.formatViewerCount(diff)); } else if (viewers != -1) { if (prevViewers == -1) { // Previous was offline, so show that b.append("_"); } b.append(Helper.formatViewerCount(viewers)); } prevViewers = viewers; if (viewers == -1) { continue; } // Calculate min/max/sum/count only when online if (firstTime == -1) { firstTime = time; } lastTime = time; if (viewers > max) { max = viewers; } if (min == -1 || viewers < min) { min = viewers; } total += viewers; count++; } // After going through all values, do some finishing work if (prevViewers == -1) { // Last value was offline, so show that b.append("_"); } if (count == 0) { return null; } int avg = total / count; return new ViewerStats(min, max, avg, firstTime, lastTime, count, b.toString()); } } /** * Holds a set of immutable values that make up viewerstats. */ public static class ViewerStats { public final int max; public final int min; public final int avg; public final long startTime; public final long endTime; public final int count; public final String history; public ViewerStats(int min, int max, int avg, long startTime, long endTime, int count, String history) { this.max = max; this.min = min; this.avg = avg; this.startTime = startTime; this.endTime = endTime; this.count = count; this.history = history; } /** * Which duration the data in this stats covers. This is not necessarily * the whole duration that was worked with (e.g. if the stream went * offline at the end, that data may not be included). This is the range * between the first and last valid data point. * * @return The number of seconds this data covers. */ public long duration() { return (endTime - startTime) / 1000; } /** * Checks if these viewerstats contain any viewer data. * * @return */ public boolean isValid() { // If min was set to another value than the initial one, then this // means at least one data point with a viewercount was there. return min != -1; } @Override public String toString() { return "Viewerstats ("+DateTime.format2(startTime) +"-"+DateTime.format2(endTime)+"):" + " avg:"+Helper.formatViewerCount(avg) + " min:"+Helper.formatViewerCount(min) + " max:"+Helper.formatViewerCount(max) + " ["+count+"/"+history+"]"; } } }
Javaec/ChattyRus
src/chatty/util/api/StreamInfo.java
Java
apache-2.0
19,898
/*********************************************************************************************** * * Copyright (C) 2016, IBL Software Engineering spol. s r. o. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * ***********************************************************************************************/ package com.iblsoft.iwxxm.webservice.ws.internal; import com.googlecode.jsonrpc4j.JsonRpcParam; import com.iblsoft.iwxxm.webservice.util.Log; import com.iblsoft.iwxxm.webservice.validator.IwxxmValidator; import com.iblsoft.iwxxm.webservice.validator.ValidationError; import com.iblsoft.iwxxm.webservice.validator.ValidationResult; import com.iblsoft.iwxxm.webservice.ws.IwxxmWebService; import com.iblsoft.iwxxm.webservice.ws.messages.ValidationRequest; import com.iblsoft.iwxxm.webservice.ws.messages.ValidationResponse; import java.io.File; import static com.google.common.base.Preconditions.checkArgument; /** * Implementation class of IwxxmWebService interface. */ public class IwxxmWebServiceImpl implements IwxxmWebService { private final IwxxmValidator iwxxmValidator; public IwxxmWebServiceImpl(File validationCatalogFile, File validationRulesDir, String defaultIwxxmVersion) { this.iwxxmValidator = new IwxxmValidator(validationCatalogFile, validationRulesDir, defaultIwxxmVersion); } @Override public ValidationResponse validate(@JsonRpcParam("request") ValidationRequest request) { Log.INSTANCE.debug("IwxxmWebService.validate request started"); checkRequestVersion(request.getRequestVersion()); ValidationResult validationResult = iwxxmValidator.validate(request.getIwxxmData(), request.getIwxxmVersion()); ValidationResponse.Builder responseBuilder = ValidationResponse.builder(); for (ValidationError ve : validationResult.getValidationErrors()) { responseBuilder.addValidationError(ve.getError(), ve.getLineNumber(), ve.getColumnNumber()); } Log.INSTANCE.debug("IwxxmWebService.validate request finished"); return responseBuilder.build(); } private void checkRequestVersion(String requestVersion) { checkArgument(requestVersion != null && requestVersion.equals("1.0"), "Unsupported request version."); } }
iblsoft/iwxxm-validator
src/main/java/com/iblsoft/iwxxm/webservice/ws/internal/IwxxmWebServiceImpl.java
Java
apache-2.0
2,770
# Copyright 2011 WebDriver committers # Copyright 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """The ActionChains implementation.""" from selenium.webdriver.remote.command import Command class ActionChains(object): """Generate user actions. All actions are stored in the ActionChains object. Call perform() to fire stored actions.""" def __init__(self, driver): """Creates a new ActionChains. Args: driver: The WebDriver instance which performs user actions. """ self._driver = driver self._actions = [] def perform(self): """Performs all stored actions.""" for action in self._actions: action() def click(self, on_element=None): """Clicks an element. Args: on_element: The element to click. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) self._actions.append(lambda: self._driver.execute(Command.CLICK, {'button': 0})) return self def click_and_hold(self, on_element): """Holds down the left mouse button on an element. Args: on_element: The element to mouse down. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) self._actions.append(lambda: self._driver.execute(Command.MOUSE_DOWN, {})) return self def context_click(self, on_element): """Performs a context-click (right click) on an element. Args: on_element: The element to context-click. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) self._actions.append(lambda: self._driver.execute(Command.CLICK, {'button': 2})) return self def double_click(self, on_element): """Double-clicks an element. Args: on_element: The element to double-click. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) self._actions.append(lambda: self._driver.execute(Command.DOUBLE_CLICK, {})) return self def drag_and_drop(self, source, target): """Holds down the left mouse button on the source element, then moves to the target element and releases the mouse button. Args: source: The element to mouse down. target: The element to mouse up. """ self.click_and_hold(source) self.release(target) return self def drag_and_drop_by_offset(self, source, xoffset, yoffset): """Holds down the left mouse button on the source element, then moves to the target element and releases the mouse button. Args: source: The element to mouse down. xoffset: X offset to move to. yoffset: Y offset to move to. """ self.click_and_hold(source) self.move_by_offset(xoffset, yoffset) self.release(source) return self def key_down(self, key, element=None): """Sends a key press only, without releasing it. Should only be used with modifier keys (Control, Alt and Shift). Args: key: The modifier key to send. Values are defined in Keys class. target: The element to send keys. If None, sends a key to current focused element. """ if element: self.click(element) self._actions.append(lambda: self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, { "value": key, "isdown": True})) return self def key_up(self, key, element=None): """Releases a modifier key. Args: key: The modifier key to send. Values are defined in Keys class. target: The element to send keys. If None, sends a key to current focused element. """ if element: self.click(element) self._actions.append(lambda: self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, { "value": key, "isdown": False})) return self def move_by_offset(self, xoffset, yoffset): """Moving the mouse to an offset from current mouse position. Args: xoffset: X offset to move to. yoffset: Y offset to move to. """ self._actions.append(lambda: self._driver.execute(Command.MOVE_TO, { 'xoffset': xoffset, 'yoffset': yoffset})) return self def move_to_element(self, to_element): """Moving the mouse to the middle of an element. Args: to_element: The element to move to. """ self._actions.append(lambda: self._driver.execute(Command.MOVE_TO, {'element': to_element.id})) return self def move_to_element_with_offset(self, to_element, xoffset, yoffset): """Move the mouse by an offset of the specificed element. Offsets are relative to the top-left corner of the element. Args: to_element: The element to move to. xoffset: X offset to move to. yoffset: Y offset to move to. """ self._actions.append(lambda: self._driver.execute(Command.MOVE_TO, { 'element': to_element.id, 'xoffset': xoffset, 'yoffset': yoffset})) return self def release(self, on_element): """Releasing a held mouse button. Args: on_element: The element to mouse up. """ if on_element: self.move_to_element(on_element) self._actions.append(lambda: self._driver.execute(Command.MOUSE_UP, {})) return self def send_keys(self, *keys_to_send): """Sends keys to current focused element. Args: keys_to_send: The keys to send. """ self._actions.append(lambda: self._driver.switch_to_active_element().send_keys(*keys_to_send)) return self def send_keys_to_element(self, element, *keys_to_send): """Sends keys to an element. Args: element: The element to send keys. keys_to_send: The keys to send. """ self._actions.append(lambda: element.send_keys(*keys_to_send)) return self
hali4ka/robotframework-selenium2library
src/Selenium2Library/lib/selenium-2.8.1/py/selenium/webdriver/common/action_chains.py
Python
apache-2.0
7,157
package org.jboss.resteasy.reactive.client.processor.beanparam; import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.BEAN_PARAM; import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.COOKIE_PARAM; import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.FORM_PARAM; import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.HEADER_PARAM; import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.PATH_PARAM; import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.QUERY_PARAM; import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; import org.jboss.jandex.FieldInfo; import org.jboss.jandex.IndexView; import org.jboss.jandex.MethodInfo; import org.jboss.jandex.Type; import org.jboss.resteasy.reactive.common.processor.JandexUtil; public class BeanParamParser { public static List<Item> parse(ClassInfo beanParamClass, IndexView index) { Set<ClassInfo> processedBeanParamClasses = Collections.newSetFromMap(new IdentityHashMap<>()); return parseInternal(beanParamClass, index, processedBeanParamClasses); } private static List<Item> parseInternal(ClassInfo beanParamClass, IndexView index, Set<ClassInfo> processedBeanParamClasses) { if (!processedBeanParamClasses.add(beanParamClass)) { throw new IllegalArgumentException("Cycle detected in BeanParam annotations; already processed class " + beanParamClass.name()); } try { List<Item> resultList = new ArrayList<>(); // Parse class tree recursively if (!JandexUtil.DOTNAME_OBJECT.equals(beanParamClass.superName())) { resultList .addAll(parseInternal(index.getClassByName(beanParamClass.superName()), index, processedBeanParamClasses)); } resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, QUERY_PARAM, (annotationValue, fieldInfo) -> new QueryParamItem(annotationValue, new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()), fieldInfo.type()), (annotationValue, getterMethod) -> new QueryParamItem(annotationValue, new GetterExtractor(getterMethod), getterMethod.returnType()))); resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, BEAN_PARAM, (annotationValue, fieldInfo) -> { Type type = fieldInfo.type(); if (type.kind() == Type.Kind.CLASS) { List<Item> subBeanParamItems = parseInternal(index.getClassByName(type.asClassType().name()), index, processedBeanParamClasses); return new BeanParamItem(subBeanParamItems, new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())); } else { throw new IllegalArgumentException("BeanParam annotation used on a field that is not an object: " + beanParamClass.name() + "." + fieldInfo.name()); } }, (annotationValue, getterMethod) -> { Type returnType = getterMethod.returnType(); List<Item> items = parseInternal(index.getClassByName(returnType.name()), index, processedBeanParamClasses); return new BeanParamItem(items, new GetterExtractor(getterMethod)); })); resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, COOKIE_PARAM, (annotationValue, fieldInfo) -> new CookieParamItem(annotationValue, new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()), fieldInfo.type().name().toString()), (annotationValue, getterMethod) -> new CookieParamItem(annotationValue, new GetterExtractor(getterMethod), getterMethod.returnType().name().toString()))); resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, HEADER_PARAM, (annotationValue, fieldInfo) -> new HeaderParamItem(annotationValue, new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()), fieldInfo.type().name().toString()), (annotationValue, getterMethod) -> new HeaderParamItem(annotationValue, new GetterExtractor(getterMethod), getterMethod.returnType().name().toString()))); resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, PATH_PARAM, (annotationValue, fieldInfo) -> new PathParamItem(annotationValue, fieldInfo.type().name().toString(), new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())), (annotationValue, getterMethod) -> new PathParamItem(annotationValue, getterMethod.returnType().name().toString(), new GetterExtractor(getterMethod)))); resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, FORM_PARAM, (annotationValue, fieldInfo) -> new FormParamItem(annotationValue, fieldInfo.type().name().toString(), new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())), (annotationValue, getterMethod) -> new FormParamItem(annotationValue, getterMethod.returnType().name().toString(), new GetterExtractor(getterMethod)))); return resultList; } finally { processedBeanParamClasses.remove(beanParamClass); } } private static MethodInfo getGetterMethod(ClassInfo beanParamClass, MethodInfo methodInfo) { MethodInfo getter = null; if (methodInfo.parameters().size() > 0) { // should be setter // find the corresponding getter: String setterName = methodInfo.name(); if (setterName.startsWith("set")) { getter = beanParamClass.method(setterName.replace("^set", "^get")); } } else if (methodInfo.name().startsWith("get")) { getter = methodInfo; } if (getter == null) { throw new IllegalArgumentException( "No getter corresponding to " + methodInfo.declaringClass().name() + "#" + methodInfo.name() + " found"); } return getter; } private static <T extends Item> List<T> paramItemsForFieldsAndMethods(ClassInfo beanParamClass, DotName parameterType, BiFunction<String, FieldInfo, T> fieldExtractor, BiFunction<String, MethodInfo, T> methodExtractor) { return ParamTypeAnnotations.of(beanParamClass, parameterType).itemsForFieldsAndMethods(fieldExtractor, methodExtractor); } private BeanParamParser() { } private static class ParamTypeAnnotations { private final ClassInfo beanParamClass; private final List<AnnotationInstance> annotations; private ParamTypeAnnotations(ClassInfo beanParamClass, DotName parameterType) { this.beanParamClass = beanParamClass; List<AnnotationInstance> relevantAnnotations = beanParamClass.annotations().get(parameterType); this.annotations = relevantAnnotations == null ? Collections.emptyList() : relevantAnnotations.stream().filter(this::isFieldOrMethodAnnotation).collect(Collectors.toList()); } private static ParamTypeAnnotations of(ClassInfo beanParamClass, DotName parameterType) { return new ParamTypeAnnotations(beanParamClass, parameterType); } private <T extends Item> List<T> itemsForFieldsAndMethods(BiFunction<String, FieldInfo, T> itemFromFieldExtractor, BiFunction<String, MethodInfo, T> itemFromMethodExtractor) { return annotations.stream() .map(annotation -> toItem(annotation, itemFromFieldExtractor, itemFromMethodExtractor)) .collect(Collectors.toList()); } private <T extends Item> T toItem(AnnotationInstance annotation, BiFunction<String, FieldInfo, T> itemFromFieldExtractor, BiFunction<String, MethodInfo, T> itemFromMethodExtractor) { String annotationValue = annotation.value() == null ? null : annotation.value().asString(); return annotation.target().kind() == AnnotationTarget.Kind.FIELD ? itemFromFieldExtractor.apply(annotationValue, annotation.target().asField()) : itemFromMethodExtractor.apply(annotationValue, getGetterMethod(beanParamClass, annotation.target().asMethod())); } private boolean isFieldOrMethodAnnotation(AnnotationInstance annotation) { return annotation.target().kind() == AnnotationTarget.Kind.FIELD || annotation.target().kind() == AnnotationTarget.Kind.METHOD; } } }
quarkusio/quarkus
independent-projects/resteasy-reactive/client/processor/src/main/java/org/jboss/resteasy/reactive/client/processor/beanparam/BeanParamParser.java
Java
apache-2.0
9,998
import * as React from 'react' import styled from 'styled-components' import { colors } from 'styles/variables' interface InputFeedbackProps { className?: string valid?: boolean } const InputFeedback: React.SFC<InputFeedbackProps> = ({ className, children }) => ( <div className={className}>{children}</div> ) export default styled(InputFeedback)` width: 100%; margin-top: 0.25rem; font-size: 80%; color: ${props => (props.valid ? colors.green : colors.red)}; `
blvdgroup/crater
priv/crater-web/src/components/ui/InputFeedback.tsx
TypeScript
apache-2.0
479