code
stringlengths
2
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
2
1.05M
// license:GPL-2.0+ // copyright-holders:Couriersud /* * nld_legacy.c * */ #include "nld_legacy.h" #include "nl_setup.h" NETLIB_NAMESPACE_DEVICES_START() NETLIB_START(nicRSFF) { register_input("S", m_S); register_input("R", m_R); register_output("Q", m_Q); register_output("QQ", m_QQ); } NETLIB_RESET(nicRSFF) { m_Q.initial(0); m_QQ.initial(1); } NETLIB_UPDATE(nicRSFF) { if (!INPLOGIC(m_S)) { OUTLOGIC(m_Q, 1, NLTIME_FROM_NS(20)); OUTLOGIC(m_QQ, 0, NLTIME_FROM_NS(20)); } else if (!INPLOGIC(m_R)) { OUTLOGIC(m_Q, 0, NLTIME_FROM_NS(20)); OUTLOGIC(m_QQ, 1, NLTIME_FROM_NS(20)); } } NETLIB_START(nicDelay) { register_input("1", m_I); register_output("2", m_Q); register_param("L_TO_H", m_L_to_H, 10); register_param("H_TO_L", m_H_to_L, 10); save(NLNAME(m_last)); } NETLIB_RESET(nicDelay) { m_Q.initial(0); } NETLIB_UPDATE_PARAM(nicDelay) { } NETLIB_UPDATE(nicDelay) { netlist_sig_t nval = INPLOGIC(m_I); if (nval && !m_last) { // L_to_H OUTLOGIC(m_Q, 1, NLTIME_FROM_NS(m_L_to_H.Value())); } else if (!nval && m_last) { // H_to_L OUTLOGIC(m_Q, 0, NLTIME_FROM_NS(m_H_to_L.Value())); } m_last = nval; } NETLIB_NAMESPACE_DEVICES_END()
RJRetro/mame
src/lib/netlist/devices/nld_legacy.cpp
C++
gpl-2.0
1,191
<div class="wrap"> <div class="postbox-container" style="width:95%; margin-right: 5%"> <div class="metabox-holder"> <div class="meta-box-sortables" style="min-height:0;"> <div class="postbox"> <h3 class="hndle"><span><?php echo $tr_Deck_Builder; ?></span></h3> <div class="inside"> <p style="width: 50%"><?php echo $tr_Select_Components; ?></p> <form method="POST" action="" id="idmsg-settings" name="idmsg-settings"> <div class="form-select"> <p> <label for="deck_select"><?php echo $tr_Create_Select; ?></label><br/> <select name="deck_select" id="deck_select"> <option><?php echo $tr_New_Deck; ?></option> </select> </p> </div> <div class="form-input"> <p> <label for="deck_title"><?php echo $tr_Deck_Title; ?></label><br/> <input type="text" name="deck_title" id="deck_title" class="deck-attr-text" value="" /> </p> </div> <div class="form-check"> <input type="checkbox" name="project_title" id="project_title" class="deck-attr" value="1"/> <label for="project_title"><?php echo $tr_Project_Title; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_image" id="project_image" class="deck-attr" value="1"/> <label for="project_image"><?php echo $tr_Product_Image; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_bar" id="project_bar" class="deck-attr" value="1"/> <label for="project_bar"><?php echo $tr_Percentage_Bar; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_pledged" id="project_pledged" class="deck-attr" value="1"/> <label for="project_pledged"><?php echo $tr_Total_Raised; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_goal" id="project_goal" class="deck-attr" value="1"/> <label for="project_goal"><?php echo $tr_Project_Goal; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_pledgers" id="project_pledgers" class="deck-attr" value="1"/> <label for="project_pledgers"><?php echo $tr_Total_Orders; ?></label> </div> <div class="form-check"> <input type="checkbox" name="days_left" id="days_left" class="deck-attr" value="1"/> <label for="days_left"><?php echo $tr_Days_To_Go; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_end" id="project_end" class="deck-attr" value="1"/> <label for="project_end"><?php echo $tr_End_Date; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_button" id="project_button" class="deck-attr" value="1"/> <label for="project_button"><?php echo $tr_Buy_Button; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_description" id="project_description" class="deck-attr" value="1"/> <label for="project_description"><?php echo $tr_meta_project_description; ?></label> </div> <div class="form-check"> <input type="checkbox" name="project_levels" id="project_levels" class="deck-attr" value="1"/> <label for="project_levels"><?php echo $tr_Levels; ?></label> </div> <div class="submit"> <input type="submit" name="deck_submit" id="submit" class="button button-primary"/> <input type="submit" name="deck_delete" id="deck_delete" class="button" value="Delete Deck" style="display: none;"/> </div> </form> </div> </div> </div> </div> </div> </div>
sharpmachine/unlikelyheroes.com
wp-content/plugins/ignitiondeck/templates/admin/_deckBuilder.php
PHP
gpl-2.0
3,759
require 'rexml/document' module Ohcount module Gestalt class CsprojRule < FileRule attr_accessor :import def initialize(*args) @import = args.shift || /.*/ @import = /^#{Regexp.escape(@import.to_s)}$/ unless @import.is_a? Regexp super(args) end def process_source_file(source_file) if source_file.filename =~ /\.csproj$/ && source_file.language_breakdown('xml') callback = lambda do |import| @count += 1 if import =~ @import end begin REXML::Document.parse_stream(source_file.language_breakdown('xml').code, CsprojListener.new(callback)) rescue REXML::ParseException # Malformed XML! -- ignore and move on end end end end end end
scriptum/ohcount
ruby/gestalt/rules/csproj_rule.rb
Ruby
gpl-2.0
739
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="cs_CZ"> <context> <name>AboutDialog</name> <message> <location filename="../../build/pcmanfm/ui_about.h" line="134"/> <source>About</source> <translation type="unfinished">O</translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="135"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:16pt; font-weight:600;&quot;&gt;PCManFM&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="137"/> <source>Lightweight file manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="143"/> <source>PCMan File Manager Copyright (C) 2009 - 2014 洪任諭 (Hong Jen Yee) 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="139"/> <source>Programming: * Hong Jen Yee (PCMan) &lt;pcman.tw@gmail.com&gt; </source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="138"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;http://lxqt.org/&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;http://lxqt.org/&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="142"/> <source>Authors</source> <translation type="unfinished">Autoři</translation> </message> <message> <location filename="../../build/pcmanfm/ui_about.h" line="160"/> <source>License</source> <translation type="unfinished">Licence</translation> </message> </context> <context> <name>AutoRunDialog</name> <message> <location filename="../../build/pcmanfm/ui_autorun.h" line="110"/> <source>Removable medium is inserted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_autorun.h" line="112"/> <source>&lt;b&gt;Removable medium is inserted&lt;/b&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_autorun.h" line="113"/> <source>Type of medium:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_autorun.h" line="114"/> <source>Detecting...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_autorun.h" line="115"/> <source>Please select the action you want to perform:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DesktopFolder</name> <message> <location filename="../../build/pcmanfm/ui_desktop-folder.h" line="75"/> <source>Form</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-folder.h" line="76"/> <source>Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-folder.h" line="77"/> <source>Desktop folder:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-folder.h" line="79"/> <source>Image file</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-folder.h" line="84"/> <source>Folder path</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-folder.h" line="85"/> <source>&amp;Browse</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DesktopPreferencesDialog</name> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="254"/> <source>Desktop Preferences</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="255"/> <source>Background</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="256"/> <source>Wallpaper mode:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="257"/> <source>Wallpaper image file:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="259"/> <source>Select background color:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="261"/> <source>Image file</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="266"/> <source>Image file path</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="267"/> <source>&amp;Browse</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="268"/> <source>Label Text</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="271"/> <source>Select text color:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="272"/> <source>Select shadow color:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="273"/> <source>Select font:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="275"/> <source>General</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="276"/> <source>Window Manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="277"/> <source>Show menus provided by window managers when desktop is clicked</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="278"/> <source>Advanced</source> <translation type="unfinished">Pokročilé</translation> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="557"/> <source>File Manager</source> <translation type="unfinished">Správce souborů</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="560"/> <source>Go Up</source> <translation type="unfinished">Nahoru</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="562"/> <source>Alt+Up</source> <translation type="unfinished">Alt+Nahoru</translation> </message> <message> <source>Home</source> <translation type="obsolete">Domů</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="564"/> <source>Alt+Home</source> <translation type="unfinished">Alt+Home</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="583"/> <source>Reload</source> <translation type="unfinished">Obnovit</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="566"/> <source>F5</source> <translation type="unfinished">F5</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="563"/> <source>&amp;Home</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="565"/> <source>&amp;Reload</source> <translation type="unfinished">&amp;Obnovit</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="567"/> <source>Go</source> <translation type="unfinished">Jdi</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="568"/> <source>Quit</source> <translation type="unfinished">ukončit</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="569"/> <source>&amp;About</source> <translation type="unfinished">&amp;O programu</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="572"/> <source>New Window</source> <translation type="unfinished">Nové okno</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="574"/> <source>Ctrl+N</source> <translation type="unfinished">Ctrl+N</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="575"/> <source>Show &amp;Hidden</source> <translation type="unfinished">Zobrazit &amp;skryté</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="576"/> <source>Ctrl+H</source> <translation type="unfinished">Ctrl+H</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="577"/> <source>&amp;Computer</source> <translation type="unfinished">Počítač</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="578"/> <source>&amp;Trash</source> <translation type="unfinished">&amp;Koš</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="579"/> <source>&amp;Network</source> <translation type="unfinished">Síť</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="580"/> <source>&amp;Desktop</source> <translation type="unfinished">Plocha</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="581"/> <source>&amp;Add to Bookmarks</source> <translation type="unfinished">Přidat k záložkám</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="582"/> <source>&amp;Applications</source> <translation type="unfinished">Programy</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="589"/> <source>Ctrl+X</source> <translation type="unfinished">Ctrl+X</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="590"/> <source>&amp;Copy</source> <translation type="unfinished">Kopírovat</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="591"/> <source>Ctrl+C</source> <translation type="unfinished">Ctrl+C</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="592"/> <source>&amp;Paste</source> <translation type="unfinished">Vložit</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="593"/> <source>Ctrl+V</source> <translation type="unfinished">Ctrl+V</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="594"/> <source>Select &amp;All</source> <translation type="unfinished">Vybrat všechno</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="596"/> <source>Pr&amp;eferences</source> <translation type="unfinished">&amp;Nastavení</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="597"/> <source>&amp;Ascending</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="598"/> <source>&amp;Descending</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="599"/> <source>&amp;By File Name</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="600"/> <source>By &amp;Modification Time</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="601"/> <source>By File &amp;Type</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="602"/> <source>By &amp;Owner</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="603"/> <source>&amp;Folder First</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="619"/> <source>&amp;Invert Selection</source> <translation type="unfinished">Invertovat výběr</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="620"/> <source>&amp;Delete</source> <translation type="unfinished">Smazat</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="622"/> <source>&amp;Rename</source> <translation type="unfinished">Přejmenovat</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="629"/> <source>&amp;Case Sensitive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="630"/> <source>By File &amp;Size</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="631"/> <source>&amp;Close Window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="595"/> <source>Ctrl+A</source> <translation type="unfinished">Ctrl+A</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="558"/> <source>Go &amp;Up</source> <translation type="unfinished">Nahoru</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="570"/> <source>&amp;New Window</source> <translation type="unfinished">Nové &amp;okno</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="584"/> <source>&amp;Icon View</source> <translation type="unfinished">Pohled s ikonami</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="585"/> <source>&amp;Compact View</source> <translation type="unfinished">Kompaktní pohled</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="586"/> <source>&amp;Detailed List</source> <translation type="unfinished">Seznam s podrobnostmi</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="587"/> <source>&amp;Thumbnail View</source> <translation type="unfinished">Pohled s náhledy</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="588"/> <source>Cu&amp;t</source> <translation type="unfinished">Vyjmout</translation> </message> <message> <source>Ascending</source> <translation type="obsolete">Vzestupně</translation> </message> <message> <source>Descending</source> <translation type="obsolete">Sestupně</translation> </message> <message> <source>By File Name</source> <translation type="obsolete">Podle jména</translation> </message> <message> <source>By Modification Time</source> <translation type="obsolete">Podle času</translation> </message> <message> <source>By File Type</source> <translation type="obsolete">Podle typu</translation> </message> <message> <source>By Owner</source> <translation type="obsolete">Podle vlastníka</translation> </message> <message> <source>Folder First</source> <translation type="obsolete">Složky jako první</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="604"/> <source>New &amp;Tab</source> <translation type="unfinished">Nový &amp;panel</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="606"/> <source>New Tab</source> <translation type="unfinished">Nový panel</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="608"/> <source>Ctrl+T</source> <translation type="unfinished">Ctrl+T</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="609"/> <source>Go &amp;Back</source> <translation type="unfinished">Zpět</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="611"/> <source>Go Back</source> <translation type="unfinished">Zpět</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="613"/> <source>Alt+Left</source> <translation type="unfinished">Alt+Vlevo</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="614"/> <source>Go &amp;Forward</source> <translation type="unfinished">&amp;Vpřed</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="616"/> <source>Go Forward</source> <translation type="unfinished">Vpřed</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="618"/> <source>Alt+Right</source> <translation type="unfinished">Alt+Vpravo</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="621"/> <source>Del</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="623"/> <source>F2</source> <translation type="unfinished">F2</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="624"/> <source>C&amp;lose Tab</source> <translation type="unfinished">Zavřít panel</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="626"/> <source>File &amp;Properties</source> <translation type="unfinished">Vlastnosti souboru</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="628"/> <source>&amp;Folder Properties</source> <translation type="unfinished">Vlastnosti složky</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="638"/> <source>Ctrl+Shift+N</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="640"/> <source>Ctrl+Alt+N</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="643"/> <source>Filter</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="646"/> <source>C&amp;reate New</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="649"/> <source>&amp;Sorting</source> <translation type="unfinished">Řadit</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="654"/> <source>Main Toolbar</source> <translation type="unfinished">Hlavní panel</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="625"/> <source>Ctrl+W</source> <translation type="unfinished">Ctrl+W</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="627"/> <source>Alt+Return</source> <translation type="unfinished">Alt+Return</translation> </message> <message> <source>Case Sensitive</source> <translation type="obsolete">Rozlišovat velikost písmen</translation> </message> <message> <source>By File Size</source> <translation type="obsolete">Podle velikosti</translation> </message> <message> <source>Close Window</source> <translation type="obsolete">Zavřít okno</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="632"/> <source>Edit Bookmarks</source> <translation type="unfinished">Upravit záložky</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="633"/> <source>Open &amp;Terminal</source> <translation type="unfinished">Otevřít &amp;terminál</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="634"/> <source>F4</source> <translation type="unfinished">F4</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="635"/> <source>Open as &amp;Root</source> <translation type="unfinished">Otevřít jako &amp;Root</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="636"/> <source>&amp;Edit Bookmarks</source> <translation type="unfinished">Upravit záložky</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="637"/> <source>&amp;Folder</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="639"/> <source>&amp;Blank File</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="641"/> <source>&amp;Find Files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="642"/> <source>F3</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="644"/> <source>Filter by string...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="645"/> <source>&amp;File</source> <translation type="unfinished">&amp;Soubor</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="647"/> <source>&amp;Help</source> <translation type="unfinished">&amp;Nápověda</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="648"/> <source>&amp;View</source> <translation type="unfinished">&amp;Zobrazení</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="650"/> <source>&amp;Edit</source> <translation type="unfinished">Úpr&amp;avy</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="651"/> <source>&amp;Bookmarks</source> <translation type="unfinished">Zál&amp;ožky</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="652"/> <source>&amp;Go</source> <translation type="unfinished">&amp;Jdi</translation> </message> <message> <location filename="../../build/pcmanfm/ui_main-win.h" line="653"/> <source>&amp;Tool</source> <translation type="unfinished">Nás&amp;troje</translation> </message> </context> <context> <name>PCManFM::Application</name> <message> <location filename="../application.cpp" line="162"/> <source>Name of configuration profile</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="162"/> <source>PROFILE</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="165"/> <source>Run PCManFM as a daemon</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="168"/> <source>Quit PCManFM</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="171"/> <source>Launch desktop manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="174"/> <source>Turn off desktop manager if it&apos;s running</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="177"/> <source>Open desktop preference dialog on the page with the specified name</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="177"/> <location filename="../application.cpp" line="193"/> <source>NAME</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="180"/> <source>Open new window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="183"/> <source>Open Find Files utility</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="186"/> <source>Set desktop wallpaper from image FILE</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="186"/> <source>FILE</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="190"/> <source>Set mode of desktop wallpaper. MODE=(color|stretch|fit|center|tile)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="190"/> <source>MODE</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="193"/> <source>Open Preferences dialog on the page with the specified name</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="196"/> <source>Files or directories to open</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="196"/> <source>[FILE1, FILE2,...]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="500"/> <location filename="../application.cpp" line="507"/> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../application.cpp" line="507"/> <source>Terminal emulator is not set.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::AutoRunDialog</name> <message> <location filename="../autorundialog.cpp" line="43"/> <source>Open in file manager</source> <translation type="unfinished"></translation> </message> <message> <location filename="../autorundialog.cpp" line="133"/> <source>Removable Disk</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::DesktopPreferencesDialog</name> <message> <location filename="../desktoppreferencesdialog.cpp" line="50"/> <source>Fill with background color only</source> <translation type="unfinished"></translation> </message> <message> <location filename="../desktoppreferencesdialog.cpp" line="51"/> <source>Stretch to fill the entire screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../desktoppreferencesdialog.cpp" line="52"/> <source>Stretch to fit the screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../desktoppreferencesdialog.cpp" line="53"/> <source>Center on the screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../desktoppreferencesdialog.cpp" line="54"/> <source>Tile the image to fill the entire screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../desktoppreferencesdialog.cpp" line="157"/> <source>Image Files</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::DesktopWindow</name> <message> <location filename="../desktopwindow.cpp" line="366"/> <source>Stic&amp;k to Current Position</source> <translation type="unfinished"></translation> </message> <message> <location filename="../desktopwindow.cpp" line="388"/> <source>Desktop Preferences</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::MainWindow</name> <message> <location filename="../mainwindow.cpp" line="190"/> <source>Clear text (Ctrl+K)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainwindow.cpp" line="455"/> <source>Version: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainwindow.cpp" line="907"/> <source>&amp;Move to Trash</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainwindow.cpp" line="907"/> <source>&amp;Delete</source> <translation type="unfinished">Smazat</translation> </message> <message> <location filename="../mainwindow.cpp" line="969"/> <location filename="../mainwindow.cpp" line="980"/> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../mainwindow.cpp" line="980"/> <source>Switch user command is not set.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::PreferencesDialog</name> <message> <location filename="../preferencesdialog.cpp" line="190"/> <source>Icon View</source> <translation type="unfinished"></translation> </message> <message> <location filename="../preferencesdialog.cpp" line="191"/> <source>Compact Icon View</source> <translation type="unfinished"></translation> </message> <message> <location filename="../preferencesdialog.cpp" line="192"/> <source>Thumbnail View</source> <translation type="unfinished"></translation> </message> <message> <location filename="../preferencesdialog.cpp" line="193"/> <source>Detailed List View</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::TabPage</name> <message> <location filename="../tabpage.cpp" line="248"/> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../tabpage.cpp" line="261"/> <source>Free space: %1 (Total: %2)</source> <translation type="unfinished"></translation> </message> <message numerus="yes"> <location filename="../tabpage.cpp" line="276"/> <source>%n item(s)</source> <translation type="unfinished"> <numerusform></numerusform> <numerusform></numerusform> <numerusform></numerusform> </translation> </message> <message numerus="yes"> <location filename="../tabpage.cpp" line="278"/> <source> (%n hidden)</source> <translation type="unfinished"> <numerusform></numerusform> <numerusform></numerusform> <numerusform></numerusform> </translation> </message> <message> <location filename="../tabpage.cpp" line="426"/> <source>%1 item(s) selected</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PCManFM::View</name> <message> <location filename="../view.cpp" line="103"/> <source>Open in New T&amp;ab</source> <translation type="unfinished"></translation> </message> <message> <location filename="../view.cpp" line="107"/> <source>Open in New Win&amp;dow</source> <translation type="unfinished"></translation> </message> <message> <location filename="../view.cpp" line="114"/> <source>Open in Termina&amp;l</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PreferencesDialog</name> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="706"/> <source>Preferences</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="715"/> <source>User Interface</source> <translation type="unfinished">Uživatelské rozhraní</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="711"/> <source>Behavior</source> <translation type="unfinished">Chování</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="717"/> <location filename="../../build/pcmanfm/ui_preferences.h" line="779"/> <source>Thumbnail</source> <translation type="unfinished">Náhled</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="719"/> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="721"/> <source>Advanced</source> <translation type="unfinished">Pokročilé</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="742"/> <source>Icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="744"/> <source>Size of big icons:</source> <translation type="unfinished">Velikost velkých ikon:</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="745"/> <source>Size of small icons:</source> <translation type="unfinished">Velikost malých ikon:</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="746"/> <source>Size of thumbnails:</source> <translation type="unfinished">Velikost náhledů:</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="747"/> <source>Size of side pane icons:</source> <translation type="unfinished">Velikost ikon v postranním panelu:</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="743"/> <source>Icon theme:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="753"/> <source>Window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="757"/> <source>Default width of new windows:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="758"/> <source>Default height of new windows:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="754"/> <source>Always show the tab bar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="755"/> <source>Show &apos;Close&apos; buttons on tabs </source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="756"/> <source>Remember the size of the last closed window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="724"/> <source>Browsing</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="725"/> <source>Open files with single click</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="726"/> <source>Delay of auto-selection in single click mode (0 to disable)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="727"/> <source>Default view mode:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="728"/> <source> sec</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="736"/> <source>File Operations</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="737"/> <source>Confirm before deleting files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="738"/> <source>Move deleted files to &quot;trash bin&quot; instead of erasing from disk.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="783"/> <source>Show thumbnails of files</source> <translation type="unfinished">Zobrazovat náhledy souborů</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="782"/> <source>Only show thumbnails for local files</source> <translation type="unfinished">Zobrazovat náhlet jen u lokálních souborů</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="713"/> <source>Display</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="729"/> <source>Bookmarks:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="732"/> <source>Open in current tab</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="733"/> <source>Open in new tab</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="734"/> <source>Open in new window</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="739"/> <source>Erase files on removable media instead of &quot;trash can&quot; creation</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="740"/> <source>Confirm before moving files into &quot;trash can&quot;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="741"/> <source>Don&apos;t ask options on launch executable file</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="748"/> <source>User interface</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="750"/> <source>Treat backup files as hidden</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="751"/> <source>Always show full file names</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="752"/> <source>Show icons of hidden files shadowed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="759"/> <source>Show in places</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="764"/> <source>Home</source> <translation type="unfinished">Domů</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="766"/> <source>Desktop</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="768"/> <source>Trash can</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="770"/> <source>Computer</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="772"/> <source>Applications</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="774"/> <source>Devices</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="776"/> <source>Network</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="780"/> <source>Do not generate thumbnails for image files exceeding this size:</source> <translation type="unfinished">Negenerovat náhledy obrázků přesahujících tuto velikost:</translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="781"/> <source> KB</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="784"/> <source>Auto Mount</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="785"/> <source>Mount mountable volumes automatically on program startup</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="786"/> <source>Mount removable media automatically when they are inserted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="787"/> <source>Show available options for removable media when they are inserted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="788"/> <source>When removable medium unmounted:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="789"/> <source>Close &amp;tab containing removable medium</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="790"/> <source>Chan&amp;ge folder in the tab to home folder</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="793"/> <source>Switch &amp;user command:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="796"/> <source>Archiver in&amp;tegration:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="797"/> <source>Templates</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="798"/> <source>Show only user defined templates in menu</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="799"/> <source>Show only one template for each MIME type</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="800"/> <source>Run default application after creation from template</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="791"/> <source>Programs</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="792"/> <source>Terminal emulator:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="794"/> <source>Examples: &quot;xterm -e %s&quot; for terminal or &quot;gksu %s&quot; for switching user. %s = the command line you want to execute with terminal or su.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../../build/pcmanfm/ui_preferences.h" line="749"/> <source>Use SI decimal prefixes instead of IEC binary prefixes</source> <translation type="unfinished"></translation> </message> </context> </TS>
rbazaud/pcmanfm-qt
pcmanfm/translations/pcmanfm-qt_cs_CZ.ts
TypeScript
gpl-2.0
53,147
/* * Copyright 2007 Sun Microsystems, Inc. * * This file is part of jVoiceBridge. * * jVoiceBridge is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation and distributed hereunder * to you. * * jVoiceBridge 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/>. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied this * code. */ package com.sun.mc.softphone.media.coreaudio; import com.sun.mc.softphone.media.NativeLibUtil; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.prefs.Preferences; import java.util.ArrayList; import com.sun.voip.Logger; import com.sun.mc.softphone.media.AudioServiceProvider; import com.sun.mc.softphone.media.Microphone; import com.sun.mc.softphone.media.Speaker; public class CoreAudioAudioServiceProvider implements AudioServiceProvider { private static final String CORE_AUDIO_NAME = "libMediaFramework.jnilib"; private static AudioDriver audioDriver; private Microphone microphone; private Speaker speaker; public CoreAudioAudioServiceProvider() throws IOException { Logger.println("Loading CoreAudio provider"); // load the libarary String arch = System.getProperty("os.arch"); String nativeLibraryName = CORE_AUDIO_NAME; Logger.println("Loading native library: " + nativeLibraryName); NativeLibUtil.loadLibrary(getClass(), nativeLibraryName); return; } public void initialize(int sampleRate, int channels, int microphoneSampleRate, int microphoneChannels, int microphoneBufferSize, int speakerBufferSize) throws IOException { shutdown(); // stop old driver if running audioDriver = new AudioDriverMac(); audioDriver.initialize(microphoneBufferSize, speakerBufferSize); Logger.println("Initializing audio driver to " + sampleRate + "/" + channels + " microphoneBufferSize " + microphoneBufferSize + " speakerBufferSize " + speakerBufferSize); /* * The speaker is always set to 2 channels. * Resampling is done if necessary. * * When set to 1 channel, sound only comes * out of 1 channel instead of 2. */ audioDriver.start( sampleRate, // speaker sample rate 2, // speaker channels 2*2, // speaker bytes per packet 1, // speaker frames per packet 2*2, // speaker frame size 16, // speaker bits per channel microphoneSampleRate,// microphone sample rate microphoneChannels, // microphone channels, 2*microphoneChannels,// microphone bytes per packet 1, // microphone frames per packet 2*microphoneChannels,// microphone bytes per frame 16); // microphone bits per channel initializeMicrophone(microphoneSampleRate, microphoneChannels, microphoneBufferSize); initializeSpeaker(sampleRate, channels, speakerBufferSize); } public void shutdown() { if (audioDriver != null) { audioDriver.stop(); audioDriver = null; } } public Microphone getMicrophone() { return microphone; } public String[] getMicrophoneList() { return new String[0]; } private void initializeMicrophone(int sampleRate, int channels, int microphoneBufferSize) throws IOException { microphone = new MicrophoneCoreAudioImpl(sampleRate, channels, microphoneBufferSize, audioDriver); } public Speaker getSpeaker() { return speaker; } public String[] getSpeakerList() { return new String[0]; } private void initializeSpeaker(int sampleRate, int channels, int speakerBufferSize) throws IOException { speaker = new SpeakerCoreAudioImpl(sampleRate, channels, speakerBufferSize, audioDriver); } }
damirkusar/jvoicebridge
softphone/src/com/sun/mc/softphone/media/coreaudio/CoreAudioAudioServiceProvider.java
Java
gpl-2.0
4,493
#!/usr/bin/env python3 import os import sys import subprocess if os.getenv("MSYSTEM") == "MINGW32": mingw_dir = "/mingw32" elif os.getenv("MSYSTEM") == "MINGW64": mingw_dir = "/mingw64" p = subprocess.Popen([ "sh", "-c", "cp {}/bin/{} {}".format(mingw_dir, sys.argv[1], sys.argv[2])]) sys.exit(p.wait())
cnvogelg/fs-uae
dist/windows/clib.py
Python
gpl-2.0
323
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ContactRole' db.create_table('base_contactrole', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('resource', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.ResourceBase'])), ('contact', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['people.Profile'])), ('role', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['people.Role'])), )) db.send_create_signal('base', ['ContactRole']) # Adding unique constraint on 'ContactRole', fields ['contact', 'resource', 'role'] db.create_unique('base_contactrole', ['contact_id', 'resource_id', 'role_id']) # Adding model 'TopicCategory' db.create_table('base_topiccategory', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=50)), ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)), ('description', self.gf('django.db.models.fields.TextField')(blank=True)), )) db.send_create_signal('base', ['TopicCategory']) # Adding model 'Thumbnail' db.create_table('base_thumbnail', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('thumb_file', self.gf('django.db.models.fields.files.FileField')(max_length=100)), ('thumb_spec', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('version', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0, null=True)), )) db.send_create_signal('base', ['Thumbnail']) # Adding model 'ResourceBase' db.create_table('base_resourcebase', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('uuid', self.gf('django.db.models.fields.CharField')(max_length=36)), ('owner', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=255)), ('date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)), ('date_type', self.gf('django.db.models.fields.CharField')(default='publication', max_length=255)), ('edition', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('abstract', self.gf('django.db.models.fields.TextField')(blank=True)), ('purpose', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('maintenance_frequency', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('keywords_region', self.gf('django.db.models.fields.CharField')(default='USA', max_length=3)), ('constraints_use', self.gf('django.db.models.fields.CharField')(default='copyright', max_length=255)), ('constraints_other', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('spatial_representation_type', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('language', self.gf('django.db.models.fields.CharField')(default='eng', max_length=3)), ('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.TopicCategory'], null=True, blank=True)), ('temporal_extent_start', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('temporal_extent_end', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('supplemental_information', self.gf('django.db.models.fields.TextField')(default=u'No information provided')), ('distribution_url', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('distribution_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('data_quality_statement', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('bbox_x0', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)), ('bbox_x1', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)), ('bbox_y0', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)), ('bbox_y1', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)), ('srid', self.gf('django.db.models.fields.CharField')(default='EPSG:4326', max_length=255)), ('csw_typename', self.gf('django.db.models.fields.CharField')(default='gmd:MD_Metadata', max_length=32)), ('csw_schema', self.gf('django.db.models.fields.CharField')(default='http://www.isotc211.org/2005/gmd', max_length=64)), ('csw_mdsource', self.gf('django.db.models.fields.CharField')(default='local', max_length=256)), ('csw_insert_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)), ('csw_type', self.gf('django.db.models.fields.CharField')(default='dataset', max_length=32)), ('csw_anytext', self.gf('django.db.models.fields.TextField')(null=True)), ('csw_wkt_geometry', self.gf('django.db.models.fields.TextField')(default='SRID=4326;POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))')), ('metadata_uploaded', self.gf('django.db.models.fields.BooleanField')(default=False)), ('metadata_xml', self.gf('django.db.models.fields.TextField')(default='<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>', null=True, blank=True)), ('thumbnail', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.Thumbnail'], null=True, blank=True)), )) db.send_create_signal('base', ['ResourceBase']) # Adding model 'Link' db.create_table('base_link', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('resource', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.ResourceBase'])), ('extension', self.gf('django.db.models.fields.CharField')(max_length=255)), ('link_type', self.gf('django.db.models.fields.CharField')(max_length=255)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), ('mime', self.gf('django.db.models.fields.CharField')(max_length=255)), ('url', self.gf('django.db.models.fields.TextField')(unique=True, max_length=1000)), )) db.send_create_signal('base', ['Link']) def backwards(self, orm): # Removing unique constraint on 'ContactRole', fields ['contact', 'resource', 'role'] db.delete_unique('base_contactrole', ['contact_id', 'resource_id', 'role_id']) # Deleting model 'ContactRole' db.delete_table('base_contactrole') # Deleting model 'TopicCategory' db.delete_table('base_topiccategory') # Deleting model 'Thumbnail' db.delete_table('base_thumbnail') # Deleting model 'ResourceBase' db.delete_table('base_resourcebase') # Deleting model 'Link' db.delete_table('base_link') models = { 'actstream.action': { 'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'}, 'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}), 'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}), 'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 384488)'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 388268)'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 388203)'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'relationships': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_to'", 'symmetrical': 'False', 'through': "orm['relationships.Relationship']", 'to': "orm['auth.User']"}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'base.contactrole': { 'Meta': {'unique_together': "(('contact', 'resource', 'role'),)", 'object_name': 'ContactRole'}, 'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Profile']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.ResourceBase']"}), 'role': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Role']"}) }, 'base.link': { 'Meta': {'object_name': 'Link'}, 'extension': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'link_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'mime': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.ResourceBase']"}), 'url': ('django.db.models.fields.TextField', [], {'unique': 'True', 'max_length': '1000'}) }, 'base.resourcebase': { 'Meta': {'object_name': 'ResourceBase'}, 'abstract': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'bbox_x0': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}), 'bbox_x1': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}), 'bbox_y0': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}), 'bbox_y1': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.TopicCategory']", 'null': 'True', 'blank': 'True'}), 'constraints_other': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'constraints_use': ('django.db.models.fields.CharField', [], {'default': "'copyright'", 'max_length': '255'}), 'contacts': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['people.Profile']", 'through': "orm['base.ContactRole']", 'symmetrical': 'False'}), 'csw_anytext': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'csw_insert_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'csw_mdsource': ('django.db.models.fields.CharField', [], {'default': "'local'", 'max_length': '256'}), 'csw_schema': ('django.db.models.fields.CharField', [], {'default': "'http://www.isotc211.org/2005/gmd'", 'max_length': '64'}), 'csw_type': ('django.db.models.fields.CharField', [], {'default': "'dataset'", 'max_length': '32'}), 'csw_typename': ('django.db.models.fields.CharField', [], {'default': "'gmd:MD_Metadata'", 'max_length': '32'}), 'csw_wkt_geometry': ('django.db.models.fields.TextField', [], {'default': "'SRID=4326;POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))'"}), 'data_quality_statement': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'date_type': ('django.db.models.fields.CharField', [], {'default': "'publication'", 'max_length': '255'}), 'distribution_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'distribution_url': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'edition': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keywords_region': ('django.db.models.fields.CharField', [], {'default': "'USA'", 'max_length': '3'}), 'language': ('django.db.models.fields.CharField', [], {'default': "'eng'", 'max_length': '3'}), 'maintenance_frequency': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'metadata_uploaded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'metadata_xml': ('django.db.models.fields.TextField', [], {'default': '\'<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>\'', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'purpose': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'spatial_representation_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'srid': ('django.db.models.fields.CharField', [], {'default': "'EPSG:4326'", 'max_length': '255'}), 'supplemental_information': ('django.db.models.fields.TextField', [], {'default': "u'No information provided'"}), 'temporal_extent_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'temporal_extent_start': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'thumbnail': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.Thumbnail']", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36'}) }, 'base.thumbnail': { 'Meta': {'object_name': 'Thumbnail'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'thumb_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), 'thumb_spec': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'version': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'null': 'True'}) }, 'base.topiccategory': { 'Meta': {'ordering': "('name',)", 'object_name': 'TopicCategory'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.profile': { 'Meta': {'object_name': 'Profile'}, 'area': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}), 'delivery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'organization': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'profile': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'profile'", 'unique': 'True', 'null': 'True', 'to': "orm['auth.User']"}), 'voice': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'zipcode': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'people.role': { 'Meta': {'object_name': 'Role'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'relationships.relationship': { 'Meta': {'ordering': "('created',)", 'unique_together': "(('from_user', 'to_user', 'status', 'site'),)", 'object_name': 'Relationship'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'from_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'from_users'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'site': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'related_name': "'relationships'", 'to': "orm['sites.Site']"}), 'status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['relationships.RelationshipStatus']"}), 'to_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'to_users'", 'to': "orm['auth.User']"}), 'weight': ('django.db.models.fields.FloatField', [], {'default': '1.0', 'null': 'True', 'blank': 'True'}) }, 'relationships.relationshipstatus': { 'Meta': {'ordering': "('name',)", 'object_name': 'RelationshipStatus'}, 'from_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'symmetrical_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'to_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'verb': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'sites.site': { 'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'taggit.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}) }, 'taggit.taggeditem': { 'Meta': {'object_name': 'TaggedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"}) } } complete_apps = ['base']
dwoods/gn-maps
geonode/base/migrations/0001_initial.py
Python
gpl-3.0
25,336
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import styles from './ModalFooter.css'; class ModalFooter extends Component { // // Render render() { const { children, ...otherProps } = this.props; return ( <div className={styles.modalFooter} {...otherProps} > {children} </div> ); } } ModalFooter.propTypes = { children: PropTypes.node }; export default ModalFooter;
Radarr/Radarr
frontend/src/Components/Modal/ModalFooter.js
JavaScript
gpl-3.0
485
package de.btu.openinfra.backend.db.rbac; import java.util.UUID; import de.btu.openinfra.backend.db.OpenInfraSchemas; import de.btu.openinfra.backend.db.daos.TopicCharacteristicToAttributeTypeGroupDao; import de.btu.openinfra.backend.db.jpa.model.AttributeTypeGroup; import de.btu.openinfra.backend.db.jpa.model.AttributeTypeGroupToTopicCharacteristic; import de.btu.openinfra.backend.db.jpa.model.TopicCharacteristic; import de.btu.openinfra.backend.db.pojos.TopicCharacteristicToAttributeTypeGroupPojo; public class TopicCharacteristicToAttributeTypeGroupRbac extends OpenInfraValueValueRbac<TopicCharacteristicToAttributeTypeGroupPojo, AttributeTypeGroupToTopicCharacteristic, AttributeTypeGroup, TopicCharacteristic, TopicCharacteristicToAttributeTypeGroupDao> { public TopicCharacteristicToAttributeTypeGroupRbac( UUID currentProjectId, OpenInfraSchemas schema) { super(currentProjectId, schema, AttributeTypeGroup.class, TopicCharacteristic.class, TopicCharacteristicToAttributeTypeGroupDao.class); } }
OpenInfRA/core
openinfra_core/src/main/java/de/btu/openinfra/backend/db/rbac/TopicCharacteristicToAttributeTypeGroupRbac.java
Java
gpl-3.0
1,063
/* * Thresher IRC client library * Copyright (C) 2002 Aaron Hunter <thresher@sharkbite.org> * * 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 2 * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * See the gpl.txt file located in the top-level-directory of * the archive of this library for complete text of license. */ using System; using System.Diagnostics; using System.Globalization; namespace Sharkbite.Irc { /// <summary> /// Constants and utility methods to support CTCP. /// </summary> /// <remarks>The CTCP constants should be used to test incoming /// CTCP queries for their type and as the CTCP command /// for outgoing ones.</remarks> public sealed class CtcpUtil { /// <summary>CTCP Finger.</summary> public const string Finger = "FINGER"; /// <summary>CTCP USERINFO.</summary> public const string UserInfo = "USERINFO"; /// <summary>CTCP VERSION.</summary> public const string Version = "VERSION"; /// <summary>CTCP SOURCE.</summary> public const string Source = "SOURCE"; /// <summary>CTCP CLIENTINFO.</summary> public const string ClientInfo = "CLIENTINFO"; /// <summary>CTCP ERRMSG.</summary> public const string ErrorMessage = "ERRMSG"; /// <summary>CTCP PING.</summary> public const string Ping = "PING"; /// <summary>CTCP TIME.</summary> public const string Time = "TIME"; internal static TraceSwitch CtcpTrace = new TraceSwitch("CtcpTraceSwitch", "Debug level for CTCP classes."); //Should never be called so make it private private CtcpUtil(){} /// <summary> /// Generate a timestamp string suitable for the CTCP Ping command. /// </summary> /// <returns>The current time as a string.</returns> public static string CreateTimestamp() { return DateTime.Now.ToFileTime().ToString( CultureInfo.InvariantCulture ); } } }
Dmitchell94/MCForge-Vanilla-Original
sharkbite.thresher/Ctcp/CtcpUtil.cs
C#
gpl-3.0
2,431
# encoding: UTF-8 # This file contains data derived from the IANA Time Zone Database # (http://www.iana.org/time-zones). module TZInfo module Data module Definitions module Europe module Minsk include TimezoneDefinition timezone 'Europe/Minsk' do |tz| tz.offset :o0, 6616, 0, :LMT tz.offset :o1, 6600, 0, :MMT tz.offset :o2, 7200, 0, :EET tz.offset :o3, 10800, 0, :MSK tz.offset :o4, 3600, 3600, :CEST tz.offset :o5, 3600, 0, :CET tz.offset :o6, 10800, 3600, :MSD tz.offset :o7, 7200, 3600, :EEST tz.offset :o8, 10800, 0, :'+03' tz.transition 1879, 12, :o1, -2840147416, 26003326573, 10800 tz.transition 1924, 5, :o2, -1441158600, 349042669, 144 tz.transition 1930, 6, :o3, -1247536800, 29113781, 12 tz.transition 1941, 6, :o4, -899780400, 19441387, 8 tz.transition 1942, 11, :o5, -857257200, 58335973, 24 tz.transition 1943, 3, :o4, -844556400, 58339501, 24 tz.transition 1943, 10, :o5, -828226800, 58344037, 24 tz.transition 1944, 4, :o4, -812502000, 58348405, 24 tz.transition 1944, 7, :o3, -804650400, 29175293, 12 tz.transition 1981, 3, :o6, 354920400 tz.transition 1981, 9, :o3, 370728000 tz.transition 1982, 3, :o6, 386456400 tz.transition 1982, 9, :o3, 402264000 tz.transition 1983, 3, :o6, 417992400 tz.transition 1983, 9, :o3, 433800000 tz.transition 1984, 3, :o6, 449614800 tz.transition 1984, 9, :o3, 465346800 tz.transition 1985, 3, :o6, 481071600 tz.transition 1985, 9, :o3, 496796400 tz.transition 1986, 3, :o6, 512521200 tz.transition 1986, 9, :o3, 528246000 tz.transition 1987, 3, :o6, 543970800 tz.transition 1987, 9, :o3, 559695600 tz.transition 1988, 3, :o6, 575420400 tz.transition 1988, 9, :o3, 591145200 tz.transition 1989, 3, :o6, 606870000 tz.transition 1989, 9, :o3, 622594800 tz.transition 1991, 3, :o7, 670374000 tz.transition 1991, 9, :o2, 686102400 tz.transition 1992, 3, :o7, 701827200 tz.transition 1992, 9, :o2, 717552000 tz.transition 1993, 3, :o7, 733276800 tz.transition 1993, 9, :o2, 749001600 tz.transition 1994, 3, :o7, 764726400 tz.transition 1994, 9, :o2, 780451200 tz.transition 1995, 3, :o7, 796176000 tz.transition 1995, 9, :o2, 811900800 tz.transition 1996, 3, :o7, 828230400 tz.transition 1996, 10, :o2, 846374400 tz.transition 1997, 3, :o7, 859680000 tz.transition 1997, 10, :o2, 877824000 tz.transition 1998, 3, :o7, 891129600 tz.transition 1998, 10, :o2, 909273600 tz.transition 1999, 3, :o7, 922579200 tz.transition 1999, 10, :o2, 941328000 tz.transition 2000, 3, :o7, 954028800 tz.transition 2000, 10, :o2, 972777600 tz.transition 2001, 3, :o7, 985478400 tz.transition 2001, 10, :o2, 1004227200 tz.transition 2002, 3, :o7, 1017532800 tz.transition 2002, 10, :o2, 1035676800 tz.transition 2003, 3, :o7, 1048982400 tz.transition 2003, 10, :o2, 1067126400 tz.transition 2004, 3, :o7, 1080432000 tz.transition 2004, 10, :o2, 1099180800 tz.transition 2005, 3, :o7, 1111881600 tz.transition 2005, 10, :o2, 1130630400 tz.transition 2006, 3, :o7, 1143331200 tz.transition 2006, 10, :o2, 1162080000 tz.transition 2007, 3, :o7, 1174780800 tz.transition 2007, 10, :o2, 1193529600 tz.transition 2008, 3, :o7, 1206835200 tz.transition 2008, 10, :o2, 1224979200 tz.transition 2009, 3, :o7, 1238284800 tz.transition 2009, 10, :o2, 1256428800 tz.transition 2010, 3, :o7, 1269734400 tz.transition 2010, 10, :o2, 1288483200 tz.transition 2011, 3, :o8, 1301184000 end end end end end end
somniumio/Somnium
vendor/cache/ruby/2.3.0/gems/tzinfo-data-1.2017.2/lib/tzinfo/data/definitions/Europe/Minsk.rb
Ruby
gpl-3.0
4,340
#include <stdio.h> #include "license_hash.hh" #ifdef DMALLOC #include <dmalloc.h> #endif #define STRLONG 4096 int main(int argc, const char* argv[]) { char license[STRLONG]; if (argc > 1) { if (GenerateTempKey(license, 4096, argv[1]) == 0) printf("%s", license); } else { printf("Usage: %s <hardware ID>\n", argv[0]); } return 0; }
Zengwn/ViewTouch-POS-System
main/temphash.cc
C++
gpl-3.0
401
/* * Copyright (c) 2007 by Fraunhofer IML, Dortmund. * All rights reserved. * * Project: myWMS */ package org.mywms.cactustest; import java.io.NotSerializableException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.mywms.model.ClearingItem; import org.mywms.model.ClearingItemOption; import org.mywms.model.ClearingItemOptionRetval; import org.mywms.model.Client; import org.mywms.res.BundleResolver; /** * @author aelbaz * @version $Revision: 599 $ provided by $Author: trautm $ */ public class ClearingItemServiceTest extends CactusTestInit { private ClearingItem clearingItem1 = null, clearingItem11 = null, clearingItem2 = null; public void testCreateItem() throws NotSerializableException { Client client = clientService.getSystemClient(); String host = "localhost"; String source1 = "Robot1"; String user1 = "Guest"; String messageResourceKey1 = "CLEARING_ITEM_MESSAGE_KEY"; String shortMessageResourceKey1 = "CLEARING_ITEM_SHORT_MESSAGE_KEY"; String[] messageParameters1 = { "f_001", "f_002" }; String[] shortMessageParameters1 = { "f_001", "f_002" }; ArrayList<ClearingItemOption> optionList = new ArrayList<ClearingItemOption>(); ArrayList<ClearingItemOptionRetval> retvalList = new ArrayList<ClearingItemOptionRetval>(); String[] messageParameters = { "eins", "zwei" }; ClearingItemOptionRetval retval1 = new ClearingItemOptionRetval(); ClearingItemOptionRetval retval2 = new ClearingItemOptionRetval(); retval1.setNameResourceKey("Date"); retval1.setType(Date.class); retvalList.add(retval1); retval2.setNameResourceKey("Dezimal"); retval2.setType(Integer.class); retvalList.add(retval2); ClearingItemOption options = new ClearingItemOption(); options.setMessageResourceKey("CLEARING_ITEM_OPTION_MESSAGE_KEY_1"); options.setMessageParameters(messageParameters); options.setRetvals(retvalList); optionList.add(options); String boundleName1 = "org.mywms.res.mywms-clearing"; String boundleName2 = "org.mywms.res.mywms-clear"; clearingItem1 = clearingItemService.create( client, host, source1, user1, messageResourceKey1, shortMessageResourceKey1, boundleName1, BundleResolver.class, shortMessageParameters1, messageParameters1, optionList); clearingItem1.setSolution("admin", options); clearingItem1 = clearingItemService.merge(clearingItem1); assertNotNull("Das Object wurde nicht erzeugt", clearingItem1); String source2 = "Robot2"; String user2 = "Guest2"; String message2 = "Das Problem liegt am Fach2"; String shortMessage2 = "Problem Nummer 2"; String messageResourceKey2 = "CLEARING_ITEM_MESSAGE_"; String shortMessageResourceKey2 = "CLEARING_ITEM_SHORT_MESSAGE_KEY"; String[] messageParameters2 = { "f_001", "f_002" }; String[] shortMessageParameters2 = { "f_001", "f_002" }; clearingItem11 = clearingItemService.create( client, host, source1, user1, messageResourceKey1, shortMessageResourceKey1, boundleName1, BundleResolver.class, shortMessageParameters1, messageParameters1, optionList); assertNotNull("Das Object wurde nicht erzeugt", clearingItem11); clearingItem2 = clearingItemService.create( client, host, source2, user2, messageResourceKey2, shortMessageResourceKey2, boundleName2, BundleResolver.class, shortMessageParameters2, messageParameters2, optionList); assertNotNull("Das Object wurde nicht erzeugt", clearingItem2); } public void testGetUser() { List<String> listUsers = clearingItemService.getUser(null); assertEquals("Guest", listUsers.get(0)); } public void testGetSource() { List<String> listSources = clearingItemService.getSources(null); assertEquals("Robot1", listSources.get(0)); } public void testGetHosts() { List<String> listHosts = clearingItemService.getHosts(null); assertEquals("localhost", listHosts.get(0)); } public void testGetChronologicalLiVoidst() { String client = clientService.getSystemClient().getNumber(); List<ClearingItem> list = clearingItemService.getChronologicalList( client, "localhost", "Robot1", "user1", 3); assertEquals("falsche Nummer", 0, list.size()); list = clearingItemService.getChronologicalList( client, "localhost", "Robot1", "Guest", 2); assertEquals("falsche Nummer", 2, list.size()); } public void testGetNondealChronologicalList() { String client = clientService.getSystemClient().getNumber(); List<ClearingItem> list = clearingItemService.getNondealChronologicalList( client, "localhost", "Robot1", "Guest", 5); assertEquals("falsche Nummer", 1, list.size()); } }
tedvals/mywms
server.app/mywms.as/cactus/src/org/mywms/cactustest/ClearingItemServiceTest.java
Java
gpl-3.0
6,345
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.radio.bindings.providers; import com.codahale.metrics.MetricRegistry; import org.graylog2.plugin.ServerStatus; import org.graylog2.radio.Configuration; import org.graylog2.radio.transports.RadioTransport; import org.graylog2.radio.transports.amqp.AMQPProducer; import org.graylog2.radio.transports.kafka.KafkaProducer; import javax.inject.Inject; import javax.inject.Provider; /** * @author Dennis Oelkers <dennis@torch.sh> */ public class RadioTransportProvider implements Provider<RadioTransport> { private final Configuration configuration; private final MetricRegistry metricRegistry; private final ServerStatus serverStatus; @Inject public RadioTransportProvider(Configuration configuration, MetricRegistry metricRegistry, ServerStatus serverStatus) { this.configuration = configuration; this.metricRegistry = metricRegistry; this.serverStatus = serverStatus; } @Override public RadioTransport get() { switch (configuration.getTransportType()) { case AMQP: return new AMQPProducer(metricRegistry, configuration, serverStatus); case KAFKA: return new KafkaProducer(serverStatus, configuration, metricRegistry); default: throw new RuntimeException("Cannot map transport type to transport."); } } }
berkeleydave/graylog2-server
graylog2-radio/src/main/java/org/graylog2/radio/bindings/providers/RadioTransportProvider.java
Java
gpl-3.0
2,065
# Phatch - Photo Batch Processor # Copyright (C) 2007-2008 www.stani.be # # 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/ # # Phatch recommends SPE (http://pythonide.stani.be) for editing python files. # Embedded icon is taken from www.openclipart.org (public domain) # Follows PEP8 from core import models from lib.reverse_translation import _t #---PIL def init(): global Image, imtools from PIL import Image from lib import imtools def transpose(image, method, amount=100): transposed = image.transpose(getattr(Image, method)) if amount < 100: transposed = imtools.blend(image, transposed, amount / 100.0) return transposed #---Phatch class Action(models.Action): """""" label = _t('Transpose') author = 'Stani' email = 'spe.stani.be@gmail.com' init = staticmethod(init) pil = staticmethod(transpose) version = '0.1' tags = [_t('default'), _t('transform')] __doc__ = _t('Flip or rotate 90 degrees') def interface(self, fields): fields[_t('Method')] = self.ImageTransposeField( 'Orientation') fields[_t('Amount')] = self.SliderField(100, 1, 100) def apply(self, photo, setting, cache): #get info info = photo.info #dpi method = self.get_field('Method', info) #special case turn to its orientation if method == 'ORIENTATION': photo._exif_transposition_reverse = () info['orientation'] = 1 else: amount = self.get_field('Amount', info) layer = photo.get_layer() layer.image = transpose(layer.image, method, amount) return photo icon = \ 'x\xda\x01`\t\x9f\xf6\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x000\x00\ \x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\x00\x00\x00\x04sBIT\x08\x08\x08\ \x08|\x08d\x88\x00\x00\t\x17IDATh\x81\xed\xd9{\x8c\x9c\xd5y\x06\xf0\xdf\x99o\ \xee3{\xb7Y_\xd6\xd8\xd8\xa6\xc4.\x94\xe2[q\xa0\x01\n\xa8n\xa4\xc4$\xa2T\t\ \xa9ZE\x15\x94^\x94J\xf9\xa3\x89Z\xb5RD\xa4\xa4Q/\x8a\x8aZH\xa2DjU\x13\xa5\ \x8dTTD\x1b \x89"\x07\x1a\xb0MK|\xc7\xb0x\xb1\x8d\xbd\xbe\xad\xed\xf5\xce^f\ \xe6\xeb\x1f\xdf7\xde\xf5\xb2\xbe\x82eU\xf2;:\xfaFG\xe7;\xf3<\xefy\xcf{\x9e\ \xf7L\x88\xe3\xd8\xffg\xcb\\m\x00\xef\xd7\xae\x11\xb8\xdav\x8d\xc0\xd5\xb6\ \x0f\x8c@\x08!\x84\xef\x85(\xbc\x1bz\xc2\xa9\xb0$\x8c\x86\x15\xeb\xeb\xf7\ \xaf\xfe\xa0\xe6?\x97e/\xf7\xc5 T5\xdd#\xb6J\xb0R\xc3J\x19\xbd\x08\xad1\x1d\ \xa7\xdb\x07C.\xf4\xa1\x1e_\xa1|}I\x04\x82P\xc4G\xc5>-\xf8\xa8\x8c\xd2L\xe3\ \xf2r\xe6\x98-;\x92\x9b\x85v\x9c\xc4\xc4\xfb\x87\xfb^\xbb(\x02A\xc8\xe3Q\xfc\ \x19z\'}\xccrK\xac\xf3\x11\xd7\x9b\xaf\xcf\\\x9d\xcd\x0ec\x13\x13\xf6\xd7\ \x06m;\xb2;\xc6,\xd4B\x08Wd\x15.H \x08\x0f\xe1k\xb8~\xf2\xa5\xc8}\xd6\xfa\ \x8c\x8f\xcb\xd5r\xbe\xfb\xf3\xe7\xfc\xd7\xde\x8d\xf6\xed?\xe8\xc4\x89S\x93/\ \x1f7\x81N\x1cD\xed\x83\x06\x9f`97\xf0\x02\xfe\x0e\xbf?\xb5\xff~\xb7\xfb|\ \xfc\xbb\xb6\x1c\xde\xe1+?\xf9\x86\xad\xdb\xde8\xdf\xfc\x01EW0\xdb\xcdH \x08\ \x1dx\x01\xab\xa6\xf6?\xe0\x1e\x9f\xac\xdd\xe7\xe1o\x7f\xc1\xd1\xc3C\x17\x9e\ =N\xa7\xbb\x82\xf6\x1e\x02A\xc8\xe2_M\x03\xff)\xeb\xdc3\xbc\xdacO>\xee\xf4\ \xf0EF\xc3\x15\x85\x9e\xd8L+\xf0\xb7\xb8oj\xc7\x1dn\xb5v\xe8\x16\x7f\xfc\x8f\ _566~\xfe\x19\x9b\x92h\x1f\xc5\x90Q\xd4\xb5\xd6\xe2\n\xd8Y\x04\x82\xb0\x04\ \x8fM\x1f\xf4[\xf5\xfb}\xf1\xa9\xbf\x9f\x19\xfc)\xec\x17;\xa6\xee\xa4\x9a\ \x13F\x8c9i\xdc~M\x9b1\x82\xc6\x95\x81?}\x05b\x7f*\x88\xa6v\x95\x15m\xdb\xf3\ \x96\xd3\'k\xe4\xce\x8c\xe30\xde2a\xa7~\xfblWw\x14\xc3)\xe0S\xe9\x88~\x1c\ \xc5\xc4\xe5\xa4\xd0^\xe1\x96X\xe6\xf7\xb2\xc2my\xe1\x95\xa0\xfe\xe7\xfd\xe2\ \xd1s\x13\x08>9}\x929\xbam\xdd\xb3\'\t\r)\xc4\x97\x9d\xb2\xc7v\x87\xbc\x86\ \xfdx\x17\xc7qZ\x12<\xa3\xe9\xf7!\x9cp\x89\x87\xd8RaiS\xf4\xe5\xaa\xdc\x839!\ \x93\x93\x91\x13~U\x9c_\x182\xe1\xa1\xa9\xce8C \x0c\x86\xeb\\\xa7g\xfad\x03\ \x0ei\x1cl&^?\x81\xe7\xf5\xdb\xea9\xbc\x89\xbd)\xf8\x96\xf7\xc7%1\xdfL\x9fu\ \x89\x8c\xb8\xa8\x10\xbaSh\x1b\x92\xfbRI\xe1\xb1\x9cL\xa1 \x92\x13\xc9\xc9\ \xc8\xca\xc8\x86\xcc\x83\x85\xc3\x85;B\x08/\xc5q\xdc<\x8b\x80\xa6\x1bg\x9a\ \xb4\xaea\xa82\x9c\xf8\xf2G\xb6\xdb\xe5\xdf\xb0U\x12\x1e\x83\x12\x99\xd0\xda\ \xacM\x93\x1b6\x86\x8b\x0b\x9d\x10~E\xf1\xb3\xb1\xf2\xe3\x1d\xa29\x05Yy\x91\ \x82lJ \x92\x15\x89d\xc4\x13\xe3Or|U\x08a,\x8e\xe3f\x88\xe3X\x08!\xe3\x9f\ \xfd\x82\x87\xed\x98i\xfa\xcc\xcf\x82\xe6\xef\xc4[\xed\xf24\xb6`\x0f\x8eH\ \xe2\xbd\x8e\xe6\xe5\xca\x84{t\xdc>!\xfezV\xb4\xba(+iyy\xd9\xb4\xe5\xe4R\xf8\ \x91H\xdc\x08\xf1\xe6\'FV\xff\xf8s[\x7f\x1e\xc7\xf1x\x8b@\x1e\xbdF\xecU\x9a!\ {7\xb1\xce\x13\x9e\xf7\x1f\xd8\x99\x82\xaf\xbd\x1f\xe0\x0f=\x14\xa2#O\xb7\ \x7f=\x93\x89\x1e-\xcaE%yE9EyE\x05\x05yy\xb9\x94J\xf2\xc9\x88dd\x1c\xec\xcf\ \xbc\xfa\xd7\x8b\x9f\xb9\x0f\xc3Ar\xdc\x94\xb1\xc4F\xff\xeb\x8es\xfc\xe2\x88\ c\xbe\xe9S>\xe7\xa7\xa8\xb5b\xf0R-\x84\x10\x10=\xbc\x7f\xc5\xf7F\xe6\r>\x90E\ YAIAIQIQQQ!]\x87|\x1aHUU\x19\x19e%\xcdS\x1d\x8dO\xb4\xff\xc5B\x0cfS\x02y7X\ \x9e\xdd\x10\x89\xee\xc8\x18\x9b)i\x94u\xfb#\xff\xe2\xb3\xd6\xc5\xd5x\xd3\ \xe5\x80O-B[c\xdb\xdc_\x7f\xa4\xf33\x0e4\xf6\xdb1\xb1]\xb1kX9\x94\x94\x94S\ \x1ae\xf9t=\x96[.;1\xcb\xc9\xc6)\x13\x1a\xfef\xf3\x86 \x11\x89\xc7\'\t\xcc\ \xf2\xe1\xfa\xf6\x86y\x9bz\x1cXuT}\xa6\xb3\'\xa3G\xd5\x8bA\xf8C|7\x16_RzL\ \xbd\x9f\xc7\xac\xa7\xff\xf3\xd9\xf0\xf4K\xcfZ\xbc\xac\xcb\'~\xe3\x17\xcd\n\ \xb3\x95U\x95T\x94T\x15U\x14\x94\xcd\xb7\xc0\xe9Z\xd1\x9aG\x1f\x10\xb7\xc5\ \x898\x1f\x03\x1d\xc8g%J1\xabfL\x89\x81\xc7\x07\xad\xfd\x87\xe5^\x9e\xbb\xfd\ \\8\xda\xf1O\xf8Z\x10\x9e\xc2\x93\xb1\xf8\xc0\xc5r@\xae\xef\x97\xab\xf3f\xdf\ U\xce\xae\xbc\xbd\xcf\x87\xae\x9b\xaf\xa2\xaa\xa2]Y\x9b\x8a\x0ee\x1dJ\xdau\ \x99\xad\xd4\xe8\xb1\xe6K\xf7\x8a\'\xe2$\xaf\xb5Z\xa2r\xa3 9_\xe7(\xfa5\xb7\ \xfb\x8e<mK\xca\xee\xfd\xca\n\xcf\xb6\xff\xb7\t\xf5\x0b\x81\xaa\xe3Y\xbc\x8e\ \xfe\x0e\x06\xe6)\x0c\xfc\x81\xeb\x07F\x1d\xcf\xffT\xbc\xac){sQvY).\xddTi\ \x94\x96\xb6\x87\xca\r\x95\xa8R\xacjS\xd5\xae\xa2]U\xa7\x8aNU\xdd*\xba\xf5\ \x98\xab\x14\xf7X\xf5\xed\xfb\xed\xd9\xdc\x9f\xa4\x8d\x1e\xad\x15h\xfa+\xeb\ \xb0%\x9b\xf2i\x18uRAS\x909u`\xc4\x0f\xbe\xb8\xc9\x83_\xb8\xdb\xce\x05{\xbd\ \xe6\xbc\x9a?\x8b\xf5X_AQ\xc6\xb8\xa6o\xd9\xd7\xa8\xca\x85\x8a|\xa6*\xab\xa4\ \xa8\x1aJ\xaa\xd9\x8a\x8a\x8a\x16\xf8\xaa\x0eU]\xaa\xbaTt\xe94\xc7<\x8b\x1d\ \xa9\x8f\xfa\xd8\xf7\x7f\xd3\x9e\x81\xfed\xdd\xc2\x14\xef7\'\xc5a&\xed\x1a\ \xc7\xb0!\xbbEI\xef\xc8\xb1Q\x1b\xfe\xf2\x05\x85\x8d9\x8f4\xd6\xebT=\xef2\ \x94P\x96Q\x96Q\x12)\x8a\xa2\xa2l\xa6$\xa7$?-\xcb\x94\xcel\xd4\xc2\x946W\x9f\ \xde\xb8\xcfWw>\xe5\x86/\xdfj\xd3\x8e\xd7\xce\xfe\x91Q\x89\x1ax\xd3q\x89<\ \x89[\xc2-\x8b\x8a\xe3\xc6,u\xb7\xac \x97\xf4\xee\xdbq\xd8\xae\xd7\x07\xfc\ \xf6\x82u\xee\xec\xb8U\x1cb\x87\x1c\x9b\xea\x049\x94\x84\x94@\xa4,\xab,\xa7$\ 7%E\x16\x14\x15\x94\xce\x80Ozg\xbb\xce"\x8b,\xb4\xd8\xff\x9c\x1cp\xf77>\xed\ \xb9M/L\x82\x0e\x92\xf0\xd9\xe8m\xbb\xbdm\x97\xedv\xda`\xcc6\x1ci\x1ddE\xcc\ \xc5j\xcb|\xde\xcd\xd6(pV+R\x99_t\xd7\x9d+\xac]\xfaK\xc6+u?\xf1\x9aWl\x951\ \xa6"\xa3*R\x15\xa9\xc8\xa9\xc8\xa9*\xa8(\xa8\xa4\xb9\xa5\xa2\xac\xaaj\x91\ \x85nt\xa3\xf9\x16zg\xac\xe6\x99\xbd/\xfb\xe6\x0f\xbf\xef\xddC\x87\xde\xbb\ \xb4\xa7\xf1\xef\xb6\xd9\xedE\x89\xee:$\x911o\xe2p\x8b@$\xc9.7\xe2\xc3V\xf9\ \x13\x1f\xb2Pi\x1a\x89\xfc\xe4\xbc\x9d}m\xee]\xb5\xc6G\xfan\xd3\xddV\xaaG\ \xf9\x89l\xc6\xb8a\'\x8c\x186\xa6\xa6K\xd5l]ztj\xd7)\x8a\xcbq\xa3\x19\xc5\ \xfbF\x872\xcf\xecy\xd5\x86\x1f\xfd\xe0\xecK\x80\xe96\x8e\xe7\rx\xd5\xb7$\ \xfa\xeb\xdd4\x88Z*w\xb4E\xe0L~\xc6r\xac\xb5\xc2#n1_\xc7\x14\x02\xe7\xbb\xc3\ (P\xe8\xcc\xea\xed\xea1\xaf\xb3[_\xc7\xacf\xbd!\x1c8z,\xbcsh\xd0\xe0\xe01\ \x8d\xfa%\xd45\'\xb1\xc9Q\x1b=\xa1\xe9g\xd8%\x91\xecc\x92\xf8\xaf\x9f\x11sH\ \x04]\x92[\xe7`\x19VZd\xbd\xb5n\xb3@\xb8\xb2w\x0bS\xac\x8e74\xbd\xe2u\xfd\ \x9e\xc1\xab\xd8!\t\x9d\x9a\xb42ii\xb03>\x8d\xe3\xb8\x19B\x18\x93H\xe4d\xaa\ \xb7\x8d\x18\xf2\x8e\xe5\xeer\xb3Ns]\xd9B\xfd 6;l\xab\x17\xd5l\x91\x84\xcd\ \xee\x14Sm\xa6\xba"L\x17\x93\xe9~(\xa2[r\x99u\x13n2\xcb\x1a\xcb\xac\xb4X\x9b\ ^\x89\xfc{\xbf\xd6*\x92\x06\xc5\xf6\x1a\xb6\xdb\x16\x87\xbd$\t\x977\xb0OR,\ \x8d\x9e\xab(z\x0f\x81\x94DF\xb2\'\xda\xd0\x8b\x05X\x8cE*n\xd2k\xb9\xc5\xfa\ \xccU\xd0\x9e\x8e*^\x04\xe0\x86dc\x8e\xe0\xb0X\xbfS\x0e\x180h\x871\xfdx\x1bo\ a@RS\x0fc\xfc|\xcawF\x02)\x89 \t\xb1b\nq\xb6$\xd5\xceK[\xaf\xb2>\xed\xfaT\ \xcc\xd6\xadS\xbb\xa2\x82HR\x0b\x06M\xb1\x11\r\xa7M\x186\xe6\xb4\x9a\t55\xc7\ \x1d\xf1\x86q\x07$\xb1}\xd0d\x8a<b\xb2\xcak\\\xa8\xde8\'\x81)D2)\x91\x02*\ \x12\x15\xd8-Q&\xdd\xe8\x92H\xdb\xaa$\xb0\xf2\xe9\xf8H\xe2\xf3\xba\xc4\xef\ \xadb\x7f$\x05xtJ\x1b\x92\xdcd\x8cH\xb2L\xfdb\xeb\x8d\x0b\x12\x98F$\x92\x1c\ \xbcy\x89z\xa8LiE\x93\xa7E\x94\xb6Vq?\x91\x92\x18O\x01\x8e\x98\xbc\x82\xa9\ \x99r\x19p\xa9\x85\xd2E\x13\x98B\xa4%\xadZ \xb3&=\x9e*\xa93-\x11\x8a\t\x91\ \xd6s\xea\x8dE\xab/\xbe\xdc\xd2\xf4\x92\t\xcc@\x86I\xbdh\x86\xe7\xa4\x82\xbf\ \xac\x1b\x8b\x0b`\xb8\xf6O\xfdU\xb6k\x04\xae\xb6]#p\xb5\xed\xff\x00\xffpD!\ \x93;\xfd \x00\x00\x00\x00IEND\xaeB`\x82j\x88\xbf\xb5'
anish/phatch
phatch/actions/transpose.py
Python
gpl-3.0
9,462
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core'; import { DatePipe, Location } from '@angular/common'; import { addYears, subYears, addDays, startOfMonth, endOfMonth, getMonth, getYear, isToday, isValid } from 'date-fns'; import { CalendarDateFormatter, CalendarMonthViewDay, CalendarEvent } from 'angular-calendar'; import { CustomDateFormatter } from './custom-date-formatter.provider'; import { Observable, BehaviorSubject, Subject } from 'rxjs/Rx'; import { AdminApi } from '../../remote'; import { Router, ActivatedRoute, Params } from '@angular/router'; import { MatSnackBar } from '@angular/material'; @Component({ selector: 'app-holidays', templateUrl: './holidays.component.html', styleUrls: ['./holidays.component.css'], providers: [ { provide: CalendarDateFormatter, useClass: CustomDateFormatter } ], encapsulation: ViewEncapsulation.None }) export class HolidaysComponent implements OnInit { public showLoadSpinner = true; @ViewChild('picker') public picker1: any; // calendar properties https://mattlewis92.github.io/angular-calendar/ public view: string = 'month'; public viewYear: BehaviorSubject<Date> = new BehaviorSubject<Date>(new Date()); public viewYearNumber: number; public locale: string = 'en'; public yearMonths: Date[] = []; public refresh: Subject<any> = new Subject(); public holidaysSaveDisabled: boolean = false; private sub: any; //public holidays: CalendarMonthViewDay[] = []; public holidays: Map<String, CalendarMonthViewDay> = new Map<String, CalendarMonthViewDay>(); constructor(private adminService: AdminApi, private datePipe: DatePipe, private route: ActivatedRoute, private location: Location, public snackBar: MatSnackBar //private router: Router ) { } ngOnInit() { this.viewYear.subscribe(date => { this.showLoadSpinner = true; this.viewYearNumber = date.getFullYear(); this.getHolidays(this.viewYearNumber); }) this.sub = this.route.params.subscribe(params => { let yearDate = new Date(+params['year'], 0, 1, 0, 0, 0); // (+) converts string 'year' to a number if (isValid(yearDate)) { this.viewYear.next(yearDate); } }); } public getHolidays(year) { this.location.replaceState("admin/globalSettings/holidays/"+year); this.adminService.globalsettingsHolidaysYearGet(year).subscribe(holidays => { // console.log(holidays); this.holidays = new Map<String, CalendarMonthViewDay>(); for (let holiday of holidays) { let dtStr = this.datePipe.transform(holiday, 'yyyy-MM-dd'); let calDay: CalendarMonthViewDayImp = new CalendarMonthViewDayImp(); calDay.date = holiday; this.holidays.set(dtStr, calDay); } this.buildMonths(year); this.refresh.next(); this.showLoadSpinner = false; }); } public setHolidays() { this.holidaysSaveDisabled = true; this.showLoadSpinner = true; let holidays: string[] = Array.from(this.holidays, x => this.datePipe.transform(x[1].date, 'yyyy-MM-dd')); this.adminService.globalsettingsHolidaysYearPost(this.viewYearNumber, holidays).subscribe(response => { //console.log(response); this.holidaysSaveDisabled = false; this.showLoadSpinner = false; this.openSnackBar('Holidays saved!', 'ok', true); }, error => { this.openSnackBar('Holidays could not be saved!', 'ok', false); }); } ngAfterViewInit() { } buildMonths(year: number) { for (let i = 0; i < 12; i++) { this.yearMonths[i] = new Date(year, i); } //console.log("build"); } prevYear() { this.viewYear.next(subYears(this.viewYear.getValue(), 1)); } nextYear() { this.viewYear.next(addYears(this.viewYear.getValue(), 1)); } clickedDate(day: CalendarMonthViewDay, monthDate: Date) { if (monthDate.getMonth() !== day.date.getMonth()) { return; } let dtStr = this.datePipe.transform(day.date, 'yyyy-MM-dd'); let holiday: CalendarMonthViewDay = this.holidays.get(dtStr); if (!holiday) { day.cssClass = 'cal-day-selected'; this.holidays.set(dtStr, day); } else { delete day.cssClass; this.holidays.delete(dtStr); } //console.log(this.holidays); } beforeMonthViewRender({ body }: { body: CalendarMonthViewDay[] }): void { body.forEach(day => { let dtStr = this.datePipe.transform(day.date, 'yyyy-MM-dd'); let holiday: CalendarMonthViewDay = this.holidays.get(dtStr); if (holiday) { day.cssClass = 'cal-day-selected'; } }); } // success and error snackBars private openSnackBar(message: string, action: string, timeOut: boolean) { if (timeOut) { this.snackBar.open(message, action, { duration: 5000, extraClasses: ['success-snack-bar'] }); } else { this.snackBar.open(message, action, { extraClasses: ['error-snack-bar'] }); } } } class CalendarMonthViewDayImp implements CalendarMonthViewDay { inMonth: boolean; events: CalendarEvent[]; backgroundColor?: string; badgeTotal: number; meta?: any; date: Date; isPast: any; isToday; isFuture; isWeekend; }
jrtdev/yum
yumfe/src/app/admin/holidays/holidays.component.ts
TypeScript
gpl-3.0
5,296
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipaySecurityProdFingerprintApplyResponse. /// </summary> public class AlipaySecurityProdFingerprintApplyResponse : AopResponse { /// <summary> /// IFAA标准中的校验类型,目前1为指纹 /// </summary> [XmlElement("auth_type")] public string AuthType { get; set; } /// <summary> /// 设备的唯一ID,IFAA标准体系中的设备的唯一标识,用于关联设备的开通状态 /// </summary> [XmlElement("device_id")] public string DeviceId { get; set; } /// <summary> /// IFAA标准中用于关联IFAA Server和业务方Server开通状态的token,此token用于后续校验和注销操作。 /// </summary> [XmlElement("token")] public string Token { get; set; } } }
ColgateKas/cms
source/BaiRong.Core/ThirdParty/Alipay/openapi/Response/AlipaySecurityProdFingerprintApplyResponse.cs
C#
gpl-3.0
926
/* Avuna HTTPD - General Server Applications Copyright (C) 2015 Maxwell Bruce 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/>. */ package org.avuna.httpd.http; import java.text.SimpleDateFormat; import org.avuna.httpd.AvunaHTTPD; import org.avuna.httpd.http.event.EventMethodLookup; import org.avuna.httpd.http.networking.RequestPacket; import org.avuna.httpd.http.networking.ResponsePacket; /** Creates a http response coming from the server. */ public class ResponseGenerator { /** Our constructor */ public ResponseGenerator() { } /** Date format that isn't being used. */ public static final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); /** Processes a request and fills in the ResponsePacket * * @param request the request * @param response the response to fill in * @return returns the success of handling the request. */ public static boolean process(RequestPacket request, ResponsePacket response) { // Check if httpVersion is compatible if (!request.httpVersion.equals("HTTP/1.1")) { // NOTE: StatusCode.NEEDS_HTTP_1_1?? if (request.httpVersion.equals("HTTP/1.0")) { request.headers.addHeader("Host", ""); } } try { // Logger.log("rg"); // response.headers.addHeader("Date", sdf.format(new Date())); timeless for optimization response.headers.addHeader("Server", "Avuna/" + AvunaHTTPD.VERSION); if (request.headers.hasHeader("Connection")) { response.headers.addHeader("Connection", request.headers.getHeader("Connection")); } if (request.host == null) { ResponseGenerator.generateDefaultResponse(response, StatusCode.INTERNAL_SERVER_ERROR); response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.INTERNAL_SERVER_ERROR, "The requested host was not found on this server. Please contratc your server administrator."); return false; } EventMethodLookup elm = new EventMethodLookup(request.method, request, response); request.host.eventBus.callEvent(elm); if (!elm.isCanceled()) { generateDefaultResponse(response, StatusCode.NOT_YET_IMPLEMENTED); response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.NOT_YET_IMPLEMENTED, "The requested URL " + request.target + " via " + request.method.name + " is not yet implemented."); return false; }else { // System.out.println((ah - start) / 1000000D + " start-ah"); // System.out.println((ah2 - ah) / 1000000D + " ah-ah2"); // System.out.println((ah3 - ah2) / 1000000D + " ah2-ah3"); // System.out.println((cur - ah3) / 1000000D + " ah3-cur"); return true; } }catch (Exception e) { request.host.logger.logError(e); generateDefaultResponse(response, StatusCode.INTERNAL_SERVER_ERROR); response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.INTERNAL_SERVER_ERROR, "The requested URL " + request.target + " caused a server failure."); return false; } } /** Generates the stausCode, httpVersion and reasonPhrase for the response * * @param response the response packet * @param status the status to set. */ public static void generateDefaultResponse(ResponsePacket response, StatusCode status) { response.statusCode = status.getStatus(); response.httpVersion = "HTTP/1.1"; response.reasonPhrase = status.getPhrase(); } }
JavaProphet/AvunaHTTPD-Java
src/org/avuna/httpd/http/ResponseGenerator.java
Java
gpl-3.0
4,004
<?php $graph_type = "toner_usage"; $toners = dbFetchRows("SELECT * FROM `toner` WHERE device_id = ?", array($device['device_id'])); if (count($toners)) { echo("<div style='background-color: #eeeeee; margin: 5px; padding: 5px;'>"); echo("<p style='padding: 0px 5px 5px;' class=sectionhead>"); echo('<a class="sectionhead" href="device/device='.$device['device_id'].'/tab=toner/">'); echo("<img align='absmiddle' src='images/icons/toner.png'> Toner</a></p>"); echo("<table width=100% cellspacing=0 cellpadding=5>"); foreach ($toners as $toner) { $percent = round($toner['toner_current'], 0); $total = formatStorage($toner['toner_size']); $free = formatStorage($toner['toner_free']); $used = formatStorage($toner['toner_used']); $background = toner2colour($toner['toner_descr'], $percent); $graph_array = array(); $graph_array['height'] = "100"; $graph_array['width'] = "210"; $graph_array['to'] = $config['time']['now']; $graph_array['id'] = $toner['toner_id']; $graph_array['type'] = $graph_type; $graph_array['from'] = $config['time']['day']; $graph_array['legend'] = "no"; $link_array = $graph_array; $link_array['page'] = "graphs"; unset($link_array['height'], $link_array['width'], $link_array['legend']); $link = generate_url($link_array); $overlib_content = generate_overlib_content($graph_array, $device['hostname'] . " - " . $toner['toner_descr']); $graph_array['width'] = 80; $graph_array['height'] = 20; $graph_array['bg'] = 'ffffff00'; # the 00 at the end makes the area transparent. $minigraph = generate_graph_tag($graph_array); echo("<tr class=device-overview> <td class=tablehead>".overlib_link($link, $toner['toner_descr'], $overlib_content)."</td> <td width=90>".overlib_link($link, $minigraph, $overlib_content)."</td> <td width=200>".overlib_link($link, print_percentage_bar (200, 20, $percent, NULL, "ffffff", $background['left'], $percent . "%", "ffffff", $background['right']), $overlib_content)." </a></td> </tr>"); } echo("</table>"); echo("</div>"); } unset ($toner_rows); ?>
zylon-internet/librenms
html/pages/device/overview/toner.inc.php
PHP
gpl-3.0
2,200
(function($){ // Search var $searchWrap = $('#search-form-wrap'), isSearchAnim = false, searchAnimDuration = 200; var startSearchAnim = function(){ isSearchAnim = true; }; var stopSearchAnim = function(callback){ setTimeout(function(){ isSearchAnim = false; callback && callback(); }, searchAnimDuration); }; var s = [ '<div style="display: none;">', '<script src="https://s11.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>', '</div>' ].join(''); var di = $(s); $('#container').append(di); $('#nav-search-btn').on('click', function(){ if (isSearchAnim) return; startSearchAnim(); $searchWrap.addClass('on'); stopSearchAnim(function(){ $('.search-form-input').focus(); }); }); $('.search-form-input').on('blur', function(){ startSearchAnim(); $searchWrap.removeClass('on'); stopSearchAnim(); }); // Share $('body').on('click', function(){ $('.article-share-box.on').removeClass('on'); }).on('click', '.article-share-link', function(e){ e.stopPropagation(); var $this = $(this), url = $this.attr('data-url'), encodedUrl = encodeURIComponent(url), id = 'article-share-box-' + $this.attr('data-id'), offset = $this.offset(); if ($('#' + id).length){ var box = $('#' + id); if (box.hasClass('on')){ box.removeClass('on'); return; } } else { var html = [ '<div id="' + id + '" class="article-share-box">', '<input class="article-share-input" value="' + url + '">', '<div class="article-share-links">', '<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>', '<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>', '<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>', '<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>', '</div>', '</div>' ].join(''); var box = $(html); $('body').append(box); } $('.article-share-box.on').hide(); box.css({ top: offset.top + 25, left: offset.left }).addClass('on'); }).on('click', '.article-share-box', function(e){ e.stopPropagation(); }).on('click', '.article-share-box-input', function(){ $(this).select(); }).on('click', '.article-share-box-link', function(e){ e.preventDefault(); e.stopPropagation(); window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450'); }); // Caption $('.article-entry').each(function(i){ $(this).find('img').each(function(){ if ($(this).parent().hasClass('fancybox')) return; var alt = this.alt; if (alt) $(this).after('<span class="caption">' + alt + '</span>'); $(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>'); }); $(this).find('.fancybox').each(function(){ $(this).attr('rel', 'article' + i); }); }); if ($.fancybox){ $('.fancybox').fancybox(); } // Mobile nav var $container = $('#container'), isMobileNavAnim = false, mobileNavAnimDuration = 200; var startMobileNavAnim = function(){ isMobileNavAnim = true; }; var stopMobileNavAnim = function(){ setTimeout(function(){ isMobileNavAnim = false; }, mobileNavAnimDuration); } $('#main-nav-toggle').on('click', function(){ if (isMobileNavAnim) return; startMobileNavAnim(); $container.toggleClass('mobile-nav-on'); stopMobileNavAnim(); }); $('#wrap').on('click', function(){ if (isMobileNavAnim || !$container.hasClass('mobile-nav-on')) return; $container.removeClass('mobile-nav-on'); }); })(jQuery);
NiroDu/nirodu.github.io
themes/hiker/source/js/scripts.js
JavaScript
gpl-3.0
4,098
// I18N constants // LANG: "es-ar", ENCODING: UTF-8 | ISO-8859-1 // Author: Mihai Bazon, <mishoo@infoiasi.ro> // FOR TRANSLATORS: // // 1. PLEASE PUT YOUR CONTACT INFO IN THE ABOVE LINE // (at least a valid email address) // // 2. PLEASE TRY TO USE UTF-8 FOR ENCODING; // (if this is not possible, please include a comment // that states what encoding is necessary.) // // Traduccion al español - argentino // Juan Rossano <jrossano@care2x.org.ar> (2005) Grupo Biolinux SpellChecker.I18N = { "CONFIRM_LINK_CLICK" : "Por favor confirme que quiere abrir este enlace", "Cancel" : "Cancelar", "Dictionary" : "Diccionario", "Finished list of mispelled words" : "Terminada la lista de palabras sugeridas", "I will open it in a new page." : "Debe abrirse una nueva pagina.", "Ignore all" : "Ignorar todo", "Ignore" : "Ignorar", "NO_ERRORS" : "No se han hallado errores con este diccionario.", "NO_ERRORS_CLOSING" : "Correccion ortrografica completa, no se hallaron palabras erroneas. Cerrando ahora...", "OK" : "OK", "Original word" : "Palabra original", "Please wait. Calling spell checker." : "Por favor espere. Llamando al diccionario.", "Please wait: changing dictionary to" : "Por favor espere: Cambiando el diccionario a", "QUIT_CONFIRMATION" : "Esto deshace los cambios y quita el corrector. Por favor confirme.", "Re-check" : "Volver a corregir", "Replace all" : "Reemplazar todo", "Replace with" : "Reemplazar con", "Replace" : "Reemplazar", "SC-spell-check" : "Corregir ortografia", "Suggestions" : "Sugerencias", "pliz weit ;-)" : "Espere por favor ;-)" };
care2x/2.7
js/html_editor/plugins/SpellChecker/lang/es-ar.js
JavaScript
gpl-3.0
2,070
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.parsePairs = parsePairs; exports.createPairs = createPairs; exports.default = void 0; var _errors = require("../../errors"); var _Map = _interopRequireDefault(require("../../schema/Map")); var _Pair = _interopRequireDefault(require("../../schema/Pair")); var _parseSeq = _interopRequireDefault(require("../../schema/parseSeq")); var _Seq = _interopRequireDefault(require("../../schema/Seq")); function parsePairs(doc, cst) { var seq = (0, _parseSeq.default)(doc, cst); for (var i = 0; i < seq.items.length; ++i) { var item = seq.items[i]; if (item instanceof _Pair.default) continue;else if (item instanceof _Map.default) { if (item.items.length > 1) { var msg = 'Each pair must have its own sequence indicator'; throw new _errors.YAMLSemanticError(cst, msg); } var pair = item.items[0] || new _Pair.default(); if (item.commentBefore) pair.commentBefore = pair.commentBefore ? "".concat(item.commentBefore, "\n").concat(pair.commentBefore) : item.commentBefore; if (item.comment) pair.comment = pair.comment ? "".concat(item.comment, "\n").concat(pair.comment) : item.comment; item = pair; } seq.items[i] = item instanceof _Pair.default ? item : new _Pair.default(item); } return seq; } function createPairs(schema, iterable, ctx) { var pairs = new _Seq.default(); pairs.tag = 'tag:yaml.org,2002:pairs'; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var it = _step.value; var key = void 0, value = void 0; if (Array.isArray(it)) { if (it.length === 2) { key = it[0]; value = it[1]; } else throw new TypeError("Expected [key, value] tuple: ".concat(it)); } else if (it && it instanceof Object) { var keys = Object.keys(it); if (keys.length === 1) { key = keys[0]; value = it[key]; } else throw new TypeError("Expected { key: value } tuple: ".concat(it)); } else { key = it; } var pair = schema.createPair(key, value, ctx); pairs.items.push(pair); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return != null) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return pairs; } var _default = { default: false, tag: 'tag:yaml.org,2002:pairs', resolve: parsePairs, createNode: createPairs }; exports.default = _default;
mdranger/mytest
node_modules/yaml/browser/dist/tags/yaml-1.1/pairs.js
JavaScript
mpl-2.0
2,962
package common import ( "reflect" "testing" ) func TestVBoxBundleConfigPrepare_VBoxBundle(t *testing.T) { // Test with empty c := new(VBoxBundleConfig) errs := c.Prepare(testConfigTemplate(t)) if len(errs) > 0 { t.Fatalf("err: %#v", errs) } if !reflect.DeepEqual(*c, VBoxBundleConfig{BundleISO: false}) { t.Fatalf("bad: %#v", c) } // Test with a good one c = new(VBoxBundleConfig) c.BundleISO = true errs = c.Prepare(testConfigTemplate(t)) if len(errs) > 0 { t.Fatalf("err: %#v", errs) } expected := VBoxBundleConfig{ BundleISO: true, } if !reflect.DeepEqual(*c, expected) { t.Fatalf("bad: %#v", c) } }
bryson/packer
builder/virtualbox/common/vboxbundle_config_test.go
GO
mpl-2.0
638
package ro.code4.czl.scrape.client.representation; import java.util.List; /** * @author Ionut-Maxim Margelatu (ionut.margelatu@gmail.com) */ public class PublicationRepresentation { private String identifier; private String title; private String type; private String institution; private String date; private String description; private int feedback_days; private ContactRepresentation contact; private List<DocumentRepresentation> documents; public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getInstitution() { return institution; } public void setInstitution(String institution) { this.institution = institution; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getFeedback_days() { return feedback_days; } public void setFeedback_days(int feedback_days) { this.feedback_days = feedback_days; } public ContactRepresentation getContact() { return contact; } public void setContact(ContactRepresentation contact) { this.contact = contact; } public List<DocumentRepresentation> getDocuments() { return documents; } public void setDocuments(List<DocumentRepresentation> documents) { this.documents = documents; } public static final class PublicationRepresentationBuilder { private String identifier; private String title; private String type; private String institution; private String date; private String description; private int feedback_days; private ContactRepresentation contact; private List<DocumentRepresentation> documents; private PublicationRepresentationBuilder() { } public static PublicationRepresentationBuilder aPublicationRepresentation() { return new PublicationRepresentationBuilder(); } public PublicationRepresentationBuilder withIdentifier(String identifier) { this.identifier = identifier; return this; } public PublicationRepresentationBuilder withTitle(String title) { this.title = title; return this; } public PublicationRepresentationBuilder withType(String type) { this.type = type; return this; } public PublicationRepresentationBuilder withInstitution(String institution) { this.institution = institution; return this; } public PublicationRepresentationBuilder withDate(String date) { this.date = date; return this; } public PublicationRepresentationBuilder withDescription(String description) { this.description = description; return this; } public PublicationRepresentationBuilder withFeedback_days(int feedback_days) { this.feedback_days = feedback_days; return this; } public PublicationRepresentationBuilder withContact(ContactRepresentation contact) { this.contact = contact; return this; } public PublicationRepresentationBuilder withDocuments(List<DocumentRepresentation> documents) { this.documents = documents; return this; } public PublicationRepresentation build() { PublicationRepresentation publicationRepresentation = new PublicationRepresentation(); publicationRepresentation.setIdentifier(identifier); publicationRepresentation.setTitle(title); publicationRepresentation.setType(type); publicationRepresentation.setInstitution(institution); publicationRepresentation.setDate(date); publicationRepresentation.setDescription(description); publicationRepresentation.setFeedback_days(feedback_days); publicationRepresentation.setContact(contact); publicationRepresentation.setDocuments(documents); return publicationRepresentation; } } }
mgax/czl-scrape
munca/src/main/java/ro/code4/czl/scrape/client/representation/PublicationRepresentation.java
Java
mpl-2.0
4,287
<?php // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. return [ 'promote' => [ 'pin' => 'Sei sicuro di voler promuovere questa trasmissione in diretta?', 'unpin' => "Sei sicuro di voler rimuovere la promozione di questa trasmissione in diretta?", ], 'top-headers' => [ 'headline' => 'Livestream', 'description' => 'I dati vengono reperiti da twitch.tv ogni cinque minuti. Sei libero di porter avviare una diretta e di comparire sulla lista! Per maggiori informazioni su come iniziare, controlla :link.', 'link' => 'la pagina della wiki riguardante le trasmissioni', ], ];
ppy/osu-web
resources/lang/it/livestreams.php
PHP
agpl-3.0
759
package dlug // 0,1,2,3,4,5,6,7,8 var ByteLen []int = []int{1,2,3,4,5,6,8,9,17} var PfxBitLen []int = []int{1,2,3,5,5,5,8,8,8} var BitLen []uint = []uint{7,14,21,27,35,43,56,64,128} var Pfx []byte = []byte{0,0x80,0xc0,0xe0,0xe8,0xf0,0xf8,0xf9,0xfa,0xff} func Check(d []byte) bool { if len(d)==0 { return false } idx := GetDlugIndex(d) if idx<0 { return false } if idx>= len(ByteLen) { return false } if len(d) != ByteLen[idx] { return false } return true } func CheckCode(d []byte) int { if len(d)==0 { return -1 } idx := GetDlugIndex(d) if idx<0 { return -2 } if idx>= len(ByteLen) { return -3 } if len(d) != ByteLen[idx] { return -4 } return 0 } func EqualByte(d []byte, b byte) bool { if len(d)==0 { return false } if len(d)==1 { if (d[0]&(0x80)) != 0 { return false } if (d[0]&0x7f) == b { return true } return false } k := GetDlugIndex(d) if k<0 { return false } if d[0]&byte(0xff << (8-byte(PfxBitLen[k]))) != Pfx[k] { return false } n:=len(d) if d[n-1]!=b {return false} for i:=1; i<(n-1); i++ { if d[i]!=0 { return false } } return true } func GetDlugIndex(d []byte) int { if len(d)==0 { return -1 } for i:=0; i<len(ByteLen); i++ { if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] { return i } } return -2 } func GetByteLen(d []byte) int { if len(d)==0 { return -1 } for i:=0; i<len(ByteLen); i++ { if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] { return ByteLen[i] } } return -2 } func GetDataBitLen(d []byte) int { if len(d)==0 { return -1 } for i:=0; i<len(ByteLen); i++ { if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] { return int(BitLen[i]) } } return -2 } func GetPrefixBitLen(d []byte) int { if len(d)==0 { return -1 } for i:=0; i<len(ByteLen); i++ { if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] { return PfxBitLen[i] } } return -2 } //----------------------- // Marshal Byte Functions //----------------------- func MarshalByte(b byte) []byte { if b<(1<<BitLen[0]) { return []byte{b} } return []byte{ 0x80, b } } func MarshalUint32(u uint32) []byte { if u<(1<<BitLen[0]) { return []byte{ byte(u&0xff) } } if u<(1<<BitLen[1]) { return []byte{ byte(Pfx[1] | byte(0xff & (u>>8))), byte(0xff & u) } } if u<(1<<BitLen[2]) { return []byte{ byte(Pfx[2] | byte(0xff & (u>>16))), byte(0xff & (u>>8)), byte(0xff & u) } } if u<(1<<BitLen[3]) { return []byte{ byte(Pfx[3] | byte(0xff & (u>>24))), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } return []byte{ Pfx[4], byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } func MarshalUint64(u uint64) []byte { if u<(1<<BitLen[0]) { return []byte{ byte(u&0xff) } } if u<(1<<BitLen[1]) { return []byte{ byte(Pfx[1] | byte(0xff & (u>>8))), byte(0xff & u) } } if u<(1<<BitLen[2]) { return []byte{ byte(Pfx[2] | byte(0xff & (u>>16))), byte(0xff & (u>>8)), byte(0xff & u) } } if u<(1<<BitLen[3]) { return []byte{ byte(Pfx[3] | byte(0xff & (u>>24))), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } if u<(1<<BitLen[4]) { return []byte{ byte(Pfx[4] | byte(0xff & (u>>32))), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } if u<(1<<uint64(BitLen[5])) { return []byte{ byte(Pfx[5] | byte(0xff & (u>>40))), byte(0xff & (u>>32)), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } if u<(1<<uint64(BitLen[6])) { return []byte{ Pfx[6], byte(0xff & (u>>48)), byte(0xff & (u>>40)), byte(0xff & (u>>32)), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } return []byte{ Pfx[7], byte(0xff & (u>>56)), byte(0xff & (u>>48)), byte(0xff & (u>>40)), byte(0xff & (u>>32)), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) } } //--------------------- // Fill Slice Functions //--------------------- func FillSliceByte(s []byte, b byte) int { if len(s) == 0 { return -1 } if b<(1<<BitLen[0]) { s[0] = b; return 1 } if len(s) < 2 { return -1 } s[0] = 0x80 s[1] = b return 2 } func FillSliceUint32(s []byte, u uint32) int { if len(s)==0 { return -1 } if u<(1<<BitLen[0]) { s[0] = byte(u&0xff) return 1 } if len(s)<int(ByteLen[1]) { return -1 } if u<(1<<BitLen[1]) { s[0] = byte(Pfx[1] | byte(0xff & (u>>8))) s[1] = byte(0xff & u) return ByteLen[1] } if len(s)<ByteLen[2] { return -1 } if u<(1<<BitLen[2]) { s[0] = byte(Pfx[2] | byte(0xff & (u>>16))) s[1] = byte(0xff & (u>>8)) s[2] = byte(0xff & u) return ByteLen[2] } if len(s)<ByteLen[3] { return -1 } if u<(1<<BitLen[3]) { s[0] = byte(Pfx[3] | byte(0xff & (u>>24))) s[1] = byte(0xff & (u>>16)) s[2] = byte(0xff & (u>>8)) s[3] = byte(0xff & u) return ByteLen[3] } if len(s)<ByteLen[4] { return -1 } s[0] = Pfx[4] s[1] = byte(0xff & (u>>24)) s[2] = byte(0xff & (u>>16)) s[3] = byte(0xff & (u>>8)) s[4] = byte(0xff & u) return ByteLen[4] } func FillSliceUint64(s []byte, u uint64) int { if len(s)==0 { return -1 } if u<(1<<BitLen[0]) { s[0] = byte(u&0xff) return 1 } if len(s)<ByteLen[1] { return -1 } if u<(1<<BitLen[1]) { s[0] = byte(Pfx[1] | byte(0xff & (u>>8))) s[1] = byte(0xff & u) return ByteLen[1] } if len(s)<ByteLen[2] { return -1 } if u<(1<<BitLen[2]) { s[0] = byte(Pfx[2] | byte(0xff & (u>>16))) s[1] = byte(0xff & (u>>8)) s[2] = byte(0xff & u) return ByteLen[2] } if len(s)<ByteLen[3] { return -1 } if u<(1<<BitLen[3]) { s[0] = byte(Pfx[3] | byte(0xff & (u>>24))) s[1] = byte(0xff & (u>>16)) s[2] = byte(0xff & (u>>8)) s[3] = byte(0xff & u) return ByteLen[3] } if len(s)<ByteLen[4] { return -1 } if u<(1<<BitLen[4]) { s[0] = Pfx[4] | byte(0xff & (u>>32)) s[1] = byte(0xff & (u>>24)) s[2] = byte(0xff & (u>>16)) s[3] = byte(0xff & (u>>8)) s[4] = byte(0xff & u) return ByteLen[4] } if len(s)<ByteLen[5] { return -1 } if u<(1<<uint64(BitLen[5])) { s[0] = Pfx[5] | byte(0xff & (u>>40)) s[1] = byte(0xff & (u>>32)) s[2] = byte(0xff & (u>>24)) s[3] = byte(0xff & (u>>16)) s[4] = byte(0xff & (u>>8)) s[5] = byte(0xff & u) return ByteLen[5] } if len(s)<ByteLen[6] { return -1 } if u<(1<<uint64(BitLen[6])) { s[0] = Pfx[6] s[1] = byte(0xff & (u>>48)) s[2] = byte(0xff & (u>>40)) s[3] = byte(0xff & (u>>32)) s[4] = byte(0xff & (u>>24)) s[5] = byte(0xff & (u>>16)) s[6] = byte(0xff & (u>>8)) s[7] = byte(0xff & u) return ByteLen[6] } if len(s)<ByteLen[7] { return -1 } s[0] = Pfx[7] s[1] = byte(0xff & (u>>56)) s[2] = byte(0xff & (u>>48)) s[3] = byte(0xff & (u>>40)) s[4] = byte(0xff & (u>>32)) s[5] = byte(0xff & (u>>24)) s[6] = byte(0xff & (u>>16)) s[7] = byte(0xff & (u>>8)) s[8] = byte(0xff & u) return ByteLen[7] } //------------------ // Convert Functions //------------------ func ConvertByte(b []byte) (byte, int) { idx := GetDlugIndex(b) if idx<0 { return 0,idx } if idx==0 { return b[0]&0x7f,1 } if len(b) < ByteLen[idx] { return 0,-1 } return b[ByteLen[idx]-1], ByteLen[idx] } func ConvertUint32(b []byte) (uint32, int) { idx := GetDlugIndex(b) if idx<0 { return 0,idx } if idx==0 { return uint32(b[0]&0x7f),1 } if len(b) < ByteLen[idx] { return 0,-1 } if idx==1 { return (uint32(b[0]&(^Pfx[1])) << 8) + uint32(b[1]), 2 } if idx==2 { return (uint32(b[0]&(^Pfx[2])) << 16) + (uint32(b[1])<<8) + uint32(b[2]), 3 } if idx==3 { return (uint32(b[0]&(^Pfx[3])) << 24) + (uint32(b[1])<<16) + (uint32(b[2])<<8) + uint32(b[3]), 4 } n := ByteLen[idx] return (uint32(b[n-4])<<24) + (uint32(b[n-3])<<16) + (uint32(b[n-2])<<8) + uint32(b[n-1]), n } func ConvertUint64(b []byte) (uint64, int) { idx := GetDlugIndex(b) if idx<0 { return 0,idx } if idx==0 { return uint64(b[0]&0x7f),1 } if len(b) < ByteLen[idx] { return 0,-1 } if idx==1 { return (uint64(b[0]&(^Pfx[1]))<<8) + uint64(b[1]), 2 } if idx==2 { return (uint64(b[0]&(^Pfx[2])) << 16) + (uint64(b[1])<<8) + uint64(b[2]), 3 } if idx==3 { return (uint64(b[0]&(^Pfx[3])) << 24) + (uint64(b[1])<<16) + (uint64(b[2])<<8) + uint64(b[3]), 4 } if idx==4 { return (uint64(b[0]&(^Pfx[4])) << 32) + (uint64(b[1])<<24) + (uint64(b[2])<<16) + (uint64(b[3])<<8) + uint64(b[4]), 5 } if idx==5 { return (uint64(b[0]&(^Pfx[5])) << 40) + (uint64(b[1])<<32) + (uint64(b[2])<<24) + (uint64(b[3])<<16) + (uint64(b[4])<<8) + uint64(b[5]), 6 } if idx==6 { return (uint64(b[1])<<48) + (uint64(b[2])<<40) + (uint64(b[3])<<32) + (uint64(b[4])<<24) + (uint64(b[5])<<16) + (uint64(b[6])<<8) + uint64(b[7]), 8 } if idx==6 { return (uint64(b[1])<<48) + (uint64(b[2])<<40) + (uint64(b[3])<<32) + (uint64(b[4])<<24) + (uint64(b[5])<<16) + (uint64(b[6])<<8) + uint64(b[7]), 8 } n := ByteLen[idx] return (uint64(b[n-8])<<56) + (uint64(b[n-7])<<48) + (uint64(b[n-6])<<40) + (uint64(b[n-5])<<32) + (uint64(b[n-4])<<24) + (uint64(b[n-3])<<16) + (uint64(b[n-2])<<8) + uint64(b[n-1]), n }
curoverse/l7g
tools/cglf-tools/dlug/.save/cp2/dlug.go
GO
agpl-3.0
9,203
/* * Copyright 2010-2012 Fabric Engine Inc. All rights reserved. */ #include <Fabric/Core/MR/ConstArray.h> #include <Fabric/Core/RT/FixedArrayDesc.h> #include <Fabric/Core/RT/Manager.h> #include <Fabric/Core/RT/VariableArrayDesc.h> #include <Fabric/Base/JSON/Decoder.h> #include <Fabric/Base/JSON/Encoder.h> #include <Fabric/Base/Exception.h> namespace Fabric { namespace MR { RC::Handle<ConstArray> ConstArray::Create( RC::ConstHandle<RT::Manager> const &rtManager, RC::ConstHandle<RT::Desc> const &elementDesc, JSON::Entity const &entity ) { return new ConstArray( rtManager, elementDesc, entity ); } RC::Handle<ConstArray> ConstArray::Create( RC::ConstHandle<RT::Manager> const &rtManager, RC::ConstHandle<RT::ArrayDesc> const &arrayDesc, void const *data ) { return new ConstArray( rtManager, arrayDesc, data ); } ConstArray::ConstArray( RC::ConstHandle<RT::Manager> const &rtManager, RC::ConstHandle<RT::Desc> const &elementDesc, JSON::Entity const &entity ) { entity.requireArray(); m_fixedArrayDesc = rtManager->getFixedArrayOf( elementDesc, entity.value.array.size ); m_data.resize( m_fixedArrayDesc->getAllocSize(), 0 ); m_fixedArrayDesc->decodeJSON( entity, &m_data[0] ); } ConstArray::ConstArray( RC::ConstHandle<RT::Manager> const &rtManager, RC::ConstHandle<RT::ArrayDesc> const &arrayDesc, void const *data ) { RC::ConstHandle<RT::Desc> elementDesc = arrayDesc->getMemberDesc(); size_t count = arrayDesc->getNumMembers( data ); m_fixedArrayDesc = rtManager->getFixedArrayOf( elementDesc, count ); m_data.resize( m_fixedArrayDesc->getAllocSize(), 0 ); for ( size_t i=0; i<count; ++i ) elementDesc->setData( arrayDesc->getImmutableMemberData( data, i ), m_fixedArrayDesc->getMutableMemberData( &m_data[0], i ) ); } ConstArray::~ConstArray() { m_fixedArrayDesc->disposeData( &m_data[0] ); } RC::ConstHandle<RT::Desc> ConstArray::getElementDesc() const { return m_fixedArrayDesc->getMemberDesc(); } const RC::Handle<ArrayProducer::ComputeState> ConstArray::createComputeState() const { return ComputeState::Create( this ); } RC::Handle<ConstArray::ComputeState> ConstArray::ComputeState::Create( RC::ConstHandle<ConstArray> const &constArray ) { return new ComputeState( constArray ); } ConstArray::ComputeState::ComputeState( RC::ConstHandle<ConstArray> const &constArray ) : ArrayProducer::ComputeState( constArray ) , m_constArray( constArray ) { setCount( m_constArray->m_fixedArrayDesc->getNumMembers() ); } void ConstArray::ComputeState::produce( size_t index, void *data ) const { return m_constArray->getElementDesc()->setData( m_constArray->m_fixedArrayDesc->getImmutableMemberData( &m_constArray->m_data[0], index ), data ); } void ConstArray::ComputeState::produceJSON( size_t index, JSON::Encoder &jg ) const { return m_constArray->getElementDesc()->encodeJSON( m_constArray->m_fixedArrayDesc->getImmutableMemberData( &m_constArray->m_data[0], index ), jg ); } RC::ConstHandle<RT::ArrayDesc> ConstArray::getArrayDesc() const { return m_fixedArrayDesc; } void const *ConstArray::getImmutableData() const { return &m_data[0]; } void ConstArray::flush() { } } }
ghostx2013/FabricEngine_Backup
Native/Core/MR/ConstArray.cpp
C++
agpl-3.0
3,557
# -*- coding: utf-8 -*- # (c) 2016 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api from dateutil.relativedelta import relativedelta class saleOrderLine(models.Model): _inherit = 'sale.order.line' @api.multi @api.depends('order_id', 'order_id.date_order', 'delay') def _compute_date_planned(self): for line in self: new_date = fields.Date.context_today(self) if line.order_id and line.order_id.date_order: new_date = fields.Datetime.from_string( line.order_id.date_order).date() if line.delay: new_date = (new_date + (relativedelta(days=line.delay))) line.date_planned = new_date date_planned = fields.Date( 'Date planned', compute='_compute_date_planned', store=True, default=_compute_date_planned) def _find_sale_lines_from_stock_information( self, company, to_date, product, location, from_date=None): cond = [('company_id', '=', company.id), ('product_id', '=', product.id), ('date_planned', '<=', to_date), ('state', '=', 'draft')] if from_date: cond.append(('date_planned', '>=', from_date)) sale_lines = self.search(cond) sale_lines = sale_lines.filtered( lambda x: x.order_id.state not in ('cancel', 'except_picking', 'except_invoice', 'done', 'approved')) sale_lines = sale_lines.filtered( lambda x: x.order_id.warehouse_id.lot_stock_id.id == location.id) return sale_lines
alfredoavanzosc/odoo-addons
stock_information/models/sale_order_line.py
Python
agpl-3.0
1,803
<?php namespace wcf\data\bbcode; use wcf\data\DatabaseObjectEditor; use wcf\data\IEditableCachedObject; use wcf\system\cache\builder\BBCodeCacheBuilder; /** * Provides functions to edit bbcodes. * * @author Alexander Ebert * @copyright 2001-2015 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package com.woltlab.wcf * @subpackage data.bbcode * @category Community Framework */ class BBCodeEditor extends DatabaseObjectEditor implements IEditableCachedObject { /** * @see \wcf\data\DatabaseObjectDecorator::$baseClass */ public static $baseClass = 'wcf\data\bbcode\BBCode'; /** * @see \wcf\data\IEditableCachedObject::resetCache() */ public static function resetCache() { BBCodeCacheBuilder::getInstance()->reset(); } }
ramiusGitHub/WCF
wcfsetup/install/files/lib/data/bbcode/BBCodeEditor.class.php
PHP
lgpl-2.1
812
package lab.s2jh.ctx; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.Map; import lab.s2jh.core.exception.ServiceException; import lab.s2jh.core.service.PropertiesConfigService; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateException; @Service public class FreemarkerService extends Configuration { private final static Logger logger = LoggerFactory.getLogger(FreemarkerService.class); private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); public FreemarkerService() { this.setDefaultEncoding("UTF-8"); this.setTemplateLoader(stringTemplateLoader); } public String processTemplate(String templateName, long version, String templateContents, Map<String, Object> dataMap) { Assert.notNull(templateName); Assert.notNull(version); if (StringUtils.isBlank(templateContents)) { return null; } Object templateSource = stringTemplateLoader.findTemplateSource(templateName); if (templateSource == null) { logger.debug("Init freemarker template: {}", templateName); stringTemplateLoader.putTemplate(templateName, templateContents, version); } else { long ver = stringTemplateLoader.getLastModified(templateSource); if (version > ver) { logger.debug("Update freemarker template: {}", templateName); stringTemplateLoader.putTemplate(templateName, templateContents, version); } } return processTemplateByName(templateName, dataMap); } private String processTemplateByName(String templateName, Map<String, Object> dataMap) { StringWriter strWriter = new StringWriter(); try { this.getTemplate(templateName).process(dataMap, strWriter); strWriter.flush(); } catch (TemplateException e) { throw new ServiceException("error.freemarker.template.process", e); } catch (IOException e) { throw new ServiceException("error.freemarker.template.process", e); } return strWriter.toString(); } public String processTemplateByContents(String templateContents, Map<String, Object> dataMap) { String templateName = "_" + templateContents.hashCode(); return processTemplate(templateName, 0, templateContents, dataMap); } public String processTemplateByFileName(String templateFileName, Map<String, Object> dataMap) { String templateDir = PropertiesConfigService.getWebRootRealPath(); templateDir += File.separator + "WEB-INF" + File.separator + "template" + File.separator + "freemarker"; File targetTemplateFile = new File(templateDir + File.separator + templateFileName + ".ftl"); //TODO: 可添加额外从classpath加载文件处理 logger.debug("Processing freemarker template file: {}", targetTemplateFile.getAbsolutePath()); long fileVersion = targetTemplateFile.lastModified(); Object templateSource = stringTemplateLoader.findTemplateSource(templateFileName); long templateVersion = 0; if (templateSource != null) { templateVersion = stringTemplateLoader.getLastModified(templateSource); } if (fileVersion > templateVersion) { try { String contents = FileUtils.readFileToString(targetTemplateFile); return processTemplate(templateFileName, fileVersion, contents, dataMap); } catch (IOException e) { throw new ServiceException("error.freemarker.template.process", e); } } else { return processTemplateByName(templateFileName, dataMap); } } }
xautlx/s2jh
common-service/src/main/java/lab/s2jh/ctx/FreemarkerService.java
Java
lgpl-3.0
4,142
/* * Copyright 2014 Jacopo Aliprandi, Dario Archetti * * This file is part of SPF. * * SPF is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * SPF is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with SPF. If not, see <http://www.gnu.org/licenses/>. * */ package it.polimi.spf.framework.services; import java.util.Collection; import android.content.Context; import android.util.Log; import it.polimi.spf.shared.model.InvocationRequest; import it.polimi.spf.shared.model.InvocationResponse; import it.polimi.spf.shared.model.SPFActivity; import it.polimi.spf.shared.model.SPFServiceDescriptor; /** * Refactored version of {@link ServiceDispatcher} * * @author darioarchetti * */ public class SPFServiceRegistry { private static final String TAG = "ServiceRegistry"; private ActivityConsumerRouteTable mActivityTable; private ServiceRegistryTable mServiceTable; private AppCommunicationAgent mCommunicationAgent; public SPFServiceRegistry(Context context) { mServiceTable = new ServiceRegistryTable(context); mActivityTable = new ActivityConsumerRouteTable(context); mCommunicationAgent = new AppCommunicationAgent(context); } /** * Registers a service. The owner application must be already registered. * * @param descriptor * @return true if the service was registered */ public boolean registerService(SPFServiceDescriptor descriptor) { return mServiceTable.registerService(descriptor) && mActivityTable.registerService(descriptor); } /** * Unregisters a service. * * @param descriptor * - the descriptor of the service to unregister * @return true if the service was removed */ public boolean unregisterService(SPFServiceDescriptor descriptor) { return mServiceTable.unregisterService(descriptor) && mActivityTable.unregisterService(descriptor); } /** * Unregisters all the service of an application * * @param appIdentifier * - the identifier of the app whose service to remove * @return true if all the services where removed. */ public boolean unregisterAllServicesOfApp(String appIdentifier) { return mServiceTable.unregisterAllServicesOfApp(appIdentifier) && mActivityTable.unregisterAllServicesOfApp(appIdentifier); } /** * Retrieves all the services of an app. * * @param appIdentifier * - the id of the app whose service to retrieve * @return the list of its services */ public SPFServiceDescriptor[] getServicesOfApp(String appIdentifier) { return mServiceTable.getServicesOfApp(appIdentifier); } /** * Dispatches an invocation request to the right application. If the * application is not found, an error response is returned. * * @param request * @return */ public InvocationResponse dispatchInvocation(InvocationRequest request) { String appName = request.getAppName(); String serviceName = request.getServiceName(); String componentName = mServiceTable.getComponentForService(appName, serviceName); if (componentName == null) { return InvocationResponse.error("Application " + appName + " doesn't have a service named " + serviceName); } AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName); if (proxy == null) { return InvocationResponse.error("Cannot bind to service"); } try { return proxy.executeService(request); } catch (Throwable t) { Log.e("ServiceRegistry", "Error dispatching invocation: ", t); return InvocationResponse.error("Internal error: " + t.getMessage()); } } /** * Dispatches an activity to the right application according to {@link * ActivityConsumerRouteTable#} * * @param activity * @return */ public InvocationResponse sendActivity(SPFActivity activity) { ServiceIdentifier id = mActivityTable.getServiceFor(activity); String componentName = mServiceTable.getComponentForService(id); if (componentName == null) { String msg = "No service to handle " + activity; Log.d(TAG, msg); return InvocationResponse.error(msg); } AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName); if (proxy == null) { String msg = "Can't bind to service " + componentName; Log.d(TAG, msg); return InvocationResponse.error(msg); } try { InvocationResponse r = proxy.sendActivity(activity); Log.v(TAG, "Activity dispatched: " + r); return r; } catch (Throwable t) { Log.e(TAG, "Error dispatching invocation: ", t); return InvocationResponse.error("Internal error: " + t.getMessage()); } } @Deprecated public Collection<ActivityVerb> getVerbSupportList() { return mActivityTable.getVerbSupport(); } public Collection<ActivityVerb> getSupportedVerbs() { return mActivityTable.getVerbSupport(); } public void setDefaultConsumerForVerb(String verb, ServiceIdentifier identifier) { mActivityTable.setDefaultServiceForVerb(verb, identifier); } }
deib-polimi/SPF2
sPFFramework/src/main/java/it/polimi/spf/framework/services/SPFServiceRegistry.java
Java
lgpl-3.0
5,348
package se.sics.gvod.net; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** * @author <a href="mailto:bruno@factor45.org">Bruno de Carvalho</a> * @author Steffen Grohsschmiedt */ public class MessageCounter extends ChannelDuplexHandler { // internal vars ---------------------------------------------------------- private final String id; private final AtomicLong writtenMessages; private final AtomicLong readMessages; // constructors ----------------------------------------------------------- public MessageCounter(String id) { this.id = id; this.writtenMessages = new AtomicLong(); this.readMessages = new AtomicLong(); } // SimpleChannelHandler --------------------------------------------------- @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { this.readMessages.incrementAndGet(); super.channelRead(ctx, msg); } @Override public void write(ChannelHandlerContext ctx, Object msgs, ChannelPromise promise) throws Exception { promise.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { MessageCounter.this.readMessages.getAndIncrement(); } }); super.write(ctx, msgs, promise); } // @Override // public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { // System.out.println(this.id + ctx.channel() + " -> sent: " + this.getWrittenMessages() // + ", recv: " + this.getReadMessages()); // super.channelUnregistered(ctx); // } // getters & setters ------------------------------------------------------ public long getWrittenMessages() { return writtenMessages.get(); } public long getReadMessages() { return readMessages.get(); } }
jimdowling/nat-traverser
network/netty/src/main/java/se/sics/gvod/net/MessageCounter.java
Java
lgpl-3.0
2,282
/* * Copyright 2012 The Netty Project * * The Netty Project 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: * * https://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 io.netty.buffer; import java.nio.ByteOrder; import static org.junit.Assert.*; /** * Tests little-endian heap channel buffers */ public class PooledLittleEndianHeapByteBufTest extends AbstractPooledByteBufTest { @Override protected ByteBuf alloc(int length, int maxCapacity) { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(length, maxCapacity).order(ByteOrder.LITTLE_ENDIAN); assertSame(ByteOrder.LITTLE_ENDIAN, buffer.order()); return buffer; } }
zer0se7en/netty
buffer/src/test/java/io/netty/buffer/PooledLittleEndianHeapByteBufTest.java
Java
apache-2.0
1,146
/* * 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.jdbi.v3.core.qualifier; import java.util.Objects; public class QualifiedConstructorParamThing { private final int id; private final String name; public QualifiedConstructorParamThing(int id, @Reversed String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QualifiedConstructorParamThing that = (QualifiedConstructorParamThing) o; return id == that.id && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { return "QualifiedConstructorParamThing{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
john9x/jdbi
core/src/test/java/org/jdbi/v3/core/qualifier/QualifiedConstructorParamThing.java
Java
apache-2.0
1,607
package org.jbpm.services.task.impl.model.xml; import static org.jbpm.services.task.impl.model.xml.AbstractJaxbTaskObject.unsupported; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import org.kie.internal.task.api.model.AccessType; import org.kie.internal.task.api.model.FaultData; import com.fasterxml.jackson.annotation.JsonAutoDetect; @XmlRootElement(name="fault-data") @XmlAccessorType(XmlAccessType.FIELD) @JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE, setterVisibility=JsonAutoDetect.Visibility.NONE, fieldVisibility=JsonAutoDetect.Visibility.ANY) public class JaxbFaultData implements FaultData { @XmlElement private AccessType accessType; @XmlElement @XmlSchemaType(name="string") private String type; @XmlElement @XmlSchemaType(name="base64Binary") private byte[] content = null; private Object contentObject; @XmlElement(name="fault-name") @XmlSchemaType(name="string") private String faultName; public JaxbFaultData() { // JAXB constructor } public JaxbFaultData(FaultData faultData) { this.accessType = faultData.getAccessType(); this.content = faultData.getContent(); this.faultName = faultData.getFaultName(); this.type = faultData.getType(); } @Override public AccessType getAccessType() { return accessType; } @Override public void setAccessType( AccessType accessType ) { this.accessType = accessType; } @Override public String getType() { return type; } @Override public void setType( String type ) { this.type = type; } @Override public byte[] getContent() { return content; } @Override public void setContent( byte[] content ) { this.content = content; } @Override public String getFaultName() { return faultName; } @Override public void setFaultName( String faultName ) { this.faultName = faultName; } @Override public Object getContentObject() { return contentObject; } @Override public void setContentObject(Object object) { this.contentObject = object; } @Override public void writeExternal( ObjectOutput out ) throws IOException { unsupported(FaultData.class); } @Override public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { unsupported(FaultData.class); } }
jakubschwan/jbpm
jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbFaultData.java
Java
apache-2.0
2,814
/* * Copyright (C) 2013 salesforce.com, 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. */ /* * ======================================= * CONFIGURATION DOCS * ======================================= */ /** * Config object that contains all of the configuration options for * a scroller instance. * * This object is supplied by the implementer when instantiating a scroller. Some * properties have default values if they are not supplied by the implementer. * All the properties with the exception of `enabled` and `scroll` are saved * inside the instance and are accessible through the `this.opts` property. * * You can add your own options to be used by your own plugins. * * @class config * @static * **/ /** * Toggle the state of the scroller. If `enabled:false`, the scroller will not * respond to any gesture events. * * @property {Boolean} enabled * @default true * **/ /** * Define the duration in ms of the transition when the scroller snaps out of the boundaries. * * * @property {Boolean} bounceTime * @default 600 * **/ /** * Use CSS transitions to perform the scrolling. By default this is set to false and * a transition based on `requestAnimationFrame` is used instead. * * Given a position and duration to scroll, it applies a `matrix3d()` transform, * a `transition-timing-function` (by default a cubic-bezier curve), * and a `transition-duration` to make the element scroll. * * Most of the libraries use this CSS technique to create a synthetic scroller. * While this is the most simple and leanest (that is, closest to the browser) implementation * possible, when dealing with large ammounts of DOM or really large scroller sizes, * performance will start to degrade due to the massive amounts of GPU, CPU, and memory * needed to manipulate this large and complex region. * * Moreover, this technique does not allow you to have any control over * or give you any position information while scrolling, given that the only event * fired by the browser is a `transitionEnd`, which is triggered once the transition is over. * * **It's recommended to use this configuration when:** * * - The scrolling size is reasonably small * - The content of the scroller is not changing often (little DOM manipulation) * - You don't need position information updates while scrolling * * * @property {Boolean} useCSSTransition * @default false * **/ /** * * Enable dual listeners (mouse and pointer events at the same time). This is useful for devices * where they can handle both types of interactions interchangeably. * This is set to false by default, allowing only one type of input interaction. * * @property {Boolean} dualListeners * @default false * **/ /** * * The minimum numbers of pixels necessary to start moving the scroller. * This is useful when you want to make sure that the user gesture * has well-defined direction (either horizontal or vertical). * * @property {integer} minThreshold * @default 5 * **/ /** * * The minimum number of pixels neccesary to calculate * the direction of the gesture. * * Ideally this value should be less than `minThreshold` to be able to * control the action of the scroller based on the direction of the gesture. * For example, you may want to lock the scroller movement if the gesture is horizontal. * * @property {integer} minDirectionThreshold * @default 2 * **/ /** * * Locks the scroller if the direction of the gesture matches one provided. * This property is meant to be used in conjunction with `minThreshold and``minDirectionThreshold`. * * Valid values: * - horizontal * - vertical * * @property {boolean} lockOnDirection * **/ /** * * Sets the scroller with the height of the items that the scroller contains. * * This property is used only when * `scroll:vertical` and `gpuOptimization: true`. * It helps the scroller calculate the positions of the surfaces * attached to the DOM, which slightly improves the performance of the scroller * (that is, the painting of that surface can occur asyncronously and outside of the JS execution). * * @plugin SurfaceManager * @property {integer} itemHeight * **/ /** * * Sets the scroller with the width of the items that the scroller contains. * * This property is used only when * `scroll:vertical` and `gpuOptimization: true`. * It helps the scroller calculate the positions of the surfaces * attached to the DOM, which slightly improves the performance of the scroller * (that is, the painting of that surface can occur asyncronously and outside of the JS execution). * * @plugin SurfaceManager * @property {integer} itemWidth * **/ /** * * Bind the event handlers to the scroller wrapper. * This is useful when using nested scrollers or when adding some custom logic * in a parent node as the event bubbles up. * * If set to true once the scroller is out of the wrapper container, it will stop scrolling. * * @property {integer} bindToWrapper * @default false * **/ /** * * Set the direction of the scroll. * By default, vertical scrolling is enabled. * * Valid values: * - horizontal * - vertical * * @property {string} scroll * @default vertical * **/ /** * * Activates pullToRefresh functionality. * Note that you need to include the `PullToRefresh` plugin as part of your scroller bundle, * otherwise this option is ignored. * * @plugin PullToRefresh * @property {boolean} pullToRefresh * @default false **/ /** * * Activates pullToLoadMore functionality. * Note that you need to include the `PullToLoadMore` plugin as part of your scroller bundle, * otherwise this option is ignored. * * @plugin PullToLoadMore * @property {boolean} pullToLoadMore * @default false * **/ /** * * Creates scrollbars on the direction of the scroll. * @plugin Indicators * @property {boolean} scrollbars * @default false * **/ /** * * Scrollbar configuration. * * @plugin Indicators * @property {Object} scrollbarsConfig * @default false * **/ /** * * Activates infiniteLoading. * * @plugin InfiniteLoading * @property {boolean} infiniteLoading * @default false * **/ /** * * Sets the configuration for infiniteLoading. * The `infiniteLoading` option must be set to true. * * @property {Object} infiniteLoadingConfig * **/ /** * * TODO: Debounce * * @property {boolean} debounce * **/ /** * * TODO: GPUOptimization * @plugin SurfaceManager * @property {boolean} gpuOptimization * **/
forcedotcom/scrollerjs
src/config.js
JavaScript
apache-2.0
6,867
package org.zstack.sdk.iam2.entity; public enum StateEvent { enable, disable, }
AlanJager/zstack
sdk/src/main/java/org/zstack/sdk/iam2/entity/StateEvent.java
Java
apache-2.0
83
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.marshalling.river; import org.jboss.marshalling.MarshallerFactory; import org.jboss.marshalling.Marshaller; import org.jboss.marshalling.Marshalling; import org.jboss.marshalling.Unmarshaller; import org.jboss.marshalling.MarshallingConfiguration; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; /** * */ public abstract class ReadWriteTest { public void run() throws Throwable { final MarshallerFactory factory = new RiverMarshallerFactory(); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configure(configuration); final Marshaller marshaller = factory.createMarshaller(configuration); final ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); marshaller.start(Marshalling.createByteOutput(baos)); runWrite(marshaller); marshaller.finish(); final byte[] bytes = baos.toByteArray(); final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration); unmarshaller.start(Marshalling.createByteInput(new ByteArrayInputStream(bytes))); runRead(unmarshaller); unmarshaller.finish(); } public void configure(MarshallingConfiguration configuration) throws Throwable {} public void runWrite(Marshaller marshaller) throws Throwable {}; public void runRead(Unmarshaller unmarshaller) throws Throwable {}; }
kohsuke/jboss-marshalling
river/src/test/java/org/jboss/marshalling/river/ReadWriteTest.java
Java
apache-2.0
2,135
package manager import ( ds "github.com/Comcast/traffic_control/traffic_monitor/experimental/traffic_monitor/deliveryservice" "sync" ) type LastStatsThreadsafe struct { stats *ds.LastStats m *sync.RWMutex } func NewLastStatsThreadsafe() LastStatsThreadsafe { s := ds.NewLastStats() return LastStatsThreadsafe{m: &sync.RWMutex{}, stats: &s} } // Get returns the last KBPS stats object. Callers MUST NOT modify the object. It is not threadsafe for writing. If the object must be modified, callers must call LastStats.Copy() and modify the copy. func (o *LastStatsThreadsafe) Get() ds.LastStats { o.m.RLock() defer o.m.RUnlock() return *o.stats } func (o *LastStatsThreadsafe) Set(s ds.LastStats) { o.m.Lock() *o.stats = s o.m.Unlock() }
dneuman64/traffic_control
traffic_monitor/experimental/traffic_monitor/manager/lastkbpsstats.go
GO
apache-2.0
756
package config import ( "encoding/json" "registry/api" "registry/storage" "os" ) type Config struct { API *api.Config `json:"api"` Storage *storage.Config `json:"storage"` } func New(filename string) (*Config, error) { // read in config var cfg Config if cfgFile, err := os.Open(filename); err != nil { return nil, err } else { dec := json.NewDecoder(cfgFile) if err := dec.Decode(&cfg); err != nil { return nil, err } } return &cfg, nil }
seryl/go-docker-registry
src/registry/config/config.go
GO
apache-2.0
474
/* * Copyright 2010 JBoss 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 org.drools.ide.common.client.factconstraints.dataprovider; import java.util.Map; public interface FieldDataProvider { public void setFactTYpe(String factType); public void setFieldName(String fieldName); public String[] getArgumentKeys(); public Object getArgumentValue(String key); public void setArgumentValue(String key, Object value); public Map<Object,String> getData(); public Object getDefault(); }
Rikkola/guvnor
droolsjbpm-ide-common/src/main/java/org/drools/ide/common/client/factconstraints/dataprovider/FieldDataProvider.java
Java
apache-2.0
1,045
from flask import Blueprint, render_template, request, url_for from CTFd.models import Users from CTFd.utils import config from CTFd.utils.decorators import authed_only from CTFd.utils.decorators.visibility import ( check_account_visibility, check_score_visibility, ) from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.user import get_current_user users = Blueprint("users", __name__) @users.route("/users") @check_account_visibility def listing(): q = request.args.get("q") field = request.args.get("field", "name") if field not in ("name", "affiliation", "website"): field = "name" filters = [] if q: filters.append(getattr(Users, field).like("%{}%".format(q))) users = ( Users.query.filter_by(banned=False, hidden=False) .filter(*filters) .order_by(Users.id.asc()) .paginate(per_page=50) ) args = dict(request.args) args.pop("page", 1) return render_template( "users/users.html", users=users, prev_page=url_for(request.endpoint, page=users.prev_num, **args), next_page=url_for(request.endpoint, page=users.next_num, **args), q=q, field=field, ) @users.route("/profile") @users.route("/user") @authed_only def private(): infos = get_infos() errors = get_errors() user = get_current_user() if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") return render_template( "users/private.html", user=user, account=user.account, infos=infos, errors=errors, ) @users.route("/users/<int:user_id>") @check_account_visibility @check_score_visibility def public(user_id): infos = get_infos() errors = get_errors() user = Users.query.filter_by(id=user_id, banned=False, hidden=False).first_or_404() if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") return render_template( "users/public.html", user=user, account=user.account, infos=infos, errors=errors )
LosFuzzys/CTFd
CTFd/users.py
Python
apache-2.0
2,090
//// [tests/cases/conformance/dynamicImport/importCallExpressionDeclarationEmit2.ts] //// //// [0.ts] export function foo() { return "foo"; } //// [1.ts] var p1 = import("./0"); //// [0.js] export function foo() { return "foo"; } //// [1.js] var p1 = import("./0"); //// [0.d.ts] export declare function foo(): string;
synaptek/TypeScript
tests/baselines/reference/importCallExpressionDeclarationEmit2.js
JavaScript
apache-2.0
339
<?php // locale: great britain english (en-gb) // author: Chris Gedrim https://github.com/chrisgedrim return array( "months" => explode('_', 'January_February_March_April_May_June_July_August_September_October_November_December'), "monthsNominative" => explode('_', 'January_February_March_April_May_June_July_August_September_October_November_December'), "monthsShort" => explode('_', 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'), "weekdays" => explode('_', 'Monday_Tuesday_Wednesday_Thursday_Friday_Saturday_Sunday'), "weekdaysShort" => explode('_', 'Mon_Tue_Wed_Thu_Fri_Sat_Sun'), "calendar" => array( "sameDay" => '[Today]', "nextDay" => '[Tomorrow]', "lastDay" => '[Yesterday]', "lastWeek" => '[Last] l', "sameElse" => 'l', "withTime" => '[at] H:i', "default" => 'd/m/Y', ), "relativeTime" => array( "future" => 'in %s', "past" => '%s ago', "s" => 'a few seconds', "ss" => '%d seconds', "m" => 'a minute', "mm" => '%d minutes', "h" => 'an hour', "hh" => '%d hours', "d" => 'a day', "dd" => '%d days', "M" => 'a month', "MM" => '%d months', "y" => 'a year', "yy" => '%d years', ), "ordinal" => function ($number) { $n = $number % 100; $ends = array('th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'); if ($n >= 11 && $n <= 13) { return $number . '[th]'; } return $number . '[' . $ends[$number % 10] . ']'; }, "week" => array( "dow" => 1, // Monday is the first day of the week. "doy" => 4 // The week that contains Jan 4th is the first week of the year. ), "customFormats" => array( "LT" => "G:i", // 22:00 "LTS" => "G:i:s", // 22:00:00 "L" => "d/m/Y", // 12/06/2010 "l" => "j/n/Y", // 12/6/2010 "LL" => "j F Y", // 12 June 2010 "ll" => "j M Y", // 12 Jun 2010 "LLL" => "j F Y G:i", // 12 June 2010 22:00 "lll" => "j M Y G:i", // 12 Jun 2010 22:00 "LLLL" => "l, j F F Y G:i", // Saturday, 12 June June 2010 22:00 "llll" => "D, j M Y G:i", // Sat, 12 Jun 2010 22:00 ), );
novaramedia/novaramedia-com
vendor/fightbulc/moment/src/Locales/en_GB.php
PHP
apache-2.0
2,478
/******************************************************************************* * Copyright 2015-2019 Toaker NewBeyondViewPager * * 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 net.soulwolf.newbeyondviewpager; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.ViewGroup; import com.toaker.common.tlog.TLog; /** * Decorator for NewBeyondViewPager * * @author Toaker [Toaker](ToakerQin@gmail.com) * [Toaker](http://www.toaker.com) * @Time Create by 2015/5/14 9:38 */ public class NewBeyondViewPager extends ViewGroup { private static final boolean DEBUG = true; private static final String LOG_TAG = "NewBeyondViewPager:"; public NewBeyondViewPager(Context context) { super(context); } public NewBeyondViewPager(Context context, AttributeSet attrs) { super(context, attrs); } public NewBeyondViewPager(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public NewBeyondViewPager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if(DEBUG){ TLog.d(LOG_TAG,"onLayout: %s %s %s %s",l,t,r,b); } } }
RyanTech/NewBeyondViewPager
library/src/main/java/net/soulwolf/newbeyondviewpager/NewBeyondViewPager.java
Java
apache-2.0
2,071
<?php error_reporting(E_ALL ^ E_NOTICE); include_once("Include_GetString.php") ; $Theme="Office2007"; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head ID="Head1"> <title><?php echo GetString("MoreColors") ; ?></title> <meta http-equiv="Page-Enter" content="blendTrans(Duration=0.1)" /> <meta http-equiv="Page-Exit" content="blendTrans(Duration=0.1)" /> <script type="text/javascript" src="../Scripts/Dialog/DialogHead.js"></script> <script type="text/javascript" src="../Scripts/Dialog/Dialog_ColorPicker.js"></script> <link href="../Themes/<?php echo $Theme; ?>/dialog.css" type="text/css" rel="stylesheet" /> <style type="text/css"> .colorcell { width:22px; height:11px; cursor:hand; } .colordiv { border:solid 1px #808080; width:22px; height:11px; font-size:1px; } </style> <script> function DoubleHex(v) { if(v<16)return "0"+v.toString(16); return v.toString(16); } function ToHexString(r,g,b) { return ("#"+DoubleHex(r*51)+DoubleHex(g*51)+DoubleHex(b*51)).toUpperCase(); } function MakeHex(z,x,y) { //hor->ver var l=z%2 var t=(z-l)/2 z=l*3+t //left column , l/r mirrow if(z<3)x=5-x; //middle row , t/b mirrow if(z==1||z==4)y=5-y; return ToHexString(5-y,5-x,5-z); } var colors=new Array(216); for(var z=0;z<6;z++) { for(var x=0;x<6;x++) { for(var y=0;y<6;y++) { var hex=MakeHex(z,x,y) var xx=(z%2)*6+x; var yy=Math.floor(z/2)*6+y; colors[yy*12+xx]=hex; } } } var arr=[]; for(var i=0;i<colors.length;i++) { if(i%12==0)arr.push("<tr>"); arr.push("<td class='colorcell'><div class='colordiv' style='background-color:") arr.push(colors[i]); arr.push("' cvalue='"); arr.push(colors[i]); arr.push("' title='") arr.push(colors[i]); arr.push("'>&nbsp;</div></td>"); if(i%12==11)arr.push("</tr>"); } </script> </head> <body> <div id="ajaxdiv"> <div class="tab-pane-control tab-pane" id="tabPane1"> <div class="tab-row"> <h2 class="tab selected"> <a tabindex="-1" href='colorpicker.php?Theme=<?php echo $Theme; ?>&<?php echo $_SERVER["QUERY_STRING"]; ?>'> <span style="white-space:nowrap;"> <?php echo GetString("WebPalette") ; ?> </span> </a> </h2> <h2 class="tab"> <a tabindex="-1" href='colorpicker_basic.php?Theme=<?php echo $Theme; ?>&<?php echo $_SERVER["QUERY_STRING"]; ?>'> <span style="white-space:nowrap;"> <?php echo GetString("NamedColors") ; ?> </span> </a> </h2> <h2 class="tab"> <a tabindex="-1" href='colorpicker_more.php?Theme=<?php echo $Theme; ?>&<?php echo $_SERVER["QUERY_STRING"]; ?>'> <span style="white-space:nowrap;"> <?php echo GetString("CustomColor") ; ?> </span> </a> </h2> </div> <div class="tab-page"> <table cellSpacing='2' cellPadding="1" align="center"> <script> document.write(arr.join("")); </script> <tr> <td colspan="12" height="12"><p align="left"></p> </td> </tr> <tr> <td colspan="12" valign="middle" height="24"> <span style="height:24px;width:50px;vertical-align:middle;"><?php echo GetString("Color") ; ?>: </span>&nbsp; <input type="text" id="divpreview" size="7" maxlength="7" style="width:180px;height:24px;border:#a0a0a0 1px solid; Padding:4;"/> </td> </tr> </table> </div> </div> <div id="container-bottom"> <input type="button" id="buttonok" value="<?php echo GetString("OK") ; ?>" class="formbutton" style="width:70px" onclick="do_insert();" /> &nbsp;&nbsp;&nbsp;&nbsp; <input type="button" id="buttoncancel" value="<?php echo GetString("Cancel") ; ?>" class="formbutton" style="width:70px" onclick="do_Close();" /> </div> </div> </body> </html>
srinivasans/educloud
others/editor/Dialogs/colorpicker.php
PHP
apache-2.0
3,928
import {BrowserDomAdapter} from 'angular2/src/dom/browser_adapter'; import {PromiseWrapper} from 'angular2/src/facade/async'; import {List, ListWrapper, Map, MapWrapper} from 'angular2/src/facade/collection'; import {DateWrapper, Type, print} from 'angular2/src/facade/lang'; import { Parser, Lexer, DynamicChangeDetection } from 'angular2/src/change_detection/change_detection'; import {Compiler, CompilerCache} from 'angular2/src/core/compiler/compiler'; import {DirectiveResolver} from 'angular2/src/core/compiler/directive_resolver'; import {PipeResolver} from 'angular2/src/core/compiler/pipe_resolver'; import * as viewModule from 'angular2/src/core/annotations_impl/view'; import {Component, Directive, View} from 'angular2/angular2'; import {ViewResolver} from 'angular2/src/core/compiler/view_resolver'; import {UrlResolver} from 'angular2/src/services/url_resolver'; import {AppRootUrl} from 'angular2/src/services/app_root_url'; import {ComponentUrlMapper} from 'angular2/src/core/compiler/component_url_mapper'; import {reflector} from 'angular2/src/reflection/reflection'; import {ReflectionCapabilities} from 'angular2/src/reflection/reflection_capabilities'; import {getIntParameter, bindAction} from 'angular2/src/test_lib/benchmark_util'; import {ProtoViewFactory} from 'angular2/src/core/compiler/proto_view_factory'; import { ViewLoader, DefaultDomCompiler, SharedStylesHost, TemplateCloner } from 'angular2/src/render/render'; import {DomElementSchemaRegistry} from 'angular2/src/render/dom/schema/dom_element_schema_registry'; export function main() { BrowserDomAdapter.makeCurrent(); var count = getIntParameter('elements'); reflector.reflectionCapabilities = new ReflectionCapabilities(); var reader = new DirectiveResolver(); var pipeResolver = new PipeResolver(); var cache = new CompilerCache(); var viewResolver = new MultipleViewResolver( count, [BenchmarkComponentNoBindings, BenchmarkComponentWithBindings]); var urlResolver = new UrlResolver(); var appRootUrl = new AppRootUrl(""); var renderCompiler = new DefaultDomCompiler( new DomElementSchemaRegistry(), new TemplateCloner(-1), new Parser(new Lexer()), new ViewLoader(null, null, null), new SharedStylesHost(), 'a'); var compiler = new Compiler(reader, pipeResolver, [], cache, viewResolver, new ComponentUrlMapper(), urlResolver, renderCompiler, new ProtoViewFactory(new DynamicChangeDetection()), appRootUrl); function measureWrapper(func, desc) { return function() { var begin = DateWrapper.now(); print(`[${desc}] Begin...`); var onSuccess = function(_) { var elapsedMs = DateWrapper.toMillis(DateWrapper.now()) - DateWrapper.toMillis(begin); print(`[${desc}] ...done, took ${elapsedMs} ms`); }; PromiseWrapper.then(func(), onSuccess, null); }; } function compileNoBindings() { cache.clear(); return compiler.compileInHost(BenchmarkComponentNoBindings); } function compileWithBindings() { cache.clear(); return compiler.compileInHost(BenchmarkComponentWithBindings); } bindAction('#compileNoBindings', measureWrapper(compileNoBindings, 'No Bindings')); bindAction('#compileWithBindings', measureWrapper(compileWithBindings, 'With Bindings')); } @Directive({selector: '[dir0]', properties: ['prop: attr0']}) class Dir0 { } @Directive({selector: '[dir1]', properties: ['prop: attr1']}) class Dir1 { constructor(dir0: Dir0) {} } @Directive({selector: '[dir2]', properties: ['prop: attr2']}) class Dir2 { constructor(dir1: Dir1) {} } @Directive({selector: '[dir3]', properties: ['prop: attr3']}) class Dir3 { constructor(dir2: Dir2) {} } @Directive({selector: '[dir4]', properties: ['prop: attr4']}) class Dir4 { constructor(dir3: Dir3) {} } class MultipleViewResolver extends ViewResolver { _multiple: number; _cache: Map<any, any>; constructor(multiple: number, components: List<Type>) { super(); this._multiple = multiple; this._cache = new Map(); ListWrapper.forEach(components, (c) => this._warmUp(c)); } _warmUp(component: Type) { var view = super.resolve(component); var multiplier = ListWrapper.createFixedSize(this._multiple); for (var i = 0; i < this._multiple; ++i) { multiplier[i] = view.template; } this._cache.set(component, ListWrapper.join(multiplier, '')); } resolve(component: Type): viewModule.View { var view = super.resolve(component); var myView = new viewModule.View( {template:<string>this._cache.get(component), directives: view.directives}); return myView; } } @Component({selector: 'cmp-nobind'}) @View({ directives: [Dir0, Dir1, Dir2, Dir3, Dir4], template: ` <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> <div class="class0 class1 class2 class3 class4 " nodir0="" attr0="value0" nodir1="" attr1="value1" nodir2="" attr2="value2" nodir3="" attr3="value3" nodir4="" attr4="value4"> </div> </div> </div> </div> </div>` }) class BenchmarkComponentNoBindings { } @Component({selector: 'cmp-withbind'}) @View({ directives: [Dir0, Dir1, Dir2, Dir3, Dir4], template: ` <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} <div class="class0 class1 class2 class3 class4 " dir0="" [attr0]="value0" dir1="" [attr1]="value1" dir2="" [attr2]="value2" dir3="" [attr3]="value3" dir4="" [attr4]="value4"> {{inter0}}{{inter1}}{{inter2}}{{inter3}}{{inter4}} </div> </div> </div> </div> </div>` }) class BenchmarkComponentWithBindings { }
tkarling/angular
modules/benchmarks/src/compiler/compiler_benchmark.ts
TypeScript
apache-2.0
7,166
package org.apache.maven.project.inheritance.t08; /* * 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. */ import java.io.File; import java.util.Iterator; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; import org.apache.maven.project.inheritance.AbstractProjectInheritanceTestCase; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * A test which demonstrates maven's dependency management * * @author <a href="rgoers@apache.org">Ralph Goers</a> */ public class ProjectInheritanceTest extends AbstractProjectInheritanceTestCase { // ---------------------------------------------------------------------- // // p1 inherits from p0 // p0 inherits from super model // // or we can show it graphically as: // // p1 ---> p0 --> super model // // ---------------------------------------------------------------------- @Test public void testDependencyManagement() throws Exception { File localRepo = getLocalRepositoryPath(); File pom0 = new File( localRepo, "p0/pom.xml" ); File pom0Basedir = pom0.getParentFile(); File pom1 = new File( pom0Basedir, "p1/pom.xml" ); // load everything... MavenProject project0 = getProjectWithDependencies( pom0 ); MavenProject project1 = getProjectWithDependencies( pom1 ); assertEquals( pom0Basedir, project1.getParent().getBasedir() ); System.out.println( "Project " + project1.getId() + " " + project1 ); Set set = project1.getArtifacts(); assertNotNull( set, "No artifacts" ); assertTrue( set.size() > 0, "No Artifacts" ); Iterator iter = set.iterator(); assertTrue( set.size() == 4, "Set size should be 4, is " + set.size() ); while ( iter.hasNext() ) { Artifact artifact = (Artifact) iter.next(); System.out.println( "Artifact: " + artifact.getDependencyConflictId() + " " + artifact.getVersion() + " Optional=" + ( artifact.isOptional() ? "true" : "false" ) ); assertTrue( artifact.getVersion().equals( "1.0" ), "Incorrect version for " + artifact.getDependencyConflictId() ); } } }
cstamas/maven
maven-compat/src/test/java/org/apache/maven/project/inheritance/t08/ProjectInheritanceTest.java
Java
apache-2.0
3,173
module MiqPolicyController::PolicyProfiles extend ActiveSupport::Concern def profile_edit case params[:button] when "cancel" @edit = nil @profile = MiqPolicySet.find_by_id(session[:edit][:profile_id]) if session[:edit] && session[:edit][:profile_id] if !@profile || (@profile && @profile.id.blank?) add_flash(_("Add of new %{models} was cancelled by the user") % {:models => ui_lookup(:model => "MiqPolicySet")}) else add_flash(_("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "MiqPolicySet"), :name => @profile.description}) end get_node_info(x_node) replace_right_cell(@nodetype) return when "reset", nil # Reset or first time in profile_build_edit_screen @sb[:action] = "profile_edit" if params[:button] == "reset" add_flash(_("All changes have been reset"), :warning) end replace_right_cell("pp") return end # Load @edit/vars for other buttons id = params[:id] ? params[:id] : "new" return unless load_edit("profile_edit__#{id}", "replace_cell__explorer") @profile = @edit[:profile_id] ? MiqPolicySet.find_by_id(@edit[:profile_id]) : MiqPolicySet.new case params[:button] when "save", "add" assert_privileges("profile_#{@profile.id ? "edit" : "new"}") add_flash(_("%{model} must contain at least one %{field}") % {:model => ui_lookup(:model => "MiqPolicySet"), :field => ui_lookup(:model => "MiqPolicy")}, :error) if @edit[:new][:policies].length == 0 # At least one member is required profile = @profile.id.blank? ? MiqPolicySet.new : MiqPolicySet.find(@profile.id) # Get new or existing record profile.description = @edit[:new][:description] profile.notes = @edit[:new][:notes] if profile.valid? && !@flash_array && profile.save policies = profile.members # Get the sets members current = [] policies.each { |p| current.push(p.id) } # Build an array of the current policy ids mems = @edit[:new][:policies].invert # Get the ids from the member list box begin policies.each { |c| profile.remove_member(MiqPolicy.find(c)) unless mems.include?(c.id) } # Remove any policies no longer in the members list box mems.each_key { |m| profile.add_member(MiqPolicy.find(m)) unless current.include?(m) } # Add any policies not in the set rescue StandardError => bang add_flash(_("Error during 'Policy Profile %{params}': %{messages}") % {:params => params[:button], :messages => bang.message}, :error) end AuditEvent.success(build_saved_audit(profile, params[:button] == "add")) flash_key = params[:button] == "save" ? _("%{model} \"%{name}\" was saved") : _("%{model} \"%{name}\" was added") add_flash(flash_key % {:model => ui_lookup(:model => "MiqPolicySet"), :name => @edit[:new][:description]}) profile_get_info(MiqPolicySet.find(profile.id)) @edit = nil @nodetype = "pp" @new_profile_node = "pp-#{to_cid(profile.id)}" replace_right_cell("pp", [:policy_profile]) else profile.errors.each do |field, msg| add_flash("#{field.to_s.capitalize} #{msg}", :error) end replace_right_cell("pp") end when "move_right", "move_left", "move_allleft" handle_selection_buttons(:policies) session[:changed] = (@edit[:new] != @edit[:current]) replace_right_cell("pp") end end def profile_delete assert_privileges("profile_delete") profiles = [] # showing 1 policy set, delete it if params[:id].nil? || MiqPolicySet.find_by_id(params[:id]).nil? add_flash(_("%{models} no longer exists") % {:models => ui_lookup(:model => "MiqPolicySet")}, :error) else profiles.push(params[:id]) end process_profiles(profiles, "destroy") unless profiles.empty? add_flash(_("The selected %{models} was deleted") % {:models => ui_lookup(:models => "MiqPolicySet")}) if @flash_array.nil? self.x_node = @new_profile_node = 'root' get_node_info('root') replace_right_cell('root', [:policy_profile]) end def profile_field_changed return unless load_edit("profile_edit__#{params[:id]}", "replace_cell__explorer") @profile = @edit[:profile_id] ? MiqPolicySet.find_by_id(@edit[:profile_id]) : MiqPolicySet.new @edit[:new][:description] = params[:description].blank? ? nil : params[:description] if params[:description] @edit[:new][:notes] = params[:notes].blank? ? nil : params[:notes] if params[:notes] send_button_changes end private def process_profiles(profiles, task) process_elements(profiles, MiqPolicySet, task) end def profile_build_edit_screen @edit = {} @edit[:new] = {} @edit[:current] = {} @profile = params[:id] ? MiqPolicySet.find(params[:id]) : MiqPolicySet.new # Get existing or new record @edit[:key] = "profile_edit__#{@profile.id || "new"}" @edit[:rec_id] = @profile.id || nil @edit[:profile_id] = @profile.id @edit[:new][:description] = @profile.description @edit[:new][:notes] = @profile.notes @edit[:new][:policies] = {} policies = @profile.members # Get the member sets policies.each { |p| @edit[:new][:policies][ui_lookup(:model => p.towhat) + " #{p.mode.capitalize}: " + p.description] = p.id } # Build a hash for the members list box @edit[:choices] = {} MiqPolicy.all.each do |p| @edit[:choices][ui_lookup(:model => p.towhat) + " #{p.mode.capitalize}: " + p.description] = p.id # Build a hash for the policies to choose from end @edit[:new][:policies].each_key do |key| @edit[:choices].delete(key) # Remove any policies that are in the members list box end @edit[:current] = copy_hash(@edit[:new]) @embedded = true @in_a_form = true @edit[:current][:add] = true if @edit[:profile_id].blank? # Force changed to be true if adding a record session[:changed] = (@edit[:new] != @edit[:current]) end def profile_get_all @profiles = MiqPolicySet.all.sort_by { |ps| ps.description.downcase } set_search_text @profiles = apply_search_filter(@search_text, @profiles) unless @search_text.blank? @right_cell_text = _("All %{models}") % {:models => ui_lookup(:models => "MiqPolicySet")} @right_cell_div = "profile_list" end # Get information for a profile def profile_get_info(profile) @record = @profile = profile @profile_policies = @profile.miq_policies.sort_by { |p| [p.towhat, p.mode, p.description.downcase] } @right_cell_text = _("%{model} \"%{name}\"") % {:model => ui_lookup(:model => "MiqPolicySet"), :name => @profile.description} @right_cell_div = "profile_details" end end
maas-ufcg/manageiq
app/controllers/miq_policy_controller/policy_profiles.rb
Ruby
apache-2.0
7,000
/* * 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. */ var TypeService = function($http, ENV, locationUtils, messageModel) { this.getTypes = function(queryParams) { return $http.get(ENV.api['root'] + 'types', {params: queryParams}).then( function (result) { return result.data.response; }, function (err) { throw err; } ) }; this.getType = function(id) { return $http.get(ENV.api['root'] + 'types', {params: {id: id}}).then( function (result) { return result.data.response[0]; }, function (err) { throw err; } ) }; this.createType = function(type) { return $http.post(ENV.api['root'] + 'types', type).then( function(result) { messageModel.setMessages([ { level: 'success', text: 'Type created' } ], true); locationUtils.navigateToPath('/types'); return result; }, function(err) { messageModel.setMessages(err.data.alerts, false); throw err; } ); }; // todo: change to use query param when it is supported this.updateType = function(type) { return $http.put(ENV.api['root'] + 'types/' + type.id, type).then( function(result) { messageModel.setMessages([ { level: 'success', text: 'Type updated' } ], false); return result; }, function(err) { messageModel.setMessages(err.data.alerts, false); throw err; } ); }; // todo: change to use query param when it is supported this.deleteType = function(id) { return $http.delete(ENV.api['root'] + "types/" + id).then( function(result) { messageModel.setMessages([ { level: 'success', text: 'Type deleted' } ], true); return result; }, function(err) { messageModel.setMessages(err.data.alerts, true); throw err; } ); }; }; TypeService.$inject = ['$http', 'ENV', 'locationUtils', 'messageModel']; module.exports = TypeService;
hbeatty/incubator-trafficcontrol
traffic_portal/app/src/common/api/TypeService.js
JavaScript
apache-2.0
3,066
/* * 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.qpid.jms.producer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import javax.jms.Destination; import javax.jms.InvalidDestinationException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueSender; import javax.jms.Session; import org.apache.qpid.jms.JmsConnectionTestSupport; import org.apache.qpid.jms.JmsQueueSession; import org.apache.qpid.jms.message.JmsOutboundMessageDispatch; import org.apache.qpid.jms.provider.mock.MockRemotePeer; import org.junit.After; import org.junit.Before; import org.junit.Test; public class JmsQueueSenderTest extends JmsConnectionTestSupport { private JmsQueueSession session; private final MockRemotePeer remotePeer = new MockRemotePeer(); @Override @Before public void setUp() throws Exception { super.setUp(); remotePeer.start(); connection = createConnectionToMockProvider(); session = (JmsQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } @Override @After public void tearDown() throws Exception { try { remotePeer.terminate(); } finally { super.tearDown(); } } @Test(timeout = 10000) public void testMultipleCloseCallsNoErrors() throws Exception { Queue queue = session.createQueue(getTestName()); QueueSender sender = session.createSender(queue); sender.close(); sender.close(); } @Test(timeout = 10000) public void testGetQueue() throws Exception { Queue queue = session.createQueue(getTestName()); QueueSender sender = session.createSender(queue); assertSame(queue, sender.getQueue()); } @Test(timeout = 10000) public void testSendToQueueWithNullOnExplicitQueueSender() throws Exception { Queue queue = session.createQueue(getTestName()); QueueSender sender = session.createSender(null); Message message = session.createMessage(); sender.send(queue, message); JmsOutboundMessageDispatch envelope = remotePeer.getLastReceivedMessage(); assertNotNull(envelope); message = envelope.getMessage(); Destination destination = message.getJMSDestination(); assertEquals(queue, destination); } @Test(timeout = 10000) public void testSendToQueueWithDeliveryOptsWithNullOnExplicitQueueSender() throws Exception { Queue queue = session.createQueue(getTestName()); QueueSender sender = session.createSender(null); Message message = session.createMessage(); sender.send(queue, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); JmsOutboundMessageDispatch envelope = remotePeer.getLastReceivedMessage(); assertNotNull(envelope); message = envelope.getMessage(); Destination destination = message.getJMSDestination(); assertEquals(queue, destination); } @Test(timeout = 10000) public void testSendToQueueWithNullOnExplicitQueueSenderThrowsInvalidDestinationException() throws Exception { Queue queue = session.createQueue(getTestName()); QueueSender sender = session.createSender(queue); Message message = session.createMessage(); try { sender.send((Queue) null, message); fail("Expected exception to be thrown"); } catch (InvalidDestinationException ide) { // expected } } @Test(timeout = 10000) public void testSendToQueueWithDeliveryOptsWithNullOnExplicitQueueSenderThrowsInvalidDestinationException() throws Exception { Queue queue = session.createQueue(getTestName()); QueueSender sender = session.createSender(queue); Message message = session.createMessage(); try { sender.send((Queue) null, message, Message.DEFAULT_DELIVERY_MODE, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE); fail("Expected exception to be thrown"); } catch (InvalidDestinationException ide) { // expected } } }
apache/qpid-jms
qpid-jms-client/src/test/java/org/apache/qpid/jms/producer/JmsQueueSenderTest.java
Java
apache-2.0
5,048
package util import ( "fmt" ) /* BytesRefHash is a special purpose hash map like data structure optimized for BytesRef instances. BytesRefHash maintains mappings of byte arrays to ids (map[[]byte]int) sorting the hashed bytes efficiently in continuous storage. The mapping to the id is encapsulated inside BytesRefHash and is guaranteed to be increased for each added BytesRef. Note: The maximum capacity BytesRef instance passed to add() must not be longer than BYTE_BLOCK_SIZE-2. The internal storage is limited to 2GB total byte storage. */ type BytesRefHash struct { pool *ByteBlockPool bytesStart []int scratch1 *BytesRef hashSize int hashHalfSize int hashMask int count int lastCount int ids []int bytesStartArray BytesStartArray bytesUsed Counter } func NewBytesRefHash(pool *ByteBlockPool, capacity int, bytesStartArray BytesStartArray) *BytesRefHash { ids := make([]int, capacity) for i, _ := range ids { ids[i] = -1 } counter := bytesStartArray.BytesUsed() if counter == nil { counter = NewCounter() } counter.AddAndGet(int64(capacity) * NUM_BYTES_INT) return &BytesRefHash{ scratch1: NewEmptyBytesRef(), hashSize: capacity, hashHalfSize: capacity >> 1, hashMask: capacity - 1, lastCount: -1, pool: pool, ids: ids, bytesStartArray: bytesStartArray, bytesStart: bytesStartArray.Init(), bytesUsed: counter, } } /* Returns the number of values in this hash. */ func (h *BytesRefHash) Size() int { return h.count } /* Returns the ids array in arbitrary order. Valid ids start at offset of 0 and end at a limit of size() - 1 Note: This is a destructive operation. clear() must be called in order to reuse this BytesRefHash instance. */ func (h *BytesRefHash) compact() []int { assert2(h.bytesStart != nil, "bytesStart is nil - not initialized") upto := 0 for i := 0; i < h.hashSize; i++ { if h.ids[i] != -1 { if upto < i { h.ids[upto] = h.ids[i] h.ids[i] = -1 } upto++ } } assert(upto == h.count) h.lastCount = h.count return h.ids } type bytesRefIntroSorter struct { *IntroSorter owner *BytesRefHash compact []int comp func([]byte, []byte) bool pivot *BytesRef scratch1 *BytesRef scratch2 *BytesRef } func newBytesRefIntroSorter(owner *BytesRefHash, v []int, comp func([]byte, []byte) bool) *bytesRefIntroSorter { ans := &bytesRefIntroSorter{ owner: owner, compact: v, comp: comp, pivot: NewEmptyBytesRef(), scratch1: NewEmptyBytesRef(), scratch2: NewEmptyBytesRef(), } ans.IntroSorter = NewIntroSorter(ans, ans) return ans } func (a *bytesRefIntroSorter) Len() int { return len(a.compact) } func (a *bytesRefIntroSorter) Swap(i, j int) { a.compact[i], a.compact[j] = a.compact[j], a.compact[i] } func (a *bytesRefIntroSorter) Less(i, j int) bool { id1, id2 := a.compact[i], a.compact[j] assert(len(a.owner.bytesStart) > id1 && len(a.owner.bytesStart) > id2) a.owner.pool.SetBytesRef(a.scratch1, a.owner.bytesStart[id1]) a.owner.pool.SetBytesRef(a.scratch2, a.owner.bytesStart[id2]) return a.comp(a.scratch1.ToBytes(), a.scratch2.ToBytes()) } func (a *bytesRefIntroSorter) SetPivot(i int) { id := a.compact[i] assert(len(a.owner.bytesStart) > id) a.owner.pool.SetBytesRef(a.pivot, a.owner.bytesStart[id]) } func (a *bytesRefIntroSorter) PivotLess(j int) bool { id := a.compact[j] assert(len(a.owner.bytesStart) > id) a.owner.pool.SetBytesRef(a.scratch2, a.owner.bytesStart[id]) return a.comp(a.pivot.ToBytes(), a.scratch2.ToBytes()) } /* Returns the values array sorted by the referenced byte values. Note: this is a destructive operation. clear() must be called in order to reuse this BytesRefHash instance. */ func (h *BytesRefHash) Sort(comp func(a, b []byte) bool) []int { compact := h.compact() s := newBytesRefIntroSorter(h, compact, comp) s.Sort(0, h.count) // TODO remove this // for i, _ := range compact { // if compact[i+1] == -1 { // break // } // assert(!s.Less(i+1, i)) // if ok := !s.Less(i+1, i); !ok { // fmt.Println("DEBUG1", compact) // assert(ok) // } // } return compact } func (h *BytesRefHash) equals(id int, b []byte) bool { h.pool.SetBytesRef(h.scratch1, h.bytesStart[id]) return h.scratch1.bytesEquals(b) } func (h *BytesRefHash) shrink(targetSize int) bool { // Cannot use util.Shrink because we require power of 2: newSize := h.hashSize for newSize >= 8 && newSize/4 > targetSize { newSize /= 2 } if newSize != h.hashSize { h.bytesUsed.AddAndGet(NUM_BYTES_INT * -int64(h.hashSize-newSize)) h.hashSize = newSize h.ids = make([]int, h.hashSize) for i, _ := range h.ids { h.ids[i] = -1 } h.hashHalfSize = newSize / 2 h.hashMask = newSize - 1 return true } return false } /* Clears the BytesRef which maps to the given BytesRef */ func (h *BytesRefHash) Clear(resetPool bool) { h.lastCount = h.count h.count = 0 if resetPool { h.pool.Reset(false, false) // we don't need to 0-fill the bufferes } h.bytesStart = h.bytesStartArray.Clear() if h.lastCount != -1 && h.shrink(h.lastCount) { // shurnk clears the hash entries return } for i, _ := range h.ids { h.ids[i] = -1 } } type MaxBytesLengthExceededError string func (e MaxBytesLengthExceededError) Error() string { return string(e) } /* Adds a new BytesRef. */ func (h *BytesRefHash) Add(bytes []byte) (int, error) { assert2(h.bytesStart != nil, "Bytesstart is null - not initialized") length := len(bytes) // final position hashPos := h.findHash(bytes) e := h.ids[hashPos] if e == -1 { // new entry if len2 := 2 + len(bytes); len2+h.pool.ByteUpto > BYTE_BLOCK_SIZE { if len2 > BYTE_BLOCK_SIZE { return 0, MaxBytesLengthExceededError(fmt.Sprintf( "bytes can be at most %v in length; got %v", BYTE_BLOCK_SIZE-2, len(bytes))) } h.pool.NextBuffer() } buffer := h.pool.Buffer bufferUpto := h.pool.ByteUpto if h.count >= len(h.bytesStart) { h.bytesStart = h.bytesStartArray.Grow() assert2(h.count < len(h.bytesStart)+1, "count: %v len: %v", h.count, len(h.bytesStart)) } e = h.count h.count++ h.bytesStart[e] = bufferUpto + h.pool.ByteOffset // We first encode the length, followed by the bytes. Length is // encoded as vint, but will consume 1 or 2 bytes at most (we // reject too-long terms, above). if length < 128 { // 1 byte to store length buffer[bufferUpto] = byte(length) h.pool.ByteUpto += length + 1 assert2(length >= 0, "Length must be positive: %v", length) copy(buffer[bufferUpto+1:], bytes) } else { // 2 bytes to store length buffer[bufferUpto] = byte(0x80 | (length & 0x7f)) buffer[bufferUpto+1] = byte((length >> 7) & 0xff) h.pool.ByteUpto += length + 2 copy(buffer[bufferUpto+2:], bytes) } assert(h.ids[hashPos] == -1) h.ids[hashPos] = e if h.count == h.hashHalfSize { h.rehash(2*h.hashSize, true) } return e, nil } return -(e + 1), nil } func (h *BytesRefHash) findHash(bytes []byte) int { assert2(h.bytesStart != nil, "bytesStart is null - not initialized") code := h.doHash(bytes) // final position hashPos := code & h.hashMask if e := h.ids[hashPos]; e != -1 && !h.equals(e, bytes) { // conflict; use linear probe to find an open slot // (see LUCENE-5604): for { code++ hashPos = code & h.hashMask e = h.ids[hashPos] if e == -1 || h.equals(e, bytes) { break } } } return hashPos } /* Called when has is too small (> 50% occupied) or too large (< 20% occupied). */ func (h *BytesRefHash) rehash(newSize int, hashOnData bool) { newMask := newSize - 1 h.bytesUsed.AddAndGet(NUM_BYTES_INT * int64(newSize)) newHash := make([]int, newSize) for i, _ := range newHash { newHash[i] = -1 } for i := 0; i < h.hashSize; i++ { if e0 := h.ids[i]; e0 != -1 { var code int if hashOnData { off := h.bytesStart[e0] start := off & BYTE_BLOCK_MASK bytes := h.pool.Buffers[off>>BYTE_BLOCK_SHIFT] var length int var pos int if bytes[start]&0x80 == 0 { // length is 1 byte length = int(bytes[start]) pos = start + 1 } else { length = int(bytes[start]&0x7f) + (int(bytes[start+1]&0xff) << 7) pos = start + 2 } code = h.doHash(bytes[pos : pos+length]) } else { code = h.bytesStart[e0] } hashPos := code & newMask assert(hashPos >= 0) if newHash[hashPos] != -1 { // conflict; use linear probe to find an open slot // (see LUCENE-5604) for { code++ hashPos = code & newMask if newHash[hashPos] == -1 { break } } } assert(newHash[hashPos] == -1) newHash[hashPos] = e0 } } h.hashMask = newMask h.bytesUsed.AddAndGet(NUM_BYTES_INT * int64(-len(h.ids))) h.ids = newHash h.hashSize = newSize h.hashHalfSize = newSize / 2 } func (h *BytesRefHash) doHash(p []byte) int { return int(MurmurHash3_x86_32(p, GOOD_FAST_HASH_SEED)) } /* reinitializes the BytesRefHash after a previous clear() call. If clear() has not been called previously this method has no effect. */ func (h *BytesRefHash) Reinit() { if h.bytesStart == nil { h.bytesStart = h.bytesStartArray.Init() } if h.ids == nil { h.ids = make([]int, h.hashSize) h.bytesUsed.AddAndGet(NUM_BYTES_INT * int64(h.hashSize)) } } /* Returns the bytesStart offset into the internally used ByteBlockPool for the given bytesID. */ func (h *BytesRefHash) ByteStart(bytesId int) int { assert2(h.bytesStart != nil, "bytesStart is null - not initialized") assert2(bytesId >= 0 && bytesId <= h.count, "%v", bytesId) return h.bytesStart[bytesId] } /* Manages allocation of per-term addresses. */ type BytesStartArray interface { // Initializes the BytesStartArray. This call will allocate memory Init() []int // A Counter reference holding the number of bytes used by this // BytesStartArray. The BytesRefHash uses this reference to track // its memory usage BytesUsed() Counter // Grows the BytesStartArray Grow() []int // clears the BytesStartArray and returns the cleared instance. Clear() []int }
balzaczyy/golucene
core/util/bytesRefHash.go
GO
apache-2.0
10,103
package org.batfish.question.namedstructures; import static org.batfish.question.namedstructures.NamedStructuresAnswerer.getAllStructureNamesOfType; import static org.batfish.question.namedstructures.NamedStructuresAnswerer.insertedObject; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multiset; import java.util.Map; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.ConfigurationFormat; import org.batfish.datamodel.NetworkFactory; import org.batfish.datamodel.pojo.Node; import org.batfish.datamodel.questions.NamedStructurePropertySpecifier; import org.batfish.datamodel.routing_policy.RoutingPolicy; import org.batfish.datamodel.table.Row; import org.junit.Test; public class NamedStructuresAnswererTest { private static final String ALL_NODES = ".*"; @Test public void testGetAllStructureNamesOfType() { NetworkFactory nf = new NetworkFactory(); // c1 has both routing policies Configuration c1 = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); nf.routingPolicyBuilder().setOwner(c1).setName("rp1").build(); nf.routingPolicyBuilder().setOwner(c1).setName("rp2").build(); // c2 has only one routing policy Configuration c2 = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); nf.routingPolicyBuilder().setOwner(c1).setName("rp1").build(); Map<String, Configuration> configurations = ImmutableMap.of("node1", c1, "node2", c2); // both policies should be returned assertThat( getAllStructureNamesOfType( NamedStructurePropertySpecifier.ROUTING_POLICY, configurations.keySet(), configurations), equalTo(ImmutableSet.of("rp1", "rp2"))); } @Test public void testRawAnswerDefinition() { NetworkFactory nf = new NetworkFactory(); Configuration c = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); RoutingPolicy rp1 = nf.routingPolicyBuilder().setOwner(c).setName("rp1").build(); RoutingPolicy rp2 = nf.routingPolicyBuilder().setOwner(c).setName("rp2").build(); nf.vrfBuilder().setOwner(c).build(); Map<String, Configuration> configurations = ImmutableMap.of("node1", c); // only get routing policies NamedStructuresQuestion question = new NamedStructuresQuestion( ALL_NODES, NamedStructurePropertySpecifier.ROUTING_POLICY, null, null, false); Multiset<Row> rows = NamedStructuresAnswerer.rawAnswer( question, configurations.keySet(), configurations, NamedStructuresAnswerer.createMetadata(question).toColumnMap()); Multiset<Row> expected = HashMultiset.create( ImmutableList.of( Row.builder() .put(NamedStructuresAnswerer.COL_NODE, new Node("node1")) .put( NamedStructuresAnswerer.COL_STRUCTURE_TYPE, NamedStructurePropertySpecifier.ROUTING_POLICY) .put(NamedStructuresAnswerer.COL_STRUCTURE_NAME, "rp1") .put( NamedStructuresAnswerer.COL_STRUCTURE_DEFINITION, insertedObject(rp1, NamedStructurePropertySpecifier.ROUTING_POLICY)) .build(), Row.builder() .put(NamedStructuresAnswerer.COL_NODE, new Node("node1")) .put( NamedStructuresAnswerer.COL_STRUCTURE_TYPE, NamedStructurePropertySpecifier.ROUTING_POLICY) .put(NamedStructuresAnswerer.COL_STRUCTURE_NAME, "rp2") .put( NamedStructuresAnswerer.COL_STRUCTURE_DEFINITION, insertedObject(rp2, NamedStructurePropertySpecifier.ROUTING_POLICY)) .build())); assertThat(rows, equalTo(expected)); } @Test public void testRawAnswerIgnoreGenerated() { NetworkFactory nf = new NetworkFactory(); Configuration c = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); RoutingPolicy rp1 = nf.routingPolicyBuilder().setOwner(c).setName("rp1").build(); nf.routingPolicyBuilder().setOwner(c).setName("~rp2").build(); Map<String, Configuration> configurations = ImmutableMap.of("node1", c); NamedStructuresQuestion question = new NamedStructuresQuestion(ALL_NODES, "/.*/", null, true, null); Multiset<Row> rows = NamedStructuresAnswerer.rawAnswer( question, configurations.keySet(), configurations, NamedStructuresAnswerer.createMetadata(question).toColumnMap()); Multiset<Row> expected = HashMultiset.create( ImmutableList.of( Row.builder() .put(NamedStructuresAnswerer.COL_NODE, new Node("node1")) .put( NamedStructuresAnswerer.COL_STRUCTURE_TYPE, NamedStructurePropertySpecifier.ROUTING_POLICY) .put(NamedStructuresAnswerer.COL_STRUCTURE_NAME, "rp1") .put( NamedStructuresAnswerer.COL_STRUCTURE_DEFINITION, insertedObject(rp1, NamedStructurePropertySpecifier.ROUTING_POLICY)) .build())); assertThat(rows, equalTo(expected)); } @Test public void testRawAnswerPresence() { NetworkFactory nf = new NetworkFactory(); Configuration c1 = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); nf.routingPolicyBuilder().setOwner(c1).setName("rp1").build(); Configuration c2 = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); Map<String, Configuration> configurations = ImmutableMap.of("node1", c1, "node2", c2); NamedStructuresQuestion question = new NamedStructuresQuestion(ALL_NODES, "/.*/", null, null, true); Multiset<Row> rows = NamedStructuresAnswerer.rawAnswer( question, configurations.keySet(), configurations, NamedStructuresAnswerer.createMetadata(question).toColumnMap()); Multiset<Row> expected = HashMultiset.create( ImmutableList.of( Row.builder() .put(NamedStructuresAnswerer.COL_NODE, new Node("node1")) .put( NamedStructuresAnswerer.COL_STRUCTURE_TYPE, NamedStructurePropertySpecifier.ROUTING_POLICY) .put(NamedStructuresAnswerer.COL_STRUCTURE_NAME, "rp1") .put(NamedStructuresAnswerer.COL_PRESENT_ON_NODE, true) .build(), Row.builder() .put(NamedStructuresAnswerer.COL_NODE, new Node("node2")) .put( NamedStructuresAnswerer.COL_STRUCTURE_TYPE, NamedStructurePropertySpecifier.ROUTING_POLICY) .put(NamedStructuresAnswerer.COL_STRUCTURE_NAME, "rp1") .put(NamedStructuresAnswerer.COL_PRESENT_ON_NODE, false) .build())); assertThat(rows, equalTo(expected)); } @Test public void testRawAnswerStructureNameRegex() { NetworkFactory nf = new NetworkFactory(); Configuration c = nf.configurationBuilder().setConfigurationFormat(ConfigurationFormat.CISCO_IOS).build(); RoutingPolicy rp1 = nf.routingPolicyBuilder().setOwner(c).setName("selected-rp1").build(); nf.routingPolicyBuilder().setOwner(c).setName("leftout-rp2").build(); Map<String, Configuration> configurations = ImmutableMap.of("node1", c); NamedStructuresQuestion question = new NamedStructuresQuestion(ALL_NODES, "/.*/", "selected.*", false, null); Multiset<Row> rows = NamedStructuresAnswerer.rawAnswer( question, configurations.keySet(), configurations, NamedStructuresAnswerer.createMetadata(question).toColumnMap()); Multiset<Row> expected = HashMultiset.create( ImmutableList.of( Row.builder() .put(NamedStructuresAnswerer.COL_NODE, new Node("node1")) .put( NamedStructuresAnswerer.COL_STRUCTURE_TYPE, NamedStructurePropertySpecifier.ROUTING_POLICY) .put(NamedStructuresAnswerer.COL_STRUCTURE_NAME, "selected-rp1") .put( NamedStructuresAnswerer.COL_STRUCTURE_DEFINITION, insertedObject(rp1, NamedStructurePropertySpecifier.ROUTING_POLICY)) .build())); assertThat(rows, equalTo(expected)); } }
intentionet/batfish
projects/question/src/test/java/org/batfish/question/namedstructures/NamedStructuresAnswererTest.java
Java
apache-2.0
9,212
define(function(require, exports, module) { var Notify = require('common/bootstrap-notify'); exports.run = function() { var $table = $('#teacher-table'); $table.on('click', '.promote-user', function(){ $.post($(this).data('url'),function(response) { window.location.reload(); }); }); $table.on('click', '.cancel-promote-user', function(){ $.post($(this).data('url'),function(response) { window.location.reload(); }); }); }; });
18826252059/im
web/bundles/topxiaadmin/js/controller/user/teacher-list.js
JavaScript
apache-2.0
539
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.rest.util.container; import org.junit.rules.ExternalResource; import org.junit.rules.TestRule; import javax.ws.rs.core.Application; import java.util.HashMap; import java.util.Map; public class JerseySpecifics implements ContainerSpecifics { protected static final TestRuleFactory DEFAULT_RULE_FACTORY = new EmbeddedServerRuleFactory(new JaxrsApplication()); protected static final Map<Class<?>, TestRuleFactory> TEST_RULE_FACTORIES = new HashMap<Class<?>, TestRuleFactory>(); public TestRule getTestRule(Class<?> testClass) { TestRuleFactory ruleFactory = DEFAULT_RULE_FACTORY; if (TEST_RULE_FACTORIES.containsKey(testClass)) { ruleFactory = TEST_RULE_FACTORIES.get(testClass); } return ruleFactory.createTestRule(); } public static class EmbeddedServerRuleFactory implements TestRuleFactory { protected Application jaxRsApplication; public EmbeddedServerRuleFactory(Application jaxRsApplication) { this.jaxRsApplication = jaxRsApplication; } public TestRule createTestRule() { return new ExternalResource() { JerseyServerBootstrap bootstrap = new JerseyServerBootstrap(jaxRsApplication); protected void before() throws Throwable { bootstrap.start(); } protected void after() { bootstrap.stop(); } }; } } }
falko/camunda-bpm-platform
engine-rest/engine-rest-jaxrs2/src/test/java-jersey2/org/camunda/bpm/engine/rest/util/container/JerseySpecifics.java
Java
apache-2.0
2,193
/* * 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.stratos.nginx.extension; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.stratos.load.balancer.common.domain.*; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.Collection; /** * Nginx load balancer configuration writer. */ public class NginxConfigWriter { private static final Log log = LogFactory.getLog(Main.class); private static final String NEW_LINE = System.getProperty("line.separator"); private static final String TAB = " "; private String templatePath; private String templateName; private String confFilePath; private String statsSocketFilePath; public NginxConfigWriter(String templatePath, String templateName, String confFilePath, String statsSocketFilePath) { this.templatePath = templatePath; this.templateName = templateName; this.confFilePath = confFilePath; this.statsSocketFilePath = statsSocketFilePath; } public boolean write(Topology topology) { StringBuilder configurationBuilder = new StringBuilder(); for (Service service : topology.getServices()) { for (Cluster cluster : service.getClusters()) { if ((service.getPorts() == null) || (service.getPorts().size() == 0)) { throw new RuntimeException(String.format("No ports found in service: %s", service.getServiceName())); } generateConfigurationForCluster(cluster, service.getPorts(), configurationBuilder); } } // Start velocity engine VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); ve.init(); // Open the template Template t = ve.getTemplate(templateName); // Insert strings into the template VelocityContext context = new VelocityContext(); context.put("configuration", configurationBuilder.toString()); // Create a new string from the template StringWriter stringWriter = new StringWriter(); t.merge(context, stringWriter); String configuration = stringWriter.toString(); // Write configuration file try { BufferedWriter writer = new BufferedWriter(new FileWriter(confFilePath)); writer.write(configuration); writer.close(); if (log.isInfoEnabled()) { log.info(String.format("Configuration written to file: %s", confFilePath)); } return true; } catch (IOException e) { if (log.isErrorEnabled()) { log.error(String.format("Could not write configuration file: %s", confFilePath)); } throw new RuntimeException(e); } } /** * Generate configuration for a cluster with the following format: * * <transport> { * upstream <cluster-hostname> { * server <hostname>:<port>; * server <hostname>:<port>; * } * server { * listen <proxy-port>; * server_name <cluster-hostname>; * location / { * proxy_pass http://<cluster-hostname> * } * location /nginx_status { * stub_status on; * access_log off; * allow 127.0.0.1; * deny all; * } * } * } * @param cluster * @param ports * @param text */ private void generateConfigurationForCluster(Cluster cluster, Collection<Port> ports, StringBuilder text) { for (Port port : ports) { for (String hostname : cluster.getHostNames()) { // Start transport block text.append(port.getProtocol()).append(" {").append(NEW_LINE); // Start upstream block text.append(TAB).append("upstream ").append(hostname).append(" {").append(NEW_LINE); for (Member member : cluster.getMembers()) { // Start upstream server block text.append(TAB).append(TAB).append("server ").append(member.getHostName()).append(":") .append(port.getValue()).append(";").append(NEW_LINE); // End upstream server block } text.append(TAB).append("}").append(NEW_LINE); // End upstream block // Start server block text.append(NEW_LINE); text.append(TAB).append("server {").append(NEW_LINE); text.append(TAB).append(TAB).append("listen ").append(port.getProxy()).append(";").append(NEW_LINE); text.append(TAB).append(TAB).append("server_name ").append(hostname).append(";").append(NEW_LINE); text.append(TAB).append(TAB).append("location / {").append(NEW_LINE); text.append(TAB).append(TAB).append(TAB).append("proxy_pass").append(TAB) .append("http://").append(hostname).append(";").append(NEW_LINE); text.append(TAB).append(TAB).append("}").append(NEW_LINE); text.append(TAB).append(TAB).append("location /nginx_status {").append(NEW_LINE); text.append(TAB).append(TAB).append(TAB).append("stub_status on;").append(NEW_LINE); text.append(TAB).append(TAB).append(TAB).append("access_log off;").append(NEW_LINE); text.append(TAB).append(TAB).append(TAB).append("allow 127.0.0.1;").append(NEW_LINE); text.append(TAB).append(TAB).append(TAB).append("deny all;").append(NEW_LINE); text.append(TAB).append(TAB).append("}").append(NEW_LINE); text.append(TAB).append("}").append(NEW_LINE); // End server block text.append("}").append(NEW_LINE); // End transport block } } } }
hsbhathiya/stratos
extensions/load-balancer/nginx-extension/src/main/java/org/apache/stratos/nginx/extension/NginxConfigWriter.java
Java
apache-2.0
7,122
// Copyright 2015 The Project Buendia 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 distrib- // uted 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 // specific language governing permissions and limitations under the License. package org.projectbuendia.client.json; /** A list of concept results returned by the server. */ public class JsonConceptResponse { public JsonConcept[] results; }
llvasconcellos/client
app/src/main/java/org/projectbuendia/client/json/JsonConceptResponse.java
Java
apache-2.0
762
/* Copyright 2014 The Kubernetes Authors 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. */ package testclient import ( "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/fields" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/watch" ) // FakeResourceQuotas implements ResourceQuotaInterface. Meant to be embedded into a struct to get a default // implementation. This makes faking out just the methods you want to test easier. type FakeResourceQuotas struct { Fake *Fake Namespace string } func (c *FakeResourceQuotas) Get(name string) (*api.ResourceQuota, error) { obj, err := c.Fake.Invokes(NewGetAction("resourcequotas", c.Namespace, name), &api.ResourceQuota{}) if obj == nil { return nil, err } return obj.(*api.ResourceQuota), err } func (c *FakeResourceQuotas) List(label labels.Selector, field fields.Selector) (*api.ResourceQuotaList, error) { obj, err := c.Fake.Invokes(NewListAction("resourcequotas", c.Namespace, label, field), &api.ResourceQuotaList{}) if obj == nil { return nil, err } return obj.(*api.ResourceQuotaList), err } func (c *FakeResourceQuotas) Create(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { obj, err := c.Fake.Invokes(NewCreateAction("resourcequotas", c.Namespace, resourceQuota), resourceQuota) if obj == nil { return nil, err } return obj.(*api.ResourceQuota), err } func (c *FakeResourceQuotas) Update(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { obj, err := c.Fake.Invokes(NewUpdateAction("resourcequotas", c.Namespace, resourceQuota), resourceQuota) if obj == nil { return nil, err } return obj.(*api.ResourceQuota), err } func (c *FakeResourceQuotas) Delete(name string) error { _, err := c.Fake.Invokes(NewDeleteAction("resourcequotas", c.Namespace, name), &api.ResourceQuota{}) return err } func (c *FakeResourceQuotas) Watch(label labels.Selector, field fields.Selector, opts unversioned.ListOptions) (watch.Interface, error) { return c.Fake.InvokesWatch(NewWatchAction("resourcequotas", c.Namespace, label, field, opts)) } func (c *FakeResourceQuotas) UpdateStatus(resourceQuota *api.ResourceQuota) (*api.ResourceQuota, error) { obj, err := c.Fake.Invokes(NewUpdateSubresourceAction("resourcequotas", "status", c.Namespace, resourceQuota), resourceQuota) if obj == nil { return nil, err } return obj.(*api.ResourceQuota), err }
GertiPoppel/kubernetes
pkg/client/unversioned/testclient/fake_resource_quotas.go
GO
apache-2.0
2,914
'use strict'; /* // [START classdefinition] */ export default class exampleClass { /* // [END classdefinition] */ constructor () { super(); console.log('Example Constructor'); } exampleFunction () { console.log('Example Function'); } }
beaufortfrancois/WebFundamentals
src/content/en/resources/jekyll/_code/example.js
JavaScript
apache-2.0
261
# Copyright (c) 2015 OpenStack Foundation. 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. from neutron import context from neutron.db.quota import api as quota_api from neutron.tests.unit import testlib_api class TestQuotaDbApi(testlib_api.SqlTestCaseLight): def _set_context(self): self.tenant_id = 'Higuain' self.context = context.Context('Gonzalo', self.tenant_id, is_admin=False, is_advsvc=False) def _create_quota_usage(self, resource, used, reserved, tenant_id=None): tenant_id = tenant_id or self.tenant_id return quota_api.set_quota_usage( self.context, resource, tenant_id, in_use=used, reserved=reserved) def _verify_quota_usage(self, usage_info, expected_resource=None, expected_used=None, expected_reserved=None, expected_dirty=None): self.assertEqual(self.tenant_id, usage_info.tenant_id) if expected_resource: self.assertEqual(expected_resource, usage_info.resource) if expected_dirty is not None: self.assertEqual(expected_dirty, usage_info.dirty) if expected_used is not None: self.assertEqual(expected_used, usage_info.used) if expected_reserved is not None: self.assertEqual(expected_reserved, usage_info.reserved) if expected_used is not None and expected_reserved is not None: self.assertEqual(expected_used + expected_reserved, usage_info.total) def setUp(self): super(TestQuotaDbApi, self).setUp() self._set_context() def test_create_quota_usage(self): usage_info = self._create_quota_usage('goals', 26, 10) self._verify_quota_usage(usage_info, expected_resource='goals', expected_used=26, expected_reserved=10) def test_update_quota_usage(self): self._create_quota_usage('goals', 26, 10) # Higuain scores a double usage_info_1 = quota_api.set_quota_usage( self.context, 'goals', self.tenant_id, in_use=28) self._verify_quota_usage(usage_info_1, expected_used=28, expected_reserved=10) usage_info_2 = quota_api.set_quota_usage( self.context, 'goals', self.tenant_id, reserved=8) self._verify_quota_usage(usage_info_2, expected_used=28, expected_reserved=8) def test_update_quota_usage_with_deltas(self): self._create_quota_usage('goals', 26, 10) # Higuain scores a double usage_info_1 = quota_api.set_quota_usage( self.context, 'goals', self.tenant_id, in_use=2, delta=True) self._verify_quota_usage(usage_info_1, expected_used=28, expected_reserved=10) usage_info_2 = quota_api.set_quota_usage( self.context, 'goals', self.tenant_id, reserved=-2, delta=True) self._verify_quota_usage(usage_info_2, expected_used=28, expected_reserved=8) def test_set_quota_usage_dirty(self): self._create_quota_usage('goals', 26, 10) # Higuain needs a shower after the match self.assertEqual(1, quota_api.set_quota_usage_dirty( self.context, 'goals', self.tenant_id)) usage_info = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id) self._verify_quota_usage(usage_info, expected_dirty=True) # Higuain is clean now self.assertEqual(1, quota_api.set_quota_usage_dirty( self.context, 'goals', self.tenant_id, dirty=False)) usage_info = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id) self._verify_quota_usage(usage_info, expected_dirty=False) def test_set_dirty_non_existing_quota_usage(self): self.assertEqual(0, quota_api.set_quota_usage_dirty( self.context, 'meh', self.tenant_id)) def test_set_resources_quota_usage_dirty(self): self._create_quota_usage('goals', 26, 10) self._create_quota_usage('assists', 11, 5) self._create_quota_usage('bookings', 3, 1) self.assertEqual(2, quota_api.set_resources_quota_usage_dirty( self.context, ['goals', 'bookings'], self.tenant_id)) usage_info_goals = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id) usage_info_assists = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'assists', self.tenant_id) usage_info_bookings = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'bookings', self.tenant_id) self._verify_quota_usage(usage_info_goals, expected_dirty=True) self._verify_quota_usage(usage_info_assists, expected_dirty=False) self._verify_quota_usage(usage_info_bookings, expected_dirty=True) def test_set_resources_quota_usage_dirty_with_empty_list(self): self._create_quota_usage('goals', 26, 10) self._create_quota_usage('assists', 11, 5) self._create_quota_usage('bookings', 3, 1) # Expect all the resources for the tenant to be set dirty self.assertEqual(3, quota_api.set_resources_quota_usage_dirty( self.context, [], self.tenant_id)) usage_info_goals = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id) usage_info_assists = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'assists', self.tenant_id) usage_info_bookings = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'bookings', self.tenant_id) self._verify_quota_usage(usage_info_goals, expected_dirty=True) self._verify_quota_usage(usage_info_assists, expected_dirty=True) self._verify_quota_usage(usage_info_bookings, expected_dirty=True) # Higuain is clean now self.assertEqual(1, quota_api.set_quota_usage_dirty( self.context, 'goals', self.tenant_id, dirty=False)) usage_info = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id) self._verify_quota_usage(usage_info, expected_dirty=False) def _test_set_all_quota_usage_dirty(self, expected): self._create_quota_usage('goals', 26, 10) self._create_quota_usage('goals', 12, 6, tenant_id='Callejon') self.assertEqual(expected, quota_api.set_all_quota_usage_dirty( self.context, 'goals')) def test_set_all_quota_usage_dirty(self): # All goal scorers need a shower after the match, but since this is not # admin context we can clean only one self._test_set_all_quota_usage_dirty(expected=1) def test_get_quota_usage_by_tenant(self): self._create_quota_usage('goals', 26, 10) self._create_quota_usage('assists', 11, 5) # Create a resource for a different tenant self._create_quota_usage('mehs', 99, 99, tenant_id='buffon') usage_infos = quota_api.get_quota_usage_by_tenant_id( self.context, self.tenant_id) self.assertEqual(2, len(usage_infos)) resources = [info.resource for info in usage_infos] self.assertIn('goals', resources) self.assertIn('assists', resources) def test_get_quota_usage_by_resource(self): self._create_quota_usage('goals', 26, 10) self._create_quota_usage('assists', 11, 5) self._create_quota_usage('goals', 12, 6, tenant_id='Callejon') usage_infos = quota_api.get_quota_usage_by_resource( self.context, 'goals') # Only 1 result expected in tenant context self.assertEqual(1, len(usage_infos)) self._verify_quota_usage(usage_infos[0], expected_resource='goals', expected_used=26, expected_reserved=10) def test_get_quota_usage_by_tenant_and_resource(self): self._create_quota_usage('goals', 26, 10) usage_info = quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id) self._verify_quota_usage(usage_info, expected_resource='goals', expected_used=26, expected_reserved=10) def test_get_non_existing_quota_usage_returns_none(self): self.assertIsNone(quota_api.get_quota_usage_by_resource_and_tenant( self.context, 'goals', self.tenant_id)) class TestQuotaDbApiAdminContext(TestQuotaDbApi): def _set_context(self): self.tenant_id = 'Higuain' self.context = context.Context('Gonzalo', self.tenant_id, is_admin=True, is_advsvc=True, load_admin_roles=False) def test_get_quota_usage_by_resource(self): self._create_quota_usage('goals', 26, 10) self._create_quota_usage('assists', 11, 5) self._create_quota_usage('goals', 12, 6, tenant_id='Callejon') usage_infos = quota_api.get_quota_usage_by_resource( self.context, 'goals') # 2 results expected in admin context self.assertEqual(2, len(usage_infos)) for usage_info in usage_infos: self.assertEqual('goals', usage_info.resource) def test_set_all_quota_usage_dirty(self): # All goal scorers need a shower after the match, and with admin # context we should be able to clean all of them self._test_set_all_quota_usage_dirty(expected=2)
paninetworks/neutron
neutron/tests/unit/db/quota/test_api.py
Python
apache-2.0
10,763
// Generated by xsd compiler for android/java // DO NOT CHANGE! package ebay.apis.eblbasecomponents; import java.io.Serializable; import com.leansoft.nano.annotation.*; import java.util.List; import java.util.Date; /** * * Returns the estimated fees for the listing that is being verified for a re-list. * */ @RootElement(name = "VerifyRelistItemResponse", namespace = "urn:ebay:apis:eBLBaseComponents") public class VerifyRelistItemResponseType extends AbstractResponseType implements Serializable { private static final long serialVersionUID = -1L; @Element(name = "ItemID") private String itemID; @Element(name = "Fees") private FeesType fees; @Element(name = "StartTime") private Date startTime; @Element(name = "EndTime") private Date endTime; @Element(name = "DiscountReason") private List<DiscountReasonCodeType> discountReason; @Element(name = "ProductSuggestions") private ProductSuggestionsType productSuggestions; /** * public getter * * * Unique item ID for the new listing. As VerifyRelistItem does not * actually re-list an item, returns 0 instead of a normal item ID. * * * @returns java.lang.String */ public String getItemID() { return this.itemID; } /** * public setter * * * Unique item ID for the new listing. As VerifyRelistItem does not * actually re-list an item, returns 0 instead of a normal item ID. * * * @param java.lang.String */ public void setItemID(String itemID) { this.itemID = itemID; } /** * public getter * * * Child elements contain the estimated listing fees for the new item * listing. The fees do not include the Final Value Fee (FVF), which cannot * be determined until an item is sold. * * * @returns ebay.apis.eblbasecomponents.FeesType */ public FeesType getFees() { return this.fees; } /** * public setter * * * Child elements contain the estimated listing fees for the new item * listing. The fees do not include the Final Value Fee (FVF), which cannot * be determined until an item is sold. * * * @param ebay.apis.eblbasecomponents.FeesType */ public void setFees(FeesType fees) { this.fees = fees; } /** * public getter * * * Date and time the new listing became active on the eBay site. * * * @returns java.util.Date */ public Date getStartTime() { return this.startTime; } /** * public setter * * * Date and time the new listing became active on the eBay site. * * * @param java.util.Date */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * public getter * * * Date and time when the new listing ends. This is the starting time plus * the listing duration. * * * @returns java.util.Date */ public Date getEndTime() { return this.endTime; } /** * public setter * * * Date and time when the new listing ends. This is the starting time plus * the listing duration. * * * @param java.util.Date */ public void setEndTime(Date endTime) { this.endTime = endTime; } /** * public getter * * * The nature of the discount, if a discount would have applied * had this actually been listed at this time. * * * @returns java.util.List<ebay.apis.eblbasecomponents.DiscountReasonCodeType> */ public List<DiscountReasonCodeType> getDiscountReason() { return this.discountReason; } /** * public setter * * * The nature of the discount, if a discount would have applied * had this actually been listed at this time. * * * @param java.util.List<ebay.apis.eblbasecomponents.DiscountReasonCodeType> */ public void setDiscountReason(List<DiscountReasonCodeType> discountReason) { this.discountReason = discountReason; } /** * public getter * * * Provides a list of products recommended by eBay which match the item information * provided by the seller. * Not applicable to Half.com. * * * @returns ebay.apis.eblbasecomponents.ProductSuggestionsType */ public ProductSuggestionsType getProductSuggestions() { return this.productSuggestions; } /** * public setter * * * Provides a list of products recommended by eBay which match the item information * provided by the seller. * Not applicable to Half.com. * * * @param ebay.apis.eblbasecomponents.ProductSuggestionsType */ public void setProductSuggestions(ProductSuggestionsType productSuggestions) { this.productSuggestions = productSuggestions; } }
bulldog2011/nano-rest
sample/HelloEBayTrading/src/ebay/apis/eblbasecomponents/VerifyRelistItemResponseType.java
Java
apache-2.0
4,812
require "language/go" class Cosi < Formula desc "Implementation of scalable collective signing" homepage "https://github.com/dedis/cosi" url "https://github.com/dedis/cosi/archive/0.8.6.tar.gz" sha256 "007e4c4def13fcecf7301d86f177f098c583151c8a3d940ccb4c65a84413a9eb" license "AGPL-3.0" bottle do cellar :any_skip_relocation sha256 "30bbb457c0fb67ee264331e434068a4a747ece4cbc536cb75d289a06e93988e2" => :catalina sha256 "2ddd695441977b1cd435fbae28d9aa864d48b7a90ec24971348d91b5d0e551df" => :mojave sha256 "00663999a04ee29f52e334022cc828d7ebe89a442f1e713afb2167112f4ebf75" => :high_sierra end depends_on "go" => :build go_resource "github.com/BurntSushi/toml" do url "https://github.com/BurntSushi/toml.git", revision: "f0aeabca5a127c4078abb8c8d64298b147264b55" end go_resource "github.com/daviddengcn/go-colortext" do url "https://github.com/daviddengcn/go-colortext.git", revision: "511bcaf42ccd42c38aba7427b6673277bf19e2a1" end go_resource "github.com/dedis/crypto" do url "https://github.com/dedis/crypto.git", revision: "d9272cb478c0942e1d60049e6df219cba2067fcd" end go_resource "github.com/dedis/protobuf" do url "https://github.com/dedis/protobuf.git", revision: "6948fbd96a0f1e4e96582003261cf647dc66c831" end go_resource "github.com/montanaflynn/stats" do url "https://github.com/montanaflynn/stats.git", revision: "60dcacf48f43d6dd654d0ed94120ff5806c5ca5c" end go_resource "github.com/satori/go.uuid" do url "https://github.com/satori/go.uuid.git", revision: "f9ab0dce87d815821e221626b772e3475a0d2749" end go_resource "golang.org/x/net" do url "https://go.googlesource.com/net.git", revision: "0c607074acd38c5f23d1344dfe74c977464d1257" end go_resource "gopkg.in/codegangsta/cli.v1" do url "https://gopkg.in/codegangsta/cli.v1.git", revision: "01857ac33766ce0c93856370626f9799281c14f4" end go_resource "gopkg.in/dedis/cothority.v0" do url "https://gopkg.in/dedis/cothority.v0.git", revision: "e5eb384290e5fd98b8cb150a1348661aa2d49e2a" end def install mkdir_p buildpath/"src/github.com/dedis" ln_s buildpath, buildpath/"src/github.com/dedis/cosi" ENV["GOPATH"] = "#{buildpath}/Godeps/_workspace:#{buildpath}" Language::Go.stage_deps resources, buildpath/"src" system "go", "build", "-o", "cosi" prefix.install "dedis_group.toml" bin.install "cosi" end test do port = free_port (testpath/"config.toml").write <<~EOS Public = "7b6d6361686d0c76d9f4b40961736eb5d0849f7db3f8bfd8f869b8015d831d45" Private = "01a80f4fef21db2aea18e5288fe9aa71324a8ad202609139e5cfffc4ffdc4484" Addresses = ["0.0.0.0:#{port}"] EOS (testpath/"group.toml").write <<~EOS [[servers]] Addresses = ["127.0.0.1:#{port}"] Public = "e21jYWhtDHbZ9LQJYXNutdCEn32z+L/Y+Gm4AV2DHUU=" EOS begin file = prefix/"README.md" sig = "README.sig" pid = fork { exec bin/"cosi", "server", "-config", "config.toml" } sleep 2 assert_match "Success", shell_output("#{bin}/cosi check -g group.toml") system bin/"cosi", "sign", "-g", "group.toml", "-o", sig, file out = shell_output("#{bin}/cosi verify -g group.toml -s #{sig} #{file}") assert_match "OK", out ensure Process.kill("TERM", pid) end end end
jabenninghoff/homebrew-core
Formula/cosi.rb
Ruby
bsd-2-clause
3,409
cask 'jetbrains-toolbox' do version '1.0.1569' sha256 '5e47e404f7b9aa6e5d500eceb59801a9c1dc4da104e29fe1e392956188369b71' url "https://download.jetbrains.com/toolbox/jetbrains-toolbox-#{version}.dmg" name 'JetBrains Toolbox' homepage 'https://www.jetbrains.com/' license :gratis app 'JetBrains Toolbox.app' end
pacav69/homebrew-cask
Casks/jetbrains-toolbox.rb
Ruby
bsd-2-clause
326
cask 'rubymine' do version '2018.1.4,181.5281.41' sha256 'e89880cfed154e01545063f830e444f0a9ae3509b177f254a92032544cffe24a' url "https://download.jetbrains.com/ruby/RubyMine-#{version.before_comma}.dmg" appcast 'https://data.services.jetbrains.com/products/releases?code=RM&latest=true&type=release' name 'RubyMine' homepage 'https://www.jetbrains.com/ruby/' auto_updates true app 'RubyMine.app' uninstall_postflight do ENV['PATH'].split(File::PATH_SEPARATOR).map { |path| File.join(path, 'mine') }.each { |path| File.delete(path) if File.exist?(path) && File.readlines(path).grep(%r{# see com.intellij.idea.SocketLock for the server side of this interface}).any? } end zap trash: [ "~/Library/Application Support/RubyMine#{version.major_minor}", "~/Library/Caches/RubyMine#{version.major_minor}", "~/Library/Logs/RubyMine#{version.major_minor}", "~/Library/Preferences/RubyMine#{version.major_minor}", ] end
goxberry/homebrew-cask
Casks/rubymine.rb
Ruby
bsd-2-clause
1,013
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/allocator/allocator_extension.h" #include "base/logging.h" namespace base { namespace allocator { bool GetProperty(const char* name, size_t* value) { thunks::GetPropertyFunction get_property_function = base::allocator::thunks::GetGetPropertyFunction(); return get_property_function != NULL && get_property_function(name, value); } void GetStats(char* buffer, int buffer_length) { DCHECK_GT(buffer_length, 0); thunks::GetStatsFunction get_stats_function = base::allocator::thunks::GetGetStatsFunction(); if (get_stats_function) get_stats_function(buffer, buffer_length); else buffer[0] = '\0'; } void ReleaseFreeMemory() { thunks::ReleaseFreeMemoryFunction release_free_memory_function = base::allocator::thunks::GetReleaseFreeMemoryFunction(); if (release_free_memory_function) release_free_memory_function(); } void SetGetPropertyFunction( thunks::GetPropertyFunction get_property_function) { DCHECK_EQ(base::allocator::thunks::GetGetPropertyFunction(), reinterpret_cast<thunks::GetPropertyFunction>(NULL)); base::allocator::thunks::SetGetPropertyFunction(get_property_function); } void SetGetStatsFunction(thunks::GetStatsFunction get_stats_function) { DCHECK_EQ(base::allocator::thunks::GetGetStatsFunction(), reinterpret_cast<thunks::GetStatsFunction>(NULL)); base::allocator::thunks::SetGetStatsFunction(get_stats_function); } void SetReleaseFreeMemoryFunction( thunks::ReleaseFreeMemoryFunction release_free_memory_function) { DCHECK_EQ(base::allocator::thunks::GetReleaseFreeMemoryFunction(), reinterpret_cast<thunks::ReleaseFreeMemoryFunction>(NULL)); base::allocator::thunks::SetReleaseFreeMemoryFunction( release_free_memory_function); } } // namespace allocator } // namespace base
leighpauls/k2cro4
base/allocator/allocator_extension.cc
C++
bsd-3-clause
1,997
package com.tinkerpop.pipes.transform; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.pipes.util.PipeHelper; import java.util.Arrays; /** * BothEdgesPipe emits both the outgoing and incoming edges of a vertex. * * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class BothEdgesPipe extends VerticesEdgesPipe { public BothEdgesPipe(final String... labels) { super(Direction.BOTH, labels); } public BothEdgesPipe(final int branchFactor, final String... labels) { super(Direction.BOTH, branchFactor, labels); } public String toString() { return (this.branchFactor == Integer.MAX_VALUE) ? PipeHelper.makePipeString(this, Arrays.asList(this.labels)) : PipeHelper.makePipeString(this, this.branchFactor, Arrays.asList(this.labels)); } }
whshev/pipes
src/main/java/com/tinkerpop/pipes/transform/BothEdgesPipe.java
Java
bsd-3-clause
855
/* @flow */ /* Flow declarations for express requests and responses */ /* eslint-disable no-unused-vars */ declare class Request { method: String; body: Object; query: Object; } declare class Response { status: (code: Number) => Response; set: (field: String, value: String) => Response; send: (body: String) => void; }
jamiehodge/express-graphql
resources/interfaces/express.js
JavaScript
bsd-3-clause
333
# -*- coding: utf-8 -*- import os CODE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) def get_permdir(): return os.path.join(CODE_DIR, 'permdir') def get_repo_root(): return get_permdir() def get_tmpdir(): return os.path.join(CODE_DIR, 'tmpdir') def init_permdir(): path = get_permdir() if not os.path.exists(path): os.makedirs(path) init_permdir()
douban/code
vilya/libs/permdir.py
Python
bsd-3-clause
407
from social_core.backends.upwork import UpworkOAuth
cjltsod/python-social-auth
social/backends/upwork.py
Python
bsd-3-clause
52
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/geolocation_permission_context.h" #include <set> #include <string> #include <utility> #include "base/bind.h" #include "base/command_line.h" #include "base/containers/hash_tables.h" #include "base/id_map.h" #include "base/memory/scoped_vector.h" #include "base/synchronization/waitable_event.h" #include "base/test/simple_test_clock.h" #include "base/time/clock.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/tab_specific_content_settings.h" #include "chrome/browser/geolocation/geolocation_permission_context_factory.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/browser/ui/website_settings/mock_permission_bubble_view.h" #include "chrome/browser/ui/website_settings/permission_bubble_manager.h" #include "chrome/browser/ui/website_settings/permission_bubble_request.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/permission_request_id.h" #include "components/infobars/core/confirm_infobar_delegate.h" #include "components/infobars/core/infobar.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_renderer_host.h" #include "content/public/test/test_utils.h" #include "content/public/test/web_contents_tester.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_ANDROID) #include "base/prefs/pref_service.h" #include "chrome/browser/android/mock_location_settings.h" #include "chrome/browser/geolocation/geolocation_permission_context_android.h" #endif #if defined(ENABLE_EXTENSIONS) #include "extensions/browser/view_type_utils.h" #endif using content::MockRenderProcessHost; // ClosedInfoBarTracker ------------------------------------------------------- // We need to track which infobars were closed. class ClosedInfoBarTracker : public content::NotificationObserver { public: ClosedInfoBarTracker(); ~ClosedInfoBarTracker() override; // content::NotificationObserver: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; size_t size() const { return removed_infobars_.size(); } bool Contains(infobars::InfoBar* infobar) const; void Clear(); private: FRIEND_TEST_ALL_PREFIXES(GeolocationPermissionContextTests, TabDestroyed); content::NotificationRegistrar registrar_; std::set<infobars::InfoBar*> removed_infobars_; }; ClosedInfoBarTracker::ClosedInfoBarTracker() { registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED, content::NotificationService::AllSources()); } ClosedInfoBarTracker::~ClosedInfoBarTracker() { } void ClosedInfoBarTracker::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK(type == chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_REMOVED); removed_infobars_.insert( content::Details<infobars::InfoBar::RemovedDetails>(details)->first); } bool ClosedInfoBarTracker::Contains(infobars::InfoBar* infobar) const { return removed_infobars_.count(infobar) != 0; } void ClosedInfoBarTracker::Clear() { removed_infobars_.clear(); } // GeolocationPermissionContextTests ------------------------------------------ class GeolocationPermissionContextTests : public ChromeRenderViewHostTestHarness { protected: // ChromeRenderViewHostTestHarness: void SetUp() override; void TearDown() override; PermissionRequestID RequestID(int bridge_id); PermissionRequestID RequestIDForTab(int tab, int bridge_id); InfoBarService* infobar_service() { return InfoBarService::FromWebContents(web_contents()); } InfoBarService* infobar_service_for_tab(int tab) { return InfoBarService::FromWebContents(extra_tabs_[tab]); } void RequestGeolocationPermission(content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture); void PermissionResponse(const PermissionRequestID& id, ContentSetting content_setting); void CheckPermissionMessageSent(int bridge_id, bool allowed); void CheckPermissionMessageSentForTab(int tab, int bridge_id, bool allowed); void CheckPermissionMessageSentInternal(MockRenderProcessHost* process, int bridge_id, bool allowed); void AddNewTab(const GURL& url); void CheckTabContentsState(const GURL& requesting_frame, ContentSetting expected_content_setting); size_t GetBubblesQueueSize(PermissionBubbleManager* manager); void AcceptBubble(PermissionBubbleManager* manager); void DenyBubble(PermissionBubbleManager* manager); void CloseBubble(PermissionBubbleManager* manager); void BubbleManagerDocumentLoadCompleted(); void BubbleManagerDocumentLoadCompleted(content::WebContents* web_contents); ContentSetting GetGeolocationContentSetting(GURL frame_0, GURL frame_1); // owned by the browser context GeolocationPermissionContext* geolocation_permission_context_; ClosedInfoBarTracker closed_infobar_tracker_; MockPermissionBubbleView bubble_view_; ScopedVector<content::WebContents> extra_tabs_; // A map between renderer child id and a pair represending the bridge id and // whether the requested permission was allowed. base::hash_map<int, std::pair<int, bool> > responses_; }; PermissionRequestID GeolocationPermissionContextTests::RequestID( int bridge_id) { return PermissionRequestID( web_contents()->GetRenderProcessHost()->GetID(), web_contents()->GetRenderViewHost()->GetRoutingID(), bridge_id, GURL()); } PermissionRequestID GeolocationPermissionContextTests::RequestIDForTab( int tab, int bridge_id) { return PermissionRequestID( extra_tabs_[tab]->GetRenderProcessHost()->GetID(), extra_tabs_[tab]->GetRenderViewHost()->GetRoutingID(), bridge_id, GURL()); } void GeolocationPermissionContextTests::RequestGeolocationPermission( content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, bool user_gesture) { geolocation_permission_context_->RequestPermission( web_contents, id, requesting_frame, user_gesture, base::Bind(&GeolocationPermissionContextTests::PermissionResponse, base::Unretained(this), id)); content::RunAllBlockingPoolTasksUntilIdle(); } void GeolocationPermissionContextTests::PermissionResponse( const PermissionRequestID& id, ContentSetting content_setting) { responses_[id.render_process_id()] = std::make_pair(id.bridge_id(), content_setting == CONTENT_SETTING_ALLOW); } void GeolocationPermissionContextTests::CheckPermissionMessageSent( int bridge_id, bool allowed) { CheckPermissionMessageSentInternal(process(), bridge_id, allowed); } void GeolocationPermissionContextTests::CheckPermissionMessageSentForTab( int tab, int bridge_id, bool allowed) { CheckPermissionMessageSentInternal(static_cast<MockRenderProcessHost*>( extra_tabs_[tab]->GetRenderProcessHost()), bridge_id, allowed); } void GeolocationPermissionContextTests::CheckPermissionMessageSentInternal( MockRenderProcessHost* process, int bridge_id, bool allowed) { ASSERT_EQ(responses_.count(process->GetID()), 1U); EXPECT_EQ(bridge_id, responses_[process->GetID()].first); EXPECT_EQ(allowed, responses_[process->GetID()].second); responses_.erase(process->GetID()); } void GeolocationPermissionContextTests::AddNewTab(const GURL& url) { content::WebContents* new_tab = CreateTestWebContents(); new_tab->GetController().LoadURL( url, content::Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); content::RenderFrameHostTester::For(new_tab->GetMainFrame()) ->SendNavigate(extra_tabs_.size() + 1, url); // Set up required helpers, and make this be as "tabby" as the code requires. #if defined(ENABLE_EXTENSIONS) extensions::SetViewType(new_tab, extensions::VIEW_TYPE_TAB_CONTENTS); #endif InfoBarService::CreateForWebContents(new_tab); PermissionBubbleManager::CreateForWebContents(new_tab); PermissionBubbleManager::FromWebContents(new_tab)->SetView(&bubble_view_); extra_tabs_.push_back(new_tab); } void GeolocationPermissionContextTests::CheckTabContentsState( const GURL& requesting_frame, ContentSetting expected_content_setting) { TabSpecificContentSettings* content_settings = TabSpecificContentSettings::FromWebContents(web_contents()); const ContentSettingsUsagesState::StateMap& state_map = content_settings->geolocation_usages_state().state_map(); EXPECT_EQ(1U, state_map.count(requesting_frame.GetOrigin())); EXPECT_EQ(0U, state_map.count(requesting_frame)); ContentSettingsUsagesState::StateMap::const_iterator settings = state_map.find(requesting_frame.GetOrigin()); ASSERT_FALSE(settings == state_map.end()) << "geolocation state not found " << requesting_frame; EXPECT_EQ(expected_content_setting, settings->second); } void GeolocationPermissionContextTests::SetUp() { ChromeRenderViewHostTestHarness::SetUp(); // Set up required helpers, and make this be as "tabby" as the code requires. #if defined(ENABLE_EXTENSIONS) extensions::SetViewType(web_contents(), extensions::VIEW_TYPE_TAB_CONTENTS); #endif InfoBarService::CreateForWebContents(web_contents()); TabSpecificContentSettings::CreateForWebContents(web_contents()); geolocation_permission_context_ = GeolocationPermissionContextFactory::GetForProfile(profile()); #if defined(OS_ANDROID) static_cast<GeolocationPermissionContextAndroid*>( geolocation_permission_context_) ->SetLocationSettingsForTesting( scoped_ptr<LocationSettings>(new MockLocationSettings())); MockLocationSettings::SetLocationStatus(true, true); #endif PermissionBubbleManager::CreateForWebContents(web_contents()); PermissionBubbleManager::FromWebContents(web_contents())->SetView( &bubble_view_); } void GeolocationPermissionContextTests::TearDown() { extra_tabs_.clear(); ChromeRenderViewHostTestHarness::TearDown(); } size_t GeolocationPermissionContextTests::GetBubblesQueueSize( PermissionBubbleManager* manager) { return manager->requests_.size(); } void GeolocationPermissionContextTests::AcceptBubble( PermissionBubbleManager* manager) { manager->Accept(); } void GeolocationPermissionContextTests::DenyBubble( PermissionBubbleManager* manager) { manager->Deny(); } void GeolocationPermissionContextTests::CloseBubble( PermissionBubbleManager* manager) { manager->Closing(); } void GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted() { GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted( web_contents()); } void GeolocationPermissionContextTests::BubbleManagerDocumentLoadCompleted( content::WebContents* web_contents) { PermissionBubbleManager::FromWebContents(web_contents)-> DocumentOnLoadCompletedInMainFrame(); } ContentSetting GeolocationPermissionContextTests::GetGeolocationContentSetting( GURL frame_0, GURL frame_1) { return profile()->GetHostContentSettingsMap()->GetContentSetting( frame_0, frame_1, CONTENT_SETTINGS_TYPE_GEOLOCATION, std::string()); } // Needed to parameterize the tests for both infobars & permission bubbles. class GeolocationPermissionContextParamTests : public GeolocationPermissionContextTests, public ::testing::WithParamInterface<bool> { protected: GeolocationPermissionContextParamTests() {} ~GeolocationPermissionContextParamTests() override {} bool BubbleEnabled() const { #if defined (OS_ANDROID) return false; #else return GetParam(); #endif } void SetUp() override { GeolocationPermissionContextTests::SetUp(); #if !defined(OS_ANDROID) if (BubbleEnabled()) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnablePermissionsBubbles); EXPECT_TRUE(PermissionBubbleManager::Enabled()); } else { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kDisablePermissionsBubbles); EXPECT_FALSE(PermissionBubbleManager::Enabled()); } #endif } size_t GetNumberOfPrompts() { if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); return GetBubblesQueueSize(manager); } else { return infobar_service()->infobar_count(); } } void AcceptPrompt() { if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); AcceptBubble(manager); } else { infobars::InfoBar* infobar = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate = infobar->delegate()->AsConfirmInfoBarDelegate(); infobar_delegate->Accept(); } } base::string16 GetPromptText() { if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); return manager->requests_.front()->GetMessageText(); } infobars::InfoBar* infobar = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate = infobar->delegate()->AsConfirmInfoBarDelegate(); return infobar_delegate->GetMessageText(); } private: DISALLOW_COPY_AND_ASSIGN(GeolocationPermissionContextParamTests); }; // Tests ---------------------------------------------------------------------- TEST_P(GeolocationPermissionContextParamTests, SinglePermissionInfobar) { if (BubbleEnabled()) return; GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); ASSERT_EQ(1U, infobar_service()->infobar_count()); infobars::InfoBar* infobar = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate = infobar->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate); infobar_delegate->Cancel(); infobar_service()->RemoveInfoBar(infobar); EXPECT_EQ(1U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar)); } TEST_P(GeolocationPermissionContextParamTests, SinglePermissionBubble) { if (!BubbleEnabled()) return; GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); BubbleManagerDocumentLoadCompleted(); EXPECT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); ASSERT_EQ(1U, GetNumberOfPrompts()); } #if defined(OS_ANDROID) // Infobar-only tests; Android doesn't support permission bubbles. TEST_F(GeolocationPermissionContextTests, GeolocationEnabledDisabled) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); MockLocationSettings::SetLocationStatus(true, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(1U, infobar_service()->infobar_count()); ConfirmInfoBarDelegate* infobar_delegate_0 = infobar_service()->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_0); base::string16 text_0 = infobar_delegate_0->GetButtonLabel( ConfirmInfoBarDelegate::BUTTON_OK); Reload(); MockLocationSettings::SetLocationStatus(true, false); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); } TEST_F(GeolocationPermissionContextTests, MasterEnabledGoogleAppsEnabled) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); MockLocationSettings::SetLocationStatus(true, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(1U, infobar_service()->infobar_count()); ConfirmInfoBarDelegate* infobar_delegate = infobar_service()->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate); infobar_delegate->Accept(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); } TEST_F(GeolocationPermissionContextTests, MasterEnabledGoogleAppsDisabled) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); MockLocationSettings::SetLocationStatus(true, false); EXPECT_EQ(0U, infobar_service()->infobar_count()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(0U, infobar_service()->infobar_count()); } #endif TEST_P(GeolocationPermissionContextParamTests, QueuedPermission) { GURL requesting_frame_0("http://www.example.com/geolocation"); GURL requesting_frame_1("http://www.example-2.com/geolocation"); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_1)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_1)); NavigateAndCommit(requesting_frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Check that no permission requests have happened yet. EXPECT_EQ(0U, GetNumberOfPrompts()); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, true); RequestGeolocationPermission( web_contents(), RequestID(1), requesting_frame_1, true); // Ensure only one infobar is created. ASSERT_EQ(1U, GetNumberOfPrompts()); base::string16 text_0 = GetPromptText(); // Accept the first frame. AcceptPrompt(); CheckTabContentsState(requesting_frame_0, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); if (!BubbleEnabled()) { infobars::InfoBar* infobar_0 = infobar_service()->infobar_at(0); infobar_service()->RemoveInfoBar(infobar_0); EXPECT_EQ(1U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_0)); closed_infobar_tracker_.Clear(); } // Now we should have a new infobar for the second frame. ASSERT_EQ(1U, GetNumberOfPrompts()); base::string16 text_1 = GetPromptText(); // Check that the messages differ. EXPECT_NE(text_0, text_1); // Cancel (block) this frame. if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); DenyBubble(manager); } else { infobars::InfoBar* infobar_1 = infobar_service()->infobar_at(0); infobar_1->delegate()->AsConfirmInfoBarDelegate()->Cancel(); } CheckTabContentsState(requesting_frame_1, CONTENT_SETTING_BLOCK); CheckPermissionMessageSent(1, false); // Ensure the persisted permissions are ok. EXPECT_EQ( CONTENT_SETTING_ALLOW, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0)); EXPECT_EQ( CONTENT_SETTING_BLOCK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0)); } TEST_P(GeolocationPermissionContextParamTests, HashIsIgnored) { GURL url_a("http://www.example.com/geolocation#a"); GURL url_b("http://www.example.com/geolocation#b"); // Navigate to the first url. NavigateAndCommit(url_a); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Check permission is requested. ASSERT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), url_a, BubbleEnabled()); ASSERT_EQ(1U, GetNumberOfPrompts()); // Change the hash, we'll still be on the same page. NavigateAndCommit(url_b); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Accept. AcceptPrompt(); CheckTabContentsState(url_a, CONTENT_SETTING_ALLOW); CheckTabContentsState(url_b, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Cleanup. if (!BubbleEnabled()) { infobars::InfoBar* infobar = infobar_service()->infobar_at(0); infobar_service()->RemoveInfoBar(infobar); EXPECT_EQ(1U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar)); } } TEST_P(GeolocationPermissionContextParamTests, PermissionForFileScheme) { // TODO(felt): The bubble is rejecting file:// permission requests. // Fix and enable this test. crbug.com/444047 if (BubbleEnabled()) return; GURL requesting_frame("file://example/geolocation.html"); NavigateAndCommit(requesting_frame); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Check permission is requested. ASSERT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(1U, GetNumberOfPrompts()); // Accept the frame. AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Make sure the setting is not stored. EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame, requesting_frame)); } TEST_P(GeolocationPermissionContextParamTests, CancelGeolocationPermissionRequest) { GURL frame_0("http://www.example.com/geolocation"); GURL frame_1("http://www.example-2.com/geolocation"); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_0, frame_0)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_1, frame_0)); NavigateAndCommit(frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); ASSERT_EQ(0U, GetNumberOfPrompts()); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), frame_0, true); RequestGeolocationPermission( web_contents(), RequestID(1), frame_1, true); // Get the first permission request text. ASSERT_EQ(1U, GetNumberOfPrompts()); base::string16 text_0 = GetPromptText(); ASSERT_FALSE(text_0.empty()); // Simulate the frame going away; the request should be removed. if (BubbleEnabled()) { PermissionBubbleManager* manager = PermissionBubbleManager::FromWebContents(web_contents()); CloseBubble(manager); } else { geolocation_permission_context_->CancelPermissionRequest(web_contents(), RequestID(0)); } // Check that the next pending request is created correctly. base::string16 text_1 = GetPromptText(); EXPECT_NE(text_0, text_1); // Allow this frame and check that it worked. AcceptPrompt(); CheckTabContentsState(frame_1, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(1, true); // Ensure the persisted permissions are ok. EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(frame_0, frame_0)); EXPECT_EQ( CONTENT_SETTING_ALLOW, GetGeolocationContentSetting(frame_1, frame_0)); } TEST_P(GeolocationPermissionContextParamTests, InvalidURL) { // Navigate to the first url. GURL invalid_embedder("about:blank"); GURL requesting_frame; NavigateAndCommit(invalid_embedder); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Nothing should be displayed. EXPECT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, true); EXPECT_EQ(0U, GetNumberOfPrompts()); CheckPermissionMessageSent(0, false); } TEST_P(GeolocationPermissionContextParamTests, SameOriginMultipleTabs) { GURL url_a("http://www.example.com/geolocation"); GURL url_b("http://www.example-2.com/geolocation"); NavigateAndCommit(url_a); // Tab A0 AddNewTab(url_b); // Tab B (extra_tabs_[0]) AddNewTab(url_a); // Tab A1 (extra_tabs_[1]) if (BubbleEnabled()) { BubbleManagerDocumentLoadCompleted(); BubbleManagerDocumentLoadCompleted(extra_tabs_[0]); BubbleManagerDocumentLoadCompleted(extra_tabs_[1]); } PermissionBubbleManager* manager_a0 = PermissionBubbleManager::FromWebContents(web_contents()); PermissionBubbleManager* manager_b = PermissionBubbleManager::FromWebContents(extra_tabs_[0]); PermissionBubbleManager* manager_a1 = PermissionBubbleManager::FromWebContents(extra_tabs_[1]); // Request permission in all three tabs. RequestGeolocationPermission( web_contents(), RequestID(0), url_a, true); RequestGeolocationPermission( extra_tabs_[0], RequestIDForTab(0, 0), url_b, true); RequestGeolocationPermission( extra_tabs_[1], RequestIDForTab(1, 0), url_a, true); ASSERT_EQ(1U, GetNumberOfPrompts()); // For A0. if (BubbleEnabled()) { ASSERT_EQ(1U, GetBubblesQueueSize(manager_b)); ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); } else { ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); ASSERT_EQ(1U, infobar_service_for_tab(1)->infobar_count()); } // Accept the permission in tab A0. if (BubbleEnabled()) { AcceptBubble(manager_a0); } else { infobars::InfoBar* infobar_a0 = infobar_service()->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate_a0 = infobar_a0->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_a0); infobar_delegate_a0->Accept(); infobar_service()->RemoveInfoBar(infobar_a0); EXPECT_EQ(2U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_a0)); } CheckPermissionMessageSent(0, true); // Because they're the same origin, this will cause tab A1's infobar to // disappear. It does not cause the bubble to disappear: crbug.com/443013. // TODO(felt): Update this test when the bubble's behavior is changed. if (BubbleEnabled()) ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); else CheckPermissionMessageSentForTab(1, 0, true); // Either way, tab B should still have a pending permission request. if (BubbleEnabled()) ASSERT_EQ(1U, GetBubblesQueueSize(manager_b)); else ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); } TEST_P(GeolocationPermissionContextParamTests, QueuedOriginMultipleTabs) { GURL url_a("http://www.example.com/geolocation"); GURL url_b("http://www.example-2.com/geolocation"); NavigateAndCommit(url_a); // Tab A0. AddNewTab(url_a); // Tab A1. if (BubbleEnabled()) { BubbleManagerDocumentLoadCompleted(); BubbleManagerDocumentLoadCompleted(extra_tabs_[0]); } PermissionBubbleManager* manager_a0 = PermissionBubbleManager::FromWebContents(web_contents()); PermissionBubbleManager* manager_a1 = PermissionBubbleManager::FromWebContents(extra_tabs_[0]); // Request permission in both tabs; the extra tab will have two permission // requests from two origins. RequestGeolocationPermission( web_contents(), RequestID(0), url_a, true); RequestGeolocationPermission( extra_tabs_[0], RequestIDForTab(0, 0), url_a, true); RequestGeolocationPermission( extra_tabs_[0], RequestIDForTab(0, 1), url_b, true); if (BubbleEnabled()) { ASSERT_EQ(1U, GetBubblesQueueSize(manager_a0)); ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); } else { ASSERT_EQ(1U, infobar_service()->infobar_count()); ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); } // Accept the first request in tab A1. if (BubbleEnabled()) { AcceptBubble(manager_a1); } else { infobars::InfoBar* infobar_a1 = infobar_service_for_tab(0)->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate_a1 = infobar_a1->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_a1); infobar_delegate_a1->Accept(); infobar_service_for_tab(0)->RemoveInfoBar(infobar_a1); EXPECT_EQ(2U, closed_infobar_tracker_.size()); EXPECT_TRUE(closed_infobar_tracker_.Contains(infobar_a1)); } CheckPermissionMessageSentForTab(0, 0, true); // Because they're the same origin, this will cause tab A0's infobar to // disappear. It does not cause the bubble to disappear: crbug.com/443013. // TODO(felt): Update this test when the bubble's behavior is changed. if (BubbleEnabled()) { EXPECT_EQ(1U, GetBubblesQueueSize(manager_a0)); } else { EXPECT_EQ(0U, infobar_service()->infobar_count()); CheckPermissionMessageSent(0, true); } // The second request should now be visible in tab A1. if (BubbleEnabled()) ASSERT_EQ(1U, GetBubblesQueueSize(manager_a1)); else ASSERT_EQ(1U, infobar_service_for_tab(0)->infobar_count()); // Accept the second request and check that it's gone. if (BubbleEnabled()) { AcceptBubble(manager_a1); EXPECT_EQ(0U, GetBubblesQueueSize(manager_a1)); } else { infobars::InfoBar* infobar_1 = infobar_service_for_tab(0)->infobar_at(0); ConfirmInfoBarDelegate* infobar_delegate_1 = infobar_1->delegate()->AsConfirmInfoBarDelegate(); ASSERT_TRUE(infobar_delegate_1); infobar_delegate_1->Accept(); } } TEST_P(GeolocationPermissionContextParamTests, TabDestroyed) { GURL requesting_frame_0("http://www.example.com/geolocation"); GURL requesting_frame_1("http://www.example-2.com/geolocation"); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0)); NavigateAndCommit(requesting_frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, false); RequestGeolocationPermission( web_contents(), RequestID(1), requesting_frame_1, false); // Ensure only one prompt is created. ASSERT_EQ(1U, GetNumberOfPrompts()); // Delete the tab contents. if (!BubbleEnabled()) { infobars::InfoBar* infobar = infobar_service()->infobar_at(0); DeleteContents(); ASSERT_EQ(1U, closed_infobar_tracker_.size()); ASSERT_TRUE(closed_infobar_tracker_.Contains(infobar)); } // The content settings should not have changed. EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_0, requesting_frame_0)); EXPECT_EQ( CONTENT_SETTING_ASK, GetGeolocationContentSetting(requesting_frame_1, requesting_frame_0)); } TEST_P(GeolocationPermissionContextParamTests, LastUsageAudited) { GURL requesting_frame("http://www.example.com/geolocation"); NavigateAndCommit(requesting_frame); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); base::SimpleTestClock* test_clock = new base::SimpleTestClock; test_clock->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10)); HostContentSettingsMap* map = profile()->GetHostContentSettingsMap(); map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock)); // The permission shouldn't have been used yet. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), requesting_frame.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); ASSERT_EQ(0U, GetNumberOfPrompts()); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, false); ASSERT_EQ(1U, GetNumberOfPrompts()); AcceptPrompt(); CheckTabContentsState(requesting_frame, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Permission has been used at the starting time. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), requesting_frame.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 10); test_clock->Advance(base::TimeDelta::FromSeconds(3)); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame, false); // Permission has been used three seconds later. EXPECT_EQ(map->GetLastUsage(requesting_frame.GetOrigin(), requesting_frame.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 13); } TEST_P(GeolocationPermissionContextParamTests, LastUsageAuditedMultipleFrames) { base::SimpleTestClock* test_clock = new base::SimpleTestClock; test_clock->SetNow(base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(10)); HostContentSettingsMap* map = profile()->GetHostContentSettingsMap(); map->SetPrefClockForTesting(scoped_ptr<base::Clock>(test_clock)); GURL requesting_frame_0("http://www.example.com/geolocation"); GURL requesting_frame_1("http://www.example-2.com/geolocation"); // The permission shouldn't have been used yet. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); NavigateAndCommit(requesting_frame_0); if (BubbleEnabled()) BubbleManagerDocumentLoadCompleted(); EXPECT_EQ(0U, GetNumberOfPrompts()); // Request permission for two frames. RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, false); RequestGeolocationPermission( web_contents(), RequestID(1), requesting_frame_1, false); // Ensure only one infobar is created. ASSERT_EQ(1U, GetNumberOfPrompts()); // Accept the first frame. AcceptPrompt(); if (!BubbleEnabled()) infobar_service()->RemoveInfoBar(infobar_service()->infobar_at(0)); CheckTabContentsState(requesting_frame_0, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(0, true); // Verify that accepting the first didn't accept because it's embedded // in the other. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 10); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 0); ASSERT_EQ(1U, GetNumberOfPrompts()); test_clock->Advance(base::TimeDelta::FromSeconds(1)); // Allow the second frame. AcceptPrompt(); CheckTabContentsState(requesting_frame_1, CONTENT_SETTING_ALLOW); CheckPermissionMessageSent(1, true); if (!BubbleEnabled()) infobar_service()->RemoveInfoBar(infobar_service()->infobar_at(0)); // Verify that the times are different. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 10); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 11); test_clock->Advance(base::TimeDelta::FromSeconds(2)); RequestGeolocationPermission( web_contents(), RequestID(0), requesting_frame_0, false); // Verify that requesting permission in one frame doesn't update other where // it is the embedder. EXPECT_EQ(map->GetLastUsage(requesting_frame_0.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 13); EXPECT_EQ(map->GetLastUsage(requesting_frame_1.GetOrigin(), requesting_frame_0.GetOrigin(), CONTENT_SETTINGS_TYPE_GEOLOCATION).ToDoubleT(), 11); } INSTANTIATE_TEST_CASE_P(GeolocationPermissionContextTestsWithAndWithoutBubbles, GeolocationPermissionContextParamTests, ::testing::Values(false, true));
sgraham/nope
chrome/browser/geolocation/geolocation_permission_context_unittest.cc
C++
bsd-3-clause
37,152
package org.buildmlearn.toolkit.fragment; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.buildmlearn.toolkit.R; import org.buildmlearn.toolkit.activity.TemplateActivity; /** * @brief Fragment displayed on the home screen. */ public class HomeFragment extends Fragment { /** * {@inheritDoc} */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); view.findViewById(R.id.button_template).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), TemplateActivity.class)); } }); return view; } }
vishwesh3/BuildmLearn-Toolkit-Android
source-code/app/src/main/java/org/buildmlearn/toolkit/fragment/HomeFragment.java
Java
bsd-3-clause
1,033
package gforms // Generate password input field: <input type="password" ...> func PasswordInputWidget(attrs map[string]string) Widget { w := new(textInputWidget) w.Type = "password" if attrs == nil { attrs = map[string]string{} } w.Attrs = attrs return w }
gernest/gforms
passwordinputwidget.go
GO
mit
266
var http = require("http"); var url = require("url"); var server; // Diese Funktion reagiert auf HTTP Requests, // hier wird also die Web Anwendung implementiert! var simpleHTTPResponder = function(req, res) { // Routing bedeutet, anhand der URL Adresse // unterschiedliche Funktionen zu steuern. // Dazu wird zunächst die URL Adresse benötigt var url_parts = url.parse(req.url, true); // Nun erfolgt die Fallunterscheidung, // hier anhand des URL Pfads if (url_parts.pathname == "/greetme") { // HTTP Header müssen gesetzt werden res.writeHead(200, { "Content-Type": "text/html" }); // Auch URL Query Parameter können abgefragt werden var query = url_parts.query; var name = "Anonymous"; if (query["name"] != undefined) { name = query["name"]; } // HTML im Script zu erzeugen ist mühselig... res.end("<html><head><title>Greetme</title></head><body><H1>Greetings " + name + "!</H1></body></html>"); // nun folgt der zweite Fall... } else { res.writeHead(404, { "Content-Type": "text/html" }); res.end( "<html><head><title>Error</title></head><body><H1>Only /greetme is implemented.</H1></body></html>" ); } } // Webserver erzeugen, an Endpunkt binden und starten server = http.createServer(simpleHTTPResponder); var port = process.argv[2]; server.listen(port);
MaximilianKucher/vs1Lab
Beispiele/nodejs_webserver/web.js
JavaScript
mit
1,328
package engine.menu.managers; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.util.List; import engine.dialogue.InteractionBox; import engine.gridobject.person.Player; import engine.images.ScaledImage; import engine.item.Weapon; import engine.menu.MenuInteractionMatrix; import engine.menu.nodes.WeaponInfoNode; public class WeaponManager extends MenuManager implements InteractionBox { private Player myPlayer; private MenuInteractionMatrix myMIM; private MenuManager myMenuManager; public WeaponManager(Player p, MenuManager mm, MenuInteractionMatrix mim) { super(p, null, mim); myPlayer = p; myMIM = mim; myMenuManager = mm; } @Override public void paintDisplay(Graphics2D g2d, int xSize, int ySize, int width, int height) { paintMenu(g2d, height, width); paintFeatureBox(g2d, "ImageFiles/PokemonBox.png", 17, 20, 300, 200); paintWeaponData(g2d); drawSelector(g2d, 198, 40, 280, 45, 44, myMIM); } @Override public void getNextText() { // TODO Auto-generated method stub } protected void paintFeatureBox(Graphics g2d, String imgPath, int x, int y, int width, int height) { Image img = new ScaledImage(width, height, imgPath).scaleImage(); g2d.drawImage(img, x, y, null); } protected void paintFeatureImage(Graphics g2d, Image feature, int x, int y) { g2d.drawImage(feature, x, y, null); } protected void paintFeatureName(Graphics g2d, String name, int x, int y) { g2d.drawString(name, x, y); } private void paintWeaponData(Graphics g2d) { List<Weapon> features = myPlayer.getWeaponList(); int emptySpace = 0; for (int i = 0; i < features.size(); i++) { if (i != 0) { emptySpace = 1; } else { emptySpace = 0; } Image scaledWeaponImage = features.get(i).getImage() .getScaledInstance(35, 35, Image.SCALE_SMOOTH); paintFeatureImage(g2d, scaledWeaponImage, 37, 45 + i * 40 + 5 * emptySpace); paintFeatureName(g2d, features.get(i).toString(), 80, 67 + i * 40 + 5 * emptySpace); } } public void createWeaponInfoNodes() { for (int i = 0; i < myPlayer.getWeaponList().size(); i++) { myMIM.setNode(new WeaponInfoNode(myPlayer, this, myMenuManager, i), 0, i); } } }
yomikaze/OOGASalad
src/engine/menu/managers/WeaponManager.java
Java
mit
2,233
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp), Shared] internal class UsingStatementHighlighter : AbstractKeywordHighlighter<UsingStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UsingStatementHighlighter() { } protected override void AddHighlights(UsingStatementSyntax usingStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(usingStatement.UsingKeyword.Span); } }
mavasani/roslyn
src/Features/CSharp/Portable/Highlighting/KeywordHighlighters/UsingStatementHighlighter.cs
C#
mit
1,116
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; using Microsoft.VisualStudio.LanguageServices.Telemetry; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class VisualStudioWorkspace_OutOfProc : OutOfProcComponent { private readonly VisualStudioWorkspace_InProc _inProc; internal VisualStudioWorkspace_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _inProc = CreateInProcComponent<VisualStudioWorkspace_InProc>(visualStudioInstance); } public void SetOptionInfer(string projectName, bool value) { _inProc.SetOptionInfer(projectName, value); WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); } public bool IsPrettyListingOn(string languageName) => _inProc.IsPrettyListingOn(languageName); public void SetPrettyListing(string languageName, bool value) => _inProc.SetPrettyListing(languageName, value); public void SetPerLanguageOption(string optionName, string feature, string language, object value) => _inProc.SetPerLanguageOption(optionName, feature, language, value); public void SetOption(string optionName, string feature, object value) => _inProc.SetOption(optionName, feature, value); public void WaitForAsyncOperations(TimeSpan timeout, string featuresToWaitFor, bool waitForWorkspaceFirst = true) => _inProc.WaitForAsyncOperations(timeout, featuresToWaitFor, waitForWorkspaceFirst); public void WaitForAllAsyncOperations(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperations(timeout, featureNames); public void WaitForAllAsyncOperationsOrFail(TimeSpan timeout, params string[] featureNames) => _inProc.WaitForAllAsyncOperationsOrFail(timeout, featureNames); public void CleanUpWorkspace() => _inProc.CleanUpWorkspace(); public void ResetOptions() => _inProc.ResetOptions(); public void CleanUpWaitingService() => _inProc.CleanUpWaitingService(); public void SetImportCompletionOption(bool value) { SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.CSharp, value); SetGlobalOption(WellKnownGlobalOption.CompletionOptions_ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, value); } public void SetEnableDecompilationOption(bool value) { SetOption("NavigateToDecompiledSources", "FeatureOnOffOptions", value); } public void SetArgumentCompletionSnippetsOption(bool value) { SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.CSharp, value); SetGlobalOption(WellKnownGlobalOption.CompletionViewOptions_EnableArgumentCompletionSnippets, LanguageNames.VisualBasic, value); } public void SetTriggerCompletionInArgumentLists(bool value) => SetGlobalOption(WellKnownGlobalOption.CompletionOptions_TriggerInArgumentLists, LanguageNames.CSharp, value); public void SetFullSolutionAnalysis(bool value) { SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.CSharp, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); SetPerLanguageOption( optionName: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Name, feature: SolutionCrawlerOptions.BackgroundAnalysisScopeOption.Feature, language: LanguageNames.VisualBasic, value: value ? BackgroundAnalysisScope.FullSolution : BackgroundAnalysisScope.Default); } public void SetFileScopedNamespaces(bool value) => _inProc.SetFileScopedNamespaces(value); public void SetEnableOpeningSourceGeneratedFilesInWorkspaceExperiment(bool value) { SetGlobalOption( WellKnownGlobalOption.VisualStudioSyntaxTreeConfigurationService_EnableOpeningSourceGeneratedFilesInWorkspace, language: null, value); } public void SetFeatureOption(string feature, string optionName, string? language, string? valueString) => _inProc.SetFeatureOption(feature, optionName, language, valueString); public void SetGlobalOption(WellKnownGlobalOption option, string? language, object? value) => _inProc.SetGlobalOption(option, language, value); } }
CyrusNajmabadi/roslyn
src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/VisualStudioWorkspace_OutOfProc.cs
C#
mit
5,369
<?php namespace SMW\Tests\SPARQLStore; use SMW\SPARQLStore\RedirectLookup; use SMW\InMemoryPoolCache; use SMW\DIWikiPage; use SMW\DIProperty; use SMW\Exporter\Escaper; use SMWExpNsResource as ExpNsResource; use SMWExpLiteral as ExpLiteral; use SMWExpResource as ExpResource; use SMWExporter as Exporter; /** * @covers \SMW\SPARQLStore\RedirectLookup * @group semantic-mediawiki * * @license GNU GPL v2+ * @since 2.0 * * @author mwjames */ class RedirectLookupTest extends \PHPUnit_Framework_TestCase { public function testCanConstruct() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $this->assertInstanceOf( '\SMW\SPARQLStore\RedirectLookup', new RedirectLookup( $repositoryConnection ) ); } public function testRedirectTragetForBlankNode() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $expNsResource = new ExpNsResource( '', '', '', null ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertFalse( $exists ); } public function testRedirectTragetForDataItemWithSubobject() { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $dataItem = new DIWikiPage( 'Foo', 1, '', 'beingASubobject' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithNoEntry() { $repositoryConnection = $this->createRepositoryConnectionMockToUse( false ); $instance = new RedirectLookup( $repositoryConnection ); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertFalse( $exists ); } public function testRedirectTragetForDBLookupWithSingleEntry() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithMultipleEntries() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, null ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->assertSame( $expNsResource, $instance->findRedirectTargetResource( $expNsResource, $exists ) ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithMultipleEntriesForcesNewResource() { $propertyPage = new DIWikiPage( 'Foo', SMW_NS_PROPERTY ); $resource = new ExpNsResource( 'Foo', Exporter::getInstance()->getNamespaceUri( 'property' ), 'property', $propertyPage ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $resource, $resource ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $targetResource = $instance->findRedirectTargetResource( $expNsResource, $exists ); $this->assertNotSame( $expNsResource, $targetResource ); $expectedResource = new ExpNsResource( Escaper::encodePage( $propertyPage ), Exporter::getInstance()->getNamespaceUri( 'wiki' ), 'wiki' ); $this->assertEquals( $expectedResource, $targetResource ); $this->assertTrue( $exists ); } public function testRedirectTragetForDBLookupWithForNonMultipleResourceEntryThrowsException() { $expLiteral = new ExpLiteral( 'Redirect' ); $repositoryConnection = $this->createRepositoryConnectionMockToUse( array( $expLiteral, $expLiteral ) ); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $dataItem = new DIWikiPage( 'Foo', 1, '', '' ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $exists = null; $this->setExpectedException( 'RuntimeException' ); $instance->findRedirectTargetResource( $expNsResource, $exists ); } public function testRedirectTargetForCachedLookup() { $dataItem = new DIWikiPage( 'Foo', NS_MAIN ); $expNsResource = new ExpNsResource( 'Foo', 'Bar', '', $dataItem ); $poolCache = InMemoryPoolCache::getInstance()->getPoolCacheFor( 'sparql.store.redirectlookup' ); $poolCache->save( $expNsResource->getUri(), $expNsResource ); $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $exists = null; $instance->findRedirectTargetResource( $expNsResource, $exists ); $this->assertTrue( $exists ); $instance->reset(); } /** * @dataProvider nonRedirectableResourceProvider */ public function testRedirectTargetForNonRedirectableResource( $expNsResource ) { $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $instance = new RedirectLookup( $repositoryConnection ); $instance->reset(); $exists = null; $instance->findRedirectTargetResource( $expNsResource, $exists ); $instance->reset(); $this->assertFalse( $exists ); } private function createRepositoryConnectionMockToUse( $listReturnValue ) { $repositoryResult = $this->getMockBuilder( '\SMW\SPARQLStore\QueryEngine\RepositoryResult' ) ->disableOriginalConstructor() ->getMock(); $repositoryResult->expects( $this->once() ) ->method( 'current' ) ->will( $this->returnValue( $listReturnValue ) ); $repositoryConnection = $this->getMockBuilder( '\SMW\SPARQLStore\RepositoryConnection' ) ->disableOriginalConstructor() ->getMock(); $repositoryConnection->expects( $this->once() ) ->method( 'select' ) ->will( $this->returnValue( $repositoryResult ) ); return $repositoryConnection; } public function nonRedirectableResourceProvider() { $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_INST' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_SUBC' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_REDI' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_MDAT' ) ); $provider[] = array( Exporter::getInstance()->getSpecialPropertyResource( '_MDAT', true ) ); return $provider; } }
stuartbman/mediawiki-vagrant
mediawiki/extensions/SemanticMediaWiki/tests/phpunit/Unit/SPARQLStore/RedirectLookupTest.php
PHP
mit
7,584
package xpath //please check the search tests in gokogiri/xml and gokogiri/html import "testing" func TestCompileGoodExpr(t *testing.T) { defer CheckXmlMemoryLeaks(t) e := Compile(`./*`) if e == nil { t.Error("expr should be good") } e.Free() } func TestCompileBadExpr(t *testing.T) { //defer CheckXmlMemoryLeaks(t) //this test causes memory leaks in libxml //however, the memory leak is very small and does not grow as more bad expressions are compiled e := Compile("./") if e != nil { t.Error("expr should be bad") } e = Compile(".//") if e != nil { t.Error("expr should be bad") } }
jbowtie/gokogiri
xpath/xpath_test.go
GO
mit
609
module Jasminerice module ApplicationHelper end end
ajacksified/restful-clients-in-rails-demo
rack-proxy/ruby/1.9.1/gems/jasminerice-0.0.8/app/helpers/jasminerice/application_helper.rb
Ruby
mit
56
'use strict'; angular.module('sumaAnalysis') .factory('actsLocs', function () { function calculateDepthAndTooltip (item, list, root, depth) { var parent; depth = depth || {depth: 0, tooltipTitle: item.title, ancestors: []}; if (parseInt(item.parent, 10) === parseInt(root, 10)) { return depth; } parent = _.find(list, {'id': item.parent}); depth.depth += 1; depth.tooltipTitle = parent.title + ': ' + depth.tooltipTitle; depth.ancestors.push(parent.id); return calculateDepthAndTooltip(parent, list, root, depth); } function processActivities (activities, activityGroups) { var activityList = [], activityGroupsHash; // Sort activities and activity groups activities = _.sortBy(activities, 'rank'); activityGroups = _.sortBy(activityGroups, 'rank'); activityGroupsHash = _.object(_.map(activityGroups, function (aGrp) { return [aGrp.id, aGrp.title]; })); // For each activity group, build a list of activities _.each(activityGroups, function (activityGroup) { // Add activity group metadata to activityGroupList array activityList.push({ 'id' : activityGroup.id, 'rank' : activityGroup.rank, 'title' : activityGroup.title, 'type' : 'activityGroup', 'depth' : 0, 'filter' : 'allow', 'enabled': true }); // Loop over activities and add the ones belonging to the current activityGroup _.each(activities, function (activity) { if (activity.activityGroup === activityGroup.id) { // Add activities to activityList array behind proper activityGroup activityList.push({ 'id' : activity.id, 'rank' : activity.rank, 'title' : activity.title, 'type' : 'activity', 'depth' : 1, 'activityGroup' : activityGroup.id, 'activityGroupTitle': activityGroupsHash[activityGroup.id], 'tooltipTitle' : activityGroupsHash[activityGroup.id] + ': ' + activity.title, 'altName' : activityGroupsHash[activityGroup.id] + ': ' + activity.title, 'filter' : 'allow', 'enabled' : true }); } }); }); return activityList; } function processLocations (locations, root) { return _.map(locations, function (loc, index, list) { var depth = calculateDepthAndTooltip(loc, list, root); loc.depth = depth.depth; loc.tooltipTitle = depth.tooltipTitle; loc.ancestors = depth.ancestors; loc.filter = true; loc.enabled = true; return loc; }); } return { get: function (init) { return { activities: processActivities(init.dictionary.activities, init.dictionary.activityGroups), locations: processLocations(init.dictionary.locations, init.rootLocation) }; } }; });
cazzerson/Suma
analysis/src/scripts/services/actsLocs.js
JavaScript
mit
3,247
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice; import com.fasterxml.jackson.annotation.JsonProperty; /** * Actions which to take by the auto-heal module when a rule is triggered. */ public class AutoHealActions { /** * Predefined action to be taken. Possible values include: 'Recycle', * 'LogEvent', 'CustomAction'. */ @JsonProperty(value = "actionType") private AutoHealActionType actionType; /** * Custom action to be taken. */ @JsonProperty(value = "customAction") private AutoHealCustomAction customAction; /** * Minimum time the process must execute * before taking the action. */ @JsonProperty(value = "minProcessExecutionTime") private String minProcessExecutionTime; /** * Get the actionType value. * * @return the actionType value */ public AutoHealActionType actionType() { return this.actionType; } /** * Set the actionType value. * * @param actionType the actionType value to set * @return the AutoHealActions object itself. */ public AutoHealActions withActionType(AutoHealActionType actionType) { this.actionType = actionType; return this; } /** * Get the customAction value. * * @return the customAction value */ public AutoHealCustomAction customAction() { return this.customAction; } /** * Set the customAction value. * * @param customAction the customAction value to set * @return the AutoHealActions object itself. */ public AutoHealActions withCustomAction(AutoHealCustomAction customAction) { this.customAction = customAction; return this; } /** * Get the minProcessExecutionTime value. * * @return the minProcessExecutionTime value */ public String minProcessExecutionTime() { return this.minProcessExecutionTime; } /** * Set the minProcessExecutionTime value. * * @param minProcessExecutionTime the minProcessExecutionTime value to set * @return the AutoHealActions object itself. */ public AutoHealActions withMinProcessExecutionTime(String minProcessExecutionTime) { this.minProcessExecutionTime = minProcessExecutionTime; return this; } }
jianghaolu/azure-sdk-for-java
azure-mgmt-appservice/src/main/java/com/microsoft/azure/management/appservice/AutoHealActions.java
Java
mit
2,569
class ExitStatus < Spinach::FeatureSteps feature "Exit status" include Integration::SpinachRunner Given "I have a feature that has no error or failure" do @feature = Integration::FeatureGenerator.success_feature end Given "I have a feature that has a failure" do @feature = Integration::FeatureGenerator.failure_feature end When "I run it" do run_feature @feature end Then "the exit status should be 0" do @last_exit_status.success?.must_equal true end Then "the exit status should be 1" do @last_exit_status.success?.must_equal false end end
alkuzad/spinach
features/steps/exit_status.rb
Ruby
mit
594
// Generated by LiveScript 1.5.0 var onmessage, this$ = this; function addEventListener(event, cb){ return this.thread.on(event, cb); } function close(){ return this.thread.emit('close'); } function importScripts(){ var i$, len$, p, results$ = []; for (i$ = 0, len$ = (arguments).length; i$ < len$; ++i$) { p = (arguments)[i$]; results$.push(self.eval(native_fs_.readFileSync(p, 'utf8'))); } return results$; } onmessage = null; thread.on('message', function(args){ return typeof onmessage == 'function' ? onmessage(args) : void 8; });
romainmnr/chatboteseo
node_modules/webworker-threads/src/load.js
JavaScript
mit
558
package com.laytonsmith.abstraction.entities; import com.laytonsmith.abstraction.MCEntity; import com.laytonsmith.abstraction.MCLivingEntity; public interface MCEvokerFangs extends MCEntity { MCLivingEntity getOwner(); void setOwner(MCLivingEntity owner); }
sk89q/CommandHelper
src/main/java/com/laytonsmith/abstraction/entities/MCEvokerFangs.java
Java
mit
262
module.exports = { "env": { "browser": true }, "plugins": [ "callback-function" ], "globals": { "_": true, "$": true, "ActErr": true, "async": true, "config": true, "logger": true, "moment": true, "respondWithError": true, "sendJSONResponse": true, "util": true, "admiral": true }, "extends": "airbnb-base/legacy", "rules": { // rules to override from airbnb/legacy "object-curly-spacing": ["error", "never"], "curly": ["error", "multi", "consistent"], "no-param-reassign": ["error", { "props": false }], "no-underscore-dangle": ["error", { "allow": ["_r", "_p"] }], "quote-props": ["error", "consistent-as-needed"], // rules from airbnb that we won't be using "consistent-return": 0, "default-case": 0, "func-names": 0, "no-plusplus": 0, "no-use-before-define": 0, "vars-on-top": 0, "no-loop-func": 0, "no-underscore-dangle": 0, "no-param-reassign": 0, "one-var-declaration-per-line": 0, "one-var": 0, "no-multi-assign": 0, "global-require": 0, // extra rules not present in airbnb "max-len": ["error", 80], } };
himanshu0503/admiral
.eslintrc.js
JavaScript
mit
1,174
/******************************************************************************* * Copyright (c) 2014 Salesforce.com, inc.. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Salesforce.com, inc. - initial API and implementation ******************************************************************************/ package com.salesforce.ide.ui.views.log; import static org.mockito.Mockito.mock; import java.io.File; import junit.framework.TestCase; /** * Class to unit test Logview * @author bvenkatesan * */ public class LogViewTest_unit extends TestCase { public void testCheckSpaceInLogEntryBeforeParentheses() throws Exception { String mockMessage = "Unable to get component for id"; File mockFile = mock(File.class); LogEntry mockEntry = mock(LogEntry.class); String TestMessage = new LogView(mockFile).new LogViewLabelProvider().getExceptionMessage(mockMessage, mockEntry); assertTrue(TestMessage.contains(" (Open")); } }
dipakmankumbare/idecore
com.salesforce.ide.ui.test/src/com/salesforce/ide/ui/views/log/LogViewTest_unit.java
Java
epl-1.0
1,175
/******************************************************************************* * Copyright (c) 2013, 2014 UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Initial API and implementation and/or initial documentation - Jay Jay Billings, * Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson, * Claire Saunders, Matthew Wang, Anna Wojtowicz *******************************************************************************/ package org.eclipse.ice.reactor.sfr.core.assembly; import org.eclipse.ice.reactor.sfr.base.ISFRComponentVisitor; import org.eclipse.ice.reactor.sfr.base.SFRComposite; import org.eclipse.ice.reactor.sfr.core.AssemblyType; /** * <p> * Class representing the assembly structure of a SFR. The SFR assembly is * housed in a hexagonal structure called the wrapper tube (or duct), and * contains a lattice of either pins or rods. * </p> * * @author Anna Wojtowicz */ public class SFRAssembly extends SFRComposite { /** * <p> * Size of a SFRAssembly. Size represents number of pins in a fuel or * control assembly, and rods in a reflector assembly. * </p> * */ private int size; /** * <p> * The type of SFR assembly represented, either fuel, control or reflector. * </p> * */ protected AssemblyType assemblyType; /** * <p> * Thickness of the assembly duct wall. * </p> * */ private double ductThickness; /** * <p> * Parameterized constructor with assemble size specified. Size represents * number of pins in a fuel or control assembly, and rods in a reflector * assembly. * </p> * * @param size * Size of the assembly. */ public SFRAssembly(int size) { // Set the size if positive, otherwise default to 1. this.size = (size > 0 ? size : 1); // Set the default name, description, and ID. setName("SFR Assembly 1"); setDescription("SFR Assembly 1's Description"); setId(1); // Default the assembly type to Fuel. assemblyType = AssemblyType.Fuel; // Initialize ductThickness. ductThickness = 0.0; return; } /** * <p> * Parameterized constructor with assembly name, type and size specified. * Size represents number of pins in a fuel or control assembly, and rods in * a reflector assembly. * </p> * * @param name * The name of the assembly. * @param type * The assembly type (fuel, control or reflector). * @param size * The size of the assembly. */ public SFRAssembly(String name, AssemblyType type, int size) { // Call the basic constructor first. this(size); // Set the name. setName(name); // Set the assembly type if possible. If null, the other constructor has // already set the type to the default (Fuel). if (type != null) { assemblyType = type; } return; } /** * <p> * Returns the assembly size. Size represents number of pins in a fuel or * control assembly, and rods in a reflector assembly. * </p> * * @return The size of the assembly. */ public int getSize() { return size; } /** * <p> * Returns the assembly type (fuel, control or reflector). * </p> * * @return The assembly type. */ public AssemblyType getAssemblyType() { return assemblyType; } /** * <p> * Sets the thickness of the assembly duct wall. * </p> * * @param thickness * The duct thickness. Must be non-negative. */ public void setDuctThickness(double thickness) { // Only set the duct thickness if it is 0 or larger. if (thickness >= 0.0) { ductThickness = thickness; } return; } /** * <p> * Returns the duct wall thickness of an assembly as a double. * </p> * * @return The duct thickness. */ public double getDuctThickness() { return ductThickness; } /** * <p> * Overrides the equals operation to check the attributes on this object * with another object of the same type. Returns true if the objects are * equal. False otherwise. * </p> * * @param otherObject * The object to be compared. * @return True if otherObject is equal. False otherwise. */ @Override public boolean equals(Object otherObject) { // By default, the objects are not equivalent. boolean equals = false; // Check the reference. if (this == otherObject) { equals = true; } // Check the information stored in the other object. else if (otherObject != null && otherObject instanceof SFRAssembly) { // We can now cast the other object. SFRAssembly assembly = (SFRAssembly) otherObject; // Compare the values between the two objects. equals = (super.equals(otherObject) && size == assembly.size && assemblyType == assembly.assemblyType && ductThickness == assembly.ductThickness); } return equals; } /** * <p> * Returns the hashCode of the object. * </p> * * @return <p> * The hash of the object. * </p> */ @Override public int hashCode() { // Hash based on super's hashCode. int hash = super.hashCode(); // Add local hashes. hash += 31 * size; hash += 31 * assemblyType.hashCode(); hash += 31 * ductThickness; return hash; } /** * <p> * Deep copies the contents of the object from another object. * </p> * * @param otherObject * <p> * The object to be copied from. * </p> */ public void copy(SFRAssembly otherObject) { // Check the parameters. if (otherObject == null) { return; } // Copy the super's values. super.copy(otherObject); // Copy the local values. size = otherObject.size; assemblyType = otherObject.assemblyType; ductThickness = otherObject.ductThickness; return; } /** * <p> * Deep copies and returns a newly instantiated object. * </p> * * @return <p> * The newly instantiated copied object. * </p> */ @Override public Object clone() { // Initialize a new object. SFRAssembly object = new SFRAssembly(size); // Copy the contents from this one. object.copy(this); // Return the newly instantiated object. return object; } /** * Overrides the default behavior (ignore) from SFRComponent and implements * the accept operation for this SFRComponent's type. */ @Override public void accept(ISFRComponentVisitor visitor) { if (visitor != null) { visitor.visit(this); } return; } }
gorindn/ice
src/org.eclipse.ice.reactor.sfr/src/org/eclipse/ice/reactor/sfr/core/assembly/SFRAssembly.java
Java
epl-1.0
6,609
<?php /** * DmSetting filter form base class. * * @package retest * @subpackage filter * @author Your name here * @version SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $ */ abstract class BaseDmSettingFormFilter extends BaseFormFilterDoctrine { public function setup() { if($this->needsWidget('id')){ $this->setWidget('id', new sfWidgetFormDmFilterInput()); $this->setValidator('id', new sfValidatorDoctrineChoice(array('required' => false, 'model' => 'DmSetting', 'column' => 'id'))); } if($this->needsWidget('name')){ $this->setWidget('name', new sfWidgetFormDmFilterInput()); $this->setValidator('name', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('type')){ $this->setWidget('type', new sfWidgetFormChoice(array('multiple' => true, 'choices' => array('' => '', 'text' => 'text', 'boolean' => 'boolean', 'select' => 'select', 'textarea' => 'textarea', 'number' => 'number', 'datetime' => 'datetime')))); $this->setValidator('type', new sfValidatorChoice(array('required' => false, 'multiple' => true , 'choices' => array('text' => 'text', 'boolean' => 'boolean', 'select' => 'select', 'textarea' => 'textarea', 'number' => 'number', 'datetime' => 'datetime')))); } if($this->needsWidget('params')){ $this->setWidget('params', new sfWidgetFormDmFilterInput()); $this->setValidator('params', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('group_name')){ $this->setWidget('group_name', new sfWidgetFormDmFilterInput()); $this->setValidator('group_name', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } if($this->needsWidget('credentials')){ $this->setWidget('credentials', new sfWidgetFormDmFilterInput()); $this->setValidator('credentials', new sfValidatorSchemaFilter('text', new sfValidatorString(array('required' => false)))); } $this->mergeI18nForm(); $this->widgetSchema->setNameFormat('dm_setting_filters[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function getModelName() { return 'DmSetting'; } public function getFields() { return array( 'id' => 'Number', 'name' => 'Text', 'type' => 'Enum', 'params' => 'Text', 'group_name' => 'Text', 'credentials' => 'Text', 'id' => 'Number', 'description' => 'Text', 'value' => 'Text', 'default_value' => 'Text', 'lang' => 'Text', ); } }
Teplitsa/bquest.ru
lib/vendor/diem/dmCorePlugin/test/project/lib/filter/doctrine/dmCorePlugin/base/BaseDmSettingFormFilter.class.php
PHP
gpl-2.0
2,784
<?php /** * Joomla! 1.5 component irbtools * * @version $Id: view.html.php 2010-10-13 07:12:40 svn $ * @author IRB Barcelona * @package Joomla * @subpackage irbtools * @license GNU/GPL * * IRB Barcelona Tools * * This component file was created using the Joomla Component Creator by Not Web Design * http://www.notwebdesign.com/joomla_component_creator/ * */ // no direct access defined('_JEXEC') or die('Restricted access'); // Import Joomla! libraries jimport( 'joomla.application.component.view'); class IrbtoolsViewDefault extends JView { function display($tpl = null) { parent::display($tpl); } } ?>
rbartolomeirb/joomlaatirb
tools/com_irbtools/build/administrator/components/com_irbtools/views/default/view.html.php
PHP
gpl-2.0
663
// $Id: Dynamic_Service_Dependency.cpp 96985 2013-04-11 15:50:32Z huangh $ #include "ace/ACE.h" #include "ace/DLL_Manager.h" #include "ace/Dynamic_Service_Dependency.h" #include "ace/Service_Config.h" #include "ace/Log_Category.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_TCHAR *principal) { this->init (ACE_Service_Config::current (), principal); } ACE_Dynamic_Service_Dependency::ACE_Dynamic_Service_Dependency (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal) { this->init (cfg, principal); } ACE_Dynamic_Service_Dependency::~ACE_Dynamic_Service_Dependency (void) { if (ACE::debug ()) ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) DSD, this=%@ - destroying\n"), this)); } void ACE_Dynamic_Service_Dependency::init (const ACE_Service_Gestalt *cfg, const ACE_TCHAR *principal) { const ACE_Service_Type* st = ACE_Dynamic_Service_Base::find_i (cfg, principal,false); if (ACE::debug ()) { ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) DSD, this=%@ - creating dependency on "), this)); st->dump (); } this->tracker_ = st->dll (); } ACE_END_VERSIONED_NAMESPACE_DECL
xIchigox/ArkCORE-NG
dep/acelite/ace/Dynamic_Service_Dependency.cpp
C++
gpl-2.0
1,326
/* java.lang.Number Copyright (C) 1998, 2001 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.lang; import java.io.Serializable; /** ** Number is a generic superclass of all the numeric classes, namely ** <code>Byte</code>, <code>Short</code>, <code>Integer</code>, ** <code>Long</code>, <code>Float</code>, and <code>Double</code>. ** ** It provides ways to convert from any one value to any other. ** ** @author Paul Fisher ** @author John Keiser ** @author Warren Levy ** @since JDK1.0 **/ public abstract class Number implements Serializable { /** Return the value of this <code>Number</code> as a <code>byte</code>. ** @return the value of this <code>Number</code> as a <code>byte</code>. **/ public byte byteValue() { return (byte) intValue(); } /** Return the value of this <code>Number</code> as a <code>short</code>. ** @return the value of this <code>Number</code> as a <code>short</code>. **/ public short shortValue() { return (short) intValue(); } /** Return the value of this <code>Number</code> as an <code>int</code>. ** @return the value of this <code>Number</code> as an <code>int</code>. **/ public abstract int intValue(); /** Return the value of this <code>Number</code> as a <code>long</code>. ** @return the value of this <code>Number</code> as a <code>long</code>. **/ public abstract long longValue(); /** Return the value of this <code>Number</code> as a <code>float</code>. ** @return the value of this <code>Number</code> as a <code>float</code>. **/ public abstract float floatValue(); /** Return the value of this <code>Number</code> as a <code>float</code>. ** @return the value of this <code>Number</code> as a <code>float</code>. **/ public abstract double doubleValue(); private static final long serialVersionUID = -8742448824652078965L; }
aosm/gcc3
libjava/java/lang/Number.java
Java
gpl-2.0
3,524
/* * 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 2 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * (c)Copyright 2006 Hewlett-Packard Development Company, LP. * */ #include "C_ProtocolControl.hpp" #include "Utils.hpp" #include "GeneratorTrace.hpp" #include "GeneratorError.h" #include "C_ProtocolBinary.hpp" #include "C_ProtocolExternal.hpp" #include "C_ProtocolBinaryBodyNotInterpreted.hpp" #include "C_ProtocolBinarySeparator.hpp" #include "C_ProtocolText.hpp" #include "C_ProtocolTlv.hpp" #define XML_PROTOCOL_SECTION (char*)"protocol" #define XML_PROTOCOL_NAME (char*)"name" #define XML_PROTOCOL_TYPE (char*)"type" C_ProtocolControl::C_ProtocolControl(C_TransportControl *P_transport_control) { GEN_DEBUG(1, "C_ProtocolControl::C_ProtocolControl() start"); NEW_VAR(m_name_map, T_ProtocolNameMap()); m_name_map->clear() ; m_protocol_table = NULL ; m_protocol_name_table = NULL ; m_protocol_table_size = 0 ; NEW_VAR(m_id_gen, C_IdGenerator()); m_transport_control = P_transport_control ; GEN_DEBUG(1, "C_ProtocolControl::C_ProtocolControl() end"); } C_ProtocolControl::~C_ProtocolControl() { int L_i ; GEN_DEBUG(1, "C_ProtocolControl::~C_ProtocolControl() start"); if (!m_name_map->empty()) { m_name_map->erase(m_name_map->begin(), m_name_map->end()); } DELETE_VAR(m_name_map); if (m_protocol_table_size != 0) { for (L_i = 0 ; L_i < m_protocol_table_size; L_i++) { DELETE_VAR(m_protocol_table[L_i]); } FREE_TABLE(m_protocol_table); FREE_TABLE(m_protocol_name_table); m_protocol_table_size = 0 ; } DELETE_VAR(m_id_gen) ; m_transport_control = NULL ; GEN_DEBUG(1, "C_ProtocolControl::~C_ProtocolControl() end"); } char* C_ProtocolControl::get_protocol_name(C_XmlData *P_data) { return (P_data->find_value(XML_PROTOCOL_NAME)) ; } char* C_ProtocolControl::get_protocol_type(C_XmlData *P_data) { return (P_data->find_value(XML_PROTOCOL_TYPE)) ; } bool C_ProtocolControl::fromXml (C_XmlData *P_data, T_pConfigValueList P_config_value_list, bool P_display_protocol_stats) { bool L_ret = true ; T_pXmlData_List L_subList ; T_XmlData_List::iterator L_subListIt ; C_XmlData *L_data ; char *L_protocol_name, *L_protocol_type ; int L_protocol_id ; T_ProtocolInstList L_protocol_inst_list ; T_pProtocolInstanceInfo L_protocol_info ; T_ProtocolInstList::iterator L_it ; GEN_DEBUG(1, "C_ProtocolControl::fromXml() start"); if (P_data != NULL) { if ((L_subList = P_data->get_sub_data()) != NULL) { for (L_subListIt = L_subList->begin() ; L_subListIt != L_subList->end() ; L_subListIt++) { L_data = *L_subListIt ; if (L_data != NULL) { if (strcmp(L_data->get_name(), XML_PROTOCOL_SECTION) == 0) { // protocol section definition found L_protocol_name = get_protocol_name (L_data) ; // check protocol type for creation L_protocol_type = get_protocol_type (L_data) ; // check name/type presence if (L_protocol_name == NULL) { GEN_ERROR(E_GEN_FATAL_ERROR, "name mandatory for section " << XML_PROTOCOL_SECTION); L_ret = false ; break ; } if (L_protocol_type == NULL) { GEN_ERROR(E_GEN_FATAL_ERROR, "type mandatory for section " << XML_PROTOCOL_SECTION); L_ret = false ; break ; } // check protocol name unicity if (m_name_map->find(T_ProtocolNameMap::key_type(L_protocol_name)) != m_name_map->end()) { GEN_ERROR(E_GEN_FATAL_ERROR, XML_PROTOCOL_SECTION << " with name [" << L_protocol_name << "] already defined"); L_ret = false ; break ; } // check protocol type or sub type if (strcmp(L_protocol_type, "binary") == 0) { // create protocol instance C_ProtocolBinary *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinary()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-tlv") == 0) { // create protocol instance C_ProtocolTlv *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolTlv()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-body-not-interpreted") == 0) { // create protocol instance C_ProtocolBinaryBodyNotInterpreted *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinaryBodyNotInterpreted()); L_protocol_instance->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "binary-separator") == 0) { // create protocol instance C_ProtocolBinarySeparator *L_protocol_instance = NULL ; T_ConstructorResult L_res ; NEW_VAR(L_protocol_instance, C_ProtocolBinarySeparator()); L_protocol_instance ->construction_data(L_data, &L_protocol_name, &L_res) ; if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { // store new instance if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "external-library") == 0) { C_ProtocolExternal *L_protocol_instance = NULL ; T_ConstructorResult L_res = E_CONSTRUCTOR_OK ; NEW_VAR(L_protocol_instance, C_ProtocolExternal(m_transport_control, L_data, &L_protocol_name, P_config_value_list, &L_res)); if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } // store new instance L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else if (strcmp(L_protocol_type, "text") == 0) { C_ProtocolText *L_protocol_instance = NULL ; T_ConstructorResult L_res = E_CONSTRUCTOR_OK ; NEW_VAR(L_protocol_instance, C_ProtocolText()); L_protocol_instance->analyze_data(L_data, &L_protocol_name, P_config_value_list, &L_res); if (L_res != E_CONSTRUCTOR_OK) { GEN_ERROR(E_GEN_FATAL_ERROR, "Error found in protocol definition"); DELETE_VAR(L_protocol_instance); L_ret = false ; break ; } else { if (P_display_protocol_stats == true) { C_ProtocolStats *L_protocol_stats ; NEW_VAR(L_protocol_stats,C_ProtocolStats(L_protocol_instance)); L_protocol_instance->set_stats(L_protocol_stats); } // store new instance L_protocol_id = m_id_gen->new_id() ; ALLOC_VAR(L_protocol_info, T_pProtocolInstanceInfo, sizeof(T_ProtocolInstanceInfo)); L_protocol_info->m_instance = L_protocol_instance ; L_protocol_info->m_id = L_protocol_id ; L_protocol_info->m_name = L_protocol_name ; L_protocol_inst_list.push_back(L_protocol_info); m_name_map ->insert(T_ProtocolNameMap::value_type(L_protocol_name, L_protocol_id)) ; } } else { GEN_ERROR(E_GEN_FATAL_ERROR, XML_PROTOCOL_SECTION << " [" << L_protocol_name << "] with type [" << L_protocol_type << "] unsupported"); L_ret = false ; } } } } if (L_ret != false) { if (!L_protocol_inst_list.empty()) { m_protocol_table_size = L_protocol_inst_list.size() ; ALLOC_TABLE(m_protocol_table, T_pC_ProtocolFrame*, sizeof(T_pC_ProtocolFrame), m_protocol_table_size) ; ALLOC_TABLE(m_protocol_name_table, char**, sizeof(char*), m_protocol_table_size) ; for (L_it = L_protocol_inst_list.begin(); L_it != L_protocol_inst_list.end() ; L_it++) { L_protocol_info = *L_it ; m_protocol_table[L_protocol_info->m_id] = L_protocol_info->m_instance ; m_protocol_name_table[L_protocol_info->m_id] = L_protocol_info->m_name ; } } else { GEN_ERROR(E_GEN_FATAL_ERROR, "No protocol definition found"); L_ret = false ; } } // if L_ret != false if (!L_protocol_inst_list.empty()) { for (L_it = L_protocol_inst_list.begin(); L_it != L_protocol_inst_list.end() ; L_it++) { FREE_VAR(*L_it); } L_protocol_inst_list.erase(L_protocol_inst_list.begin(), L_protocol_inst_list.end()); } } } GEN_DEBUG(1, "C_ProtocolControl::fromXml() end ret=" << L_ret); return (L_ret); } C_ProtocolFrame* C_ProtocolControl::get_protocol (char *P_name) { C_ProtocolFrame *L_ret = NULL ; int L_id ; L_id = get_protocol_id (P_name) ; if (L_id != ERROR_PROTOCOL_UNKNOWN) { L_ret = m_protocol_table[L_id] ; } return (L_ret) ; } C_ProtocolFrame* C_ProtocolControl::get_protocol (int P_id) { C_ProtocolFrame *L_ret = NULL ; if ((P_id < m_protocol_table_size) && (P_id >= 0)) { L_ret = m_protocol_table[P_id] ; } return (L_ret); } int C_ProtocolControl::get_protocol_id (char *P_name) { int L_ret = ERROR_PROTOCOL_UNKNOWN ; T_ProtocolNameMap::iterator L_it ; L_it = m_name_map->find(T_ProtocolNameMap::key_type(P_name)) ; if (L_it != m_name_map->end()) { L_ret = L_it->second ; } return (L_ret) ; } int C_ProtocolControl::get_nb_protocol () { return (m_protocol_table_size); } char* C_ProtocolControl::get_protocol_name (int P_id) { char *L_ret = NULL ; if ((P_id < m_protocol_table_size) && (P_id >= 0)) { L_ret = m_protocol_name_table[P_id] ; } return (L_ret); }
hamzasheikh/Seagull
seagull/trunk/src/generator-model/C_ProtocolControl.cpp
C++
gpl-2.0
14,839
// Targeted by JavaCPP version 0.8-SNAPSHOT package com.googlecode.javacpp; import com.googlecode.javacpp.*; import com.googlecode.javacpp.annotation.*; import java.nio.*; import static com.googlecode.javacpp.opencv_core.*; import static com.googlecode.javacpp.opencv_imgproc.*; public class opencv_highgui extends com.googlecode.javacpp.helper.opencv_highgui { static { Loader.load(); } // Parsed from /usr/local/include/opencv2/highgui/highgui_c.h /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ // #ifndef __OPENCV_HIGHGUI_H__ // #define __OPENCV_HIGHGUI_H__ // #include "opencv2/core/core_c.h" // #ifdef __cplusplus // #endif /* __cplusplus */ /****************************************************************************************\ * Basic GUI functions * \****************************************************************************************/ //YV //-----------New for Qt /* For font */ /** enum */ public static final int CV_FONT_LIGHT = 25,//QFont::Light, CV_FONT_NORMAL = 50,//QFont::Normal, CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, CV_FONT_BOLD = 75,//QFont::Bold, CV_FONT_BLACK = 87; //QFont::Black /** enum */ public static final int CV_STYLE_NORMAL = 0,//QFont::StyleNormal, CV_STYLE_ITALIC = 1,//QFont::StyleItalic, CV_STYLE_OBLIQUE = 2; //QFont::StyleOblique /* ---------*/ //for color cvScalar(blue_component, green_component, red\_component[, alpha_component]) //and alpha= 0 <-> 0xFF (not transparent <-> transparent) public static native @ByVal @Platform("linux") CvFont cvFontQt(@Cast("const char*") BytePointer nameFont, int pointSize/*CV_DEFAULT(-1)*/, @ByVal CvScalar color/*CV_DEFAULT(cvScalarAll(0))*/, int weight/*CV_DEFAULT(CV_FONT_NORMAL)*/, int style/*CV_DEFAULT(CV_STYLE_NORMAL)*/, int spacing/*CV_DEFAULT(0)*/); public static native @ByVal @Platform("linux") CvFont cvFontQt(@Cast("const char*") BytePointer nameFont); public static native @ByVal @Platform("linux") CvFont cvFontQt(String nameFont, int pointSize/*CV_DEFAULT(-1)*/, @ByVal CvScalar color/*CV_DEFAULT(cvScalarAll(0))*/, int weight/*CV_DEFAULT(CV_FONT_NORMAL)*/, int style/*CV_DEFAULT(CV_STYLE_NORMAL)*/, int spacing/*CV_DEFAULT(0)*/); public static native @ByVal @Platform("linux") CvFont cvFontQt(String nameFont); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal CvPoint org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal @Cast("CvPoint*") IntBuffer org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal @Cast("CvPoint*") int[] org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal CvPoint org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, @Cast("const char*") BytePointer text, @ByVal @Cast("CvPoint*") IntBuffer org, CvFont arg2); public static native @Platform("linux") void cvAddText(@Const CvArr img, String text, @ByVal @Cast("CvPoint*") int[] org, CvFont arg2); public static native @Platform("linux") void cvDisplayOverlay(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayOverlay(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text); public static native @Platform("linux") void cvDisplayOverlay(String name, String text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayOverlay(String name, String text); public static native @Platform("linux") void cvDisplayStatusBar(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayStatusBar(@Cast("const char*") BytePointer name, @Cast("const char*") BytePointer text); public static native @Platform("linux") void cvDisplayStatusBar(String name, String text, int delayms/*CV_DEFAULT(0)*/); public static native @Platform("linux") void cvDisplayStatusBar(String name, String text); public static native @Platform("linux") void cvSaveWindowParameters(@Cast("const char*") BytePointer name); public static native @Platform("linux") void cvSaveWindowParameters(String name); public static native @Platform("linux") void cvLoadWindowParameters(@Cast("const char*") BytePointer name); public static native @Platform("linux") void cvLoadWindowParameters(String name); public static class Pt2Func_int_PointerPointer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_PointerPointer(Pointer p) { super(p); } protected Pt2Func_int_PointerPointer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") PointerPointer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_PointerPointer pt2Func, int argc, @Cast("char**") PointerPointer argv); public static class Pt2Func_int_BytePointer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_BytePointer(Pointer p) { super(p); } protected Pt2Func_int_BytePointer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr BytePointer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_BytePointer pt2Func, int argc, @Cast("char**") @ByPtrPtr BytePointer argv); public static class Pt2Func_int_ByteBuffer extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_ByteBuffer(Pointer p) { super(p); } protected Pt2Func_int_ByteBuffer() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_ByteBuffer pt2Func, int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); public static class Pt2Func_int_byte__ extends FunctionPointer { static { Loader.load(); } public Pt2Func_int_byte__(Pointer p) { super(p); } protected Pt2Func_int_byte__() { allocate(); } private native void allocate(); public native int call(int argc, @Cast("char**") @ByPtrPtr byte[] argv); } public static native @Platform("linux") int cvStartLoop(Pt2Func_int_byte__ pt2Func, int argc, @Cast("char**") @ByPtrPtr byte[] argv); public static native @Platform("linux") void cvStopLoop( ); @Convention("CV_CDECL") public static class CvButtonCallback extends FunctionPointer { static { Loader.load(); } public CvButtonCallback(Pointer p) { super(p); } protected CvButtonCallback() { allocate(); } private native void allocate(); public native void call(int state, Pointer userdata); } /** enum */ public static final int CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2; public static native @Platform("linux") int cvCreateButton( @Cast("const char*") BytePointer button_name/*CV_DEFAULT(NULL)*/,CvButtonCallback on_change/*CV_DEFAULT(NULL)*/, Pointer userdata/*CV_DEFAULT(NULL)*/, int button_type/*CV_DEFAULT(CV_PUSH_BUTTON)*/, int initial_button_state/*CV_DEFAULT(0)*/); public static native @Platform("linux") int cvCreateButton(); public static native @Platform("linux") int cvCreateButton( String button_name/*CV_DEFAULT(NULL)*/,CvButtonCallback on_change/*CV_DEFAULT(NULL)*/, Pointer userdata/*CV_DEFAULT(NULL)*/, int button_type/*CV_DEFAULT(CV_PUSH_BUTTON)*/, int initial_button_state/*CV_DEFAULT(0)*/); //---------------------- /* this function is used to set some external parameters in case of X Window */ public static native int cvInitSystem( int argc, @Cast("char**") PointerPointer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr BytePointer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv ); public static native int cvInitSystem( int argc, @Cast("char**") @ByPtrPtr byte[] argv ); public static native int cvStartWindowThread( ); // --------- YV --------- /** enum */ public static final int //These 3 flags are used by cvSet/GetWindowProperty CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed CV_WINDOW_OPENGL = 0x00001000, //window with opengl support //Those flags are only for Qt CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar CV_GUI_NORMAL = 0x00000010, //old fashious way //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) CV_WINDOW_KEEPRATIO = 0x00000000;//the ration image is respected. /* create window */ public static native int cvNamedWindow( @Cast("const char*") BytePointer name, int flags/*CV_DEFAULT(CV_WINDOW_AUTOSIZE)*/ ); public static native int cvNamedWindow( @Cast("const char*") BytePointer name ); public static native int cvNamedWindow( String name, int flags/*CV_DEFAULT(CV_WINDOW_AUTOSIZE)*/ ); public static native int cvNamedWindow( String name ); /* Set and Get Property of the window */ public static native void cvSetWindowProperty(@Cast("const char*") BytePointer name, int prop_id, double prop_value); public static native void cvSetWindowProperty(String name, int prop_id, double prop_value); public static native double cvGetWindowProperty(@Cast("const char*") BytePointer name, int prop_id); public static native double cvGetWindowProperty(String name, int prop_id); /* display image within window (highgui windows remember their content) */ public static native void cvShowImage( @Cast("const char*") BytePointer name, @Const CvArr image ); public static native void cvShowImage( String name, @Const CvArr image ); /* resize/move window */ public static native void cvResizeWindow( @Cast("const char*") BytePointer name, int width, int height ); public static native void cvResizeWindow( String name, int width, int height ); public static native void cvMoveWindow( @Cast("const char*") BytePointer name, int x, int y ); public static native void cvMoveWindow( String name, int x, int y ); /* destroy window and all the trackers associated with it */ public static native void cvDestroyWindow( @Cast("const char*") BytePointer name ); public static native void cvDestroyWindow( String name ); public static native void cvDestroyAllWindows(); /* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ public static native Pointer cvGetWindowHandle( @Cast("const char*") BytePointer name ); public static native Pointer cvGetWindowHandle( String name ); /* get name of highgui window given its native handle */ public static native @Cast("const char*") BytePointer cvGetWindowName( Pointer window_handle ); @Convention("CV_CDECL") public static class CvTrackbarCallback extends FunctionPointer { static { Loader.load(); } public CvTrackbarCallback(Pointer p) { super(p); } protected CvTrackbarCallback() { allocate(); } private native void allocate(); public native void call(int pos); } /* create trackbar and display it on top of given window, set callback */ public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntBuffer value, int count); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, IntPointer value, int count); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count); public static native int cvCreateTrackbar( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback on_change/*CV_DEFAULT(NULL)*/); public static native int cvCreateTrackbar( String trackbar_name, String window_name, int[] value, int count); @Convention("CV_CDECL") public static class CvTrackbarCallback2 extends FunctionPointer { static { Loader.load(); } public CvTrackbarCallback2(Pointer p) { super(p); } protected CvTrackbarCallback2() { allocate(); } private native void allocate(); public native void call(int pos, Pointer userdata); } public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntPointer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int[] value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, IntPointer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, IntBuffer value, int count, CvTrackbarCallback2 on_change); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback2 on_change, Pointer userdata/*CV_DEFAULT(0)*/); public static native int cvCreateTrackbar2( String trackbar_name, String window_name, int[] value, int count, CvTrackbarCallback2 on_change); /* retrieve or set trackbar position */ public static native int cvGetTrackbarPos( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name ); public static native int cvGetTrackbarPos( String trackbar_name, String window_name ); public static native void cvSetTrackbarPos( @Cast("const char*") BytePointer trackbar_name, @Cast("const char*") BytePointer window_name, int pos ); public static native void cvSetTrackbarPos( String trackbar_name, String window_name, int pos ); /** enum */ public static final int CV_EVENT_MOUSEMOVE = 0, CV_EVENT_LBUTTONDOWN = 1, CV_EVENT_RBUTTONDOWN = 2, CV_EVENT_MBUTTONDOWN = 3, CV_EVENT_LBUTTONUP = 4, CV_EVENT_RBUTTONUP = 5, CV_EVENT_MBUTTONUP = 6, CV_EVENT_LBUTTONDBLCLK = 7, CV_EVENT_RBUTTONDBLCLK = 8, CV_EVENT_MBUTTONDBLCLK = 9; /** enum */ public static final int CV_EVENT_FLAG_LBUTTON = 1, CV_EVENT_FLAG_RBUTTON = 2, CV_EVENT_FLAG_MBUTTON = 4, CV_EVENT_FLAG_CTRLKEY = 8, CV_EVENT_FLAG_SHIFTKEY = 16, CV_EVENT_FLAG_ALTKEY = 32; @Convention("CV_CDECL") public static class CvMouseCallback extends FunctionPointer { static { Loader.load(); } public CvMouseCallback(Pointer p) { super(p); } protected CvMouseCallback() { allocate(); } private native void allocate(); public native void call(int event, int x, int y, int flags, Pointer param); } /* assign callback for mouse events */ public static native void cvSetMouseCallback( @Cast("const char*") BytePointer window_name, CvMouseCallback on_mouse, Pointer param/*CV_DEFAULT(NULL)*/); public static native void cvSetMouseCallback( @Cast("const char*") BytePointer window_name, CvMouseCallback on_mouse); public static native void cvSetMouseCallback( String window_name, CvMouseCallback on_mouse, Pointer param/*CV_DEFAULT(NULL)*/); public static native void cvSetMouseCallback( String window_name, CvMouseCallback on_mouse); /** enum */ public static final int /* 8bit, color or not */ CV_LOAD_IMAGE_UNCHANGED = -1, /* 8bit, gray */ CV_LOAD_IMAGE_GRAYSCALE = 0, /* ?, color */ CV_LOAD_IMAGE_COLOR = 1, /* any depth, ? */ CV_LOAD_IMAGE_ANYDEPTH = 2, /* ?, any color */ CV_LOAD_IMAGE_ANYCOLOR = 4; /* load image from file iscolor can be a combination of above flags where CV_LOAD_IMAGE_UNCHANGED overrides the other flags using CV_LOAD_IMAGE_ANYCOLOR alone is equivalent to CV_LOAD_IMAGE_UNCHANGED unless CV_LOAD_IMAGE_ANYDEPTH is specified images are converted to 8bit */ public static native IplImage cvLoadImage( @Cast("const char*") BytePointer filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvLoadImage( @Cast("const char*") BytePointer filename); public static native IplImage cvLoadImage( String filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvLoadImage( String filename); public static native CvMat cvLoadImageM( @Cast("const char*") BytePointer filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvLoadImageM( @Cast("const char*") BytePointer filename); public static native CvMat cvLoadImageM( String filename, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvLoadImageM( String filename); /** enum */ public static final int CV_IMWRITE_JPEG_QUALITY = 1, CV_IMWRITE_PNG_COMPRESSION = 16, CV_IMWRITE_PNG_STRATEGY = 17, CV_IMWRITE_PNG_BILEVEL = 18, CV_IMWRITE_PNG_STRATEGY_DEFAULT = 0, CV_IMWRITE_PNG_STRATEGY_FILTERED = 1, CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, CV_IMWRITE_PNG_STRATEGY_RLE = 3, CV_IMWRITE_PNG_STRATEGY_FIXED = 4, CV_IMWRITE_PXM_BINARY = 32; /* save image to file */ public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( @Cast("const char*") BytePointer filename, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native int cvSaveImage( String filename, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); /* decode image stored in the buffer */ public static native IplImage cvDecodeImage( @Const CvMat buf, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native IplImage cvDecodeImage( @Const CvMat buf); public static native CvMat cvDecodeImageM( @Const CvMat buf, int iscolor/*CV_DEFAULT(CV_LOAD_IMAGE_COLOR)*/); public static native CvMat cvDecodeImageM( @Const CvMat buf); /* encode image and store the result as a byte vector (single-row 8uC1 matrix) */ public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const IntPointer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( @Cast("const char*") BytePointer ext, @Const CvArr image, @Const IntBuffer params/*CV_DEFAULT(0)*/ ); public static native CvMat cvEncodeImage( String ext, @Const CvArr image, @Const int[] params/*CV_DEFAULT(0)*/ ); /** enum */ public static final int CV_CVTIMG_FLIP = 1, CV_CVTIMG_SWAP_RB = 2; /* utility function: convert one image to another with optional vertical flip */ public static native void cvConvertImage( @Const CvArr src, CvArr dst, int flags/*CV_DEFAULT(0)*/); public static native void cvConvertImage( @Const CvArr src, CvArr dst); /* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ public static native int cvWaitKey(int delay/*CV_DEFAULT(0)*/); public static native int cvWaitKey(); // OpenGL support @Convention("CV_CDECL") public static class CvOpenGlDrawCallback extends FunctionPointer { static { Loader.load(); } public CvOpenGlDrawCallback(Pointer p) { super(p); } protected CvOpenGlDrawCallback() { allocate(); } private native void allocate(); public native void call(Pointer userdata); } public static native void cvSetOpenGlDrawCallback(@Cast("const char*") BytePointer window_name, CvOpenGlDrawCallback callback, Pointer userdata/*CV_DEFAULT(NULL)*/); public static native void cvSetOpenGlDrawCallback(@Cast("const char*") BytePointer window_name, CvOpenGlDrawCallback callback); public static native void cvSetOpenGlDrawCallback(String window_name, CvOpenGlDrawCallback callback, Pointer userdata/*CV_DEFAULT(NULL)*/); public static native void cvSetOpenGlDrawCallback(String window_name, CvOpenGlDrawCallback callback); public static native void cvSetOpenGlContext(@Cast("const char*") BytePointer window_name); public static native void cvSetOpenGlContext(String window_name); public static native void cvUpdateWindow(@Cast("const char*") BytePointer window_name); public static native void cvUpdateWindow(String window_name); /****************************************************************************************\ * Working with Video Files and Cameras * \****************************************************************************************/ /* "black box" capture structure */ @Opaque public static class CvCapture extends Pointer { public CvCapture() { } public CvCapture(Pointer p) { super(p); } } /* start capturing frames from video file */ public static native CvCapture cvCreateFileCapture( @Cast("const char*") BytePointer filename ); public static native CvCapture cvCreateFileCapture( String filename ); /** enum */ public static final int CV_CAP_ANY = 0, // autodetect CV_CAP_MIL = 100, // MIL proprietary drivers CV_CAP_VFW = 200, // platform native CV_CAP_V4L = 200, CV_CAP_V4L2 = 200, CV_CAP_FIREWARE = 300, // IEEE 1394 drivers CV_CAP_FIREWIRE = 300, CV_CAP_IEEE1394 = 300, CV_CAP_DC1394 = 300, CV_CAP_CMU1394 = 300, CV_CAP_STEREO = 400, // TYZX proprietary drivers CV_CAP_TYZX = 400, CV_TYZX_LEFT = 400, CV_TYZX_RIGHT = 401, CV_TYZX_COLOR = 402, CV_TYZX_Z = 403, CV_CAP_QT = 500, // QuickTime CV_CAP_UNICAP = 600, // Unicap drivers CV_CAP_DSHOW = 700, // DirectShow (via videoInput) CV_CAP_MSMF = 1400, // Microsoft Media Foundation (via videoInput) CV_CAP_PVAPI = 800, // PvAPI, Prosilica GigE SDK CV_CAP_OPENNI = 900, // OpenNI (for Kinect) CV_CAP_OPENNI_ASUS = 910, // OpenNI (for Asus Xtion) CV_CAP_ANDROID = 1000, // Android CV_CAP_ANDROID_BACK = CV_CAP_ANDROID+99, // Android back camera CV_CAP_ANDROID_FRONT = CV_CAP_ANDROID+98, // Android front camera CV_CAP_XIAPI = 1100, // XIMEA Camera API CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK CV_CAP_INTELPERC = 1500; // Intel Perceptual Computing SDK /* start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) */ public static native CvCapture cvCreateCameraCapture( int index ); /* grab a frame, return 1 on success, 0 on fail. this function is thought to be fast */ public static native int cvGrabFrame( CvCapture capture ); /* get the frame grabbed with cvGrabFrame(..) This function may apply some frame processing like frame decompression, flipping etc. !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ public static native IplImage cvRetrieveFrame( CvCapture capture, int streamIdx/*CV_DEFAULT(0)*/ ); public static native IplImage cvRetrieveFrame( CvCapture capture ); /* Just a combination of cvGrabFrame and cvRetrieveFrame !!!DO NOT RELEASE or MODIFY the retrieved frame!!! */ public static native IplImage cvQueryFrame( CvCapture capture ); /* stop capturing/reading and free resources */ public static native void cvReleaseCapture( @Cast("CvCapture**") PointerPointer capture ); public static native void cvReleaseCapture( @ByPtrPtr CvCapture capture ); /** enum */ public static final int // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) // every feature can have only one mode turned on at a time CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user CV_CAP_PROP_DC1394_MODE_AUTO = -2, CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, CV_CAP_PROP_POS_MSEC = 0, CV_CAP_PROP_POS_FRAMES = 1, CV_CAP_PROP_POS_AVI_RATIO = 2, CV_CAP_PROP_FRAME_WIDTH = 3, CV_CAP_PROP_FRAME_HEIGHT = 4, CV_CAP_PROP_FPS = 5, CV_CAP_PROP_FOURCC = 6, CV_CAP_PROP_FRAME_COUNT = 7, CV_CAP_PROP_FORMAT = 8, CV_CAP_PROP_MODE = 9, CV_CAP_PROP_BRIGHTNESS = 10, CV_CAP_PROP_CONTRAST = 11, CV_CAP_PROP_SATURATION = 12, CV_CAP_PROP_HUE = 13, CV_CAP_PROP_GAIN = 14, CV_CAP_PROP_EXPOSURE = 15, CV_CAP_PROP_CONVERT_RGB = 16, CV_CAP_PROP_WHITE_BALANCE_BLUE_U = 17, CV_CAP_PROP_RECTIFICATION = 18, CV_CAP_PROP_MONOCROME = 19, CV_CAP_PROP_SHARPNESS = 20, CV_CAP_PROP_AUTO_EXPOSURE = 21, // exposure control done by camera, // user can adjust refernce level // using this feature CV_CAP_PROP_GAMMA = 22, CV_CAP_PROP_TEMPERATURE = 23, CV_CAP_PROP_TRIGGER = 24, CV_CAP_PROP_TRIGGER_DELAY = 25, CV_CAP_PROP_WHITE_BALANCE_RED_V = 26, CV_CAP_PROP_ZOOM = 27, CV_CAP_PROP_FOCUS = 28, CV_CAP_PROP_GUID = 29, CV_CAP_PROP_ISO_SPEED = 30, CV_CAP_PROP_MAX_DC1394 = 31, CV_CAP_PROP_BACKLIGHT = 32, CV_CAP_PROP_PAN = 33, CV_CAP_PROP_TILT = 34, CV_CAP_PROP_ROLL = 35, CV_CAP_PROP_IRIS = 36, CV_CAP_PROP_SETTINGS = 37, CV_CAP_PROP_AUTOGRAB = 1024, // property for highgui class CvCapture_Android only CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING= 1025, // readonly, tricky property, returns cpnst char* indeed CV_CAP_PROP_PREVIEW_FORMAT= 1026, // readonly, tricky property, returns cpnst char* indeed // OpenNI map generators CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR, // Properties of cameras available through OpenNI interfaces CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map // by changing depth generator's view point (if the flag is "on") or // sets this view point to its normal one (if the flag is "off"). CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, // Properties of cameras available through GStreamer interface CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast // Properties of cameras available through XIMEA SDK interface CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds // Properties for Android cameras CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, // Properties of cameras available through AVFOUNDATION interface CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, // Properties of cameras available through Smartek Giganetix Ethernet Vision interface /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, // Intel PerC streams CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR; /** enum */ public static final int // Data given from depth generator. CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 // Data given from RGB image generator. CV_CAP_OPENNI_BGR_IMAGE = 5, CV_CAP_OPENNI_GRAY_IMAGE = 6; // Supported output modes of OpenNI image generator /** enum */ public static final int CV_CAP_OPENNI_VGA_30HZ = 0, CV_CAP_OPENNI_SXGA_15HZ = 1, CV_CAP_OPENNI_SXGA_30HZ = 2, CV_CAP_OPENNI_QVGA_30HZ = 3, CV_CAP_OPENNI_QVGA_60HZ = 4; //supported by Android camera output formats /** enum */ public static final int CV_CAP_ANDROID_COLOR_FRAME_BGR = 0, //BGR CV_CAP_ANDROID_COLOR_FRAME = CV_CAP_ANDROID_COLOR_FRAME_BGR, CV_CAP_ANDROID_GREY_FRAME = 1, //Y CV_CAP_ANDROID_COLOR_FRAME_RGB = 2, CV_CAP_ANDROID_COLOR_FRAME_BGRA = 3, CV_CAP_ANDROID_COLOR_FRAME_RGBA = 4; // supported Android camera flash modes /** enum */ public static final int CV_CAP_ANDROID_FLASH_MODE_AUTO = 0, CV_CAP_ANDROID_FLASH_MODE_OFF = 1, CV_CAP_ANDROID_FLASH_MODE_ON = 2, CV_CAP_ANDROID_FLASH_MODE_RED_EYE = 3, CV_CAP_ANDROID_FLASH_MODE_TORCH = 4; // supported Android camera focus modes /** enum */ public static final int CV_CAP_ANDROID_FOCUS_MODE_AUTO = 0, CV_CAP_ANDROID_FOCUS_MODE_CONTINUOUS_VIDEO = 1, CV_CAP_ANDROID_FOCUS_MODE_EDOF = 2, CV_CAP_ANDROID_FOCUS_MODE_FIXED = 3, CV_CAP_ANDROID_FOCUS_MODE_INFINITY = 4, CV_CAP_ANDROID_FOCUS_MODE_MACRO = 5; // supported Android camera white balance modes /** enum */ public static final int CV_CAP_ANDROID_WHITE_BALANCE_AUTO = 0, CV_CAP_ANDROID_WHITE_BALANCE_CLOUDY_DAYLIGHT = 1, CV_CAP_ANDROID_WHITE_BALANCE_DAYLIGHT = 2, CV_CAP_ANDROID_WHITE_BALANCE_FLUORESCENT = 3, CV_CAP_ANDROID_WHITE_BALANCE_INCANDESCENT = 4, CV_CAP_ANDROID_WHITE_BALANCE_SHADE = 5, CV_CAP_ANDROID_WHITE_BALANCE_TWILIGHT = 6, CV_CAP_ANDROID_WHITE_BALANCE_WARM_FLUORESCENT = 7; // supported Android camera antibanding modes /** enum */ public static final int CV_CAP_ANDROID_ANTIBANDING_50HZ = 0, CV_CAP_ANDROID_ANTIBANDING_60HZ = 1, CV_CAP_ANDROID_ANTIBANDING_AUTO = 2, CV_CAP_ANDROID_ANTIBANDING_OFF = 3; /** enum */ public static final int CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. CV_CAP_INTELPERC_IMAGE = 3; /* retrieve or set capture properties */ public static native double cvGetCaptureProperty( CvCapture capture, int property_id ); public static native int cvSetCaptureProperty( CvCapture capture, int property_id, double value ); // Return the type of the capturer (eg, CV_CAP_V4W, CV_CAP_UNICAP), which is unknown if created with CV_CAP_ANY public static native int cvGetCaptureDomain( CvCapture capture); /* "black box" video file writer structure */ @Opaque public static class CvVideoWriter extends Pointer { public CvVideoWriter() { } public CvVideoWriter(Pointer p) { super(p); } } // #define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) public static native int CV_FOURCC(@Cast("char") byte c1, @Cast("char") byte c2, @Cast("char") byte c3, @Cast("char") byte c4); public static final int CV_FOURCC_PROMPT = -1; /* Open Codec Selection Dialog (Windows only) */ public static native @MemberGetter int CV_FOURCC_DEFAULT(); public static final int CV_FOURCC_DEFAULT = CV_FOURCC_DEFAULT(); /* Use default codec for specified filename (Linux only) */ /* initialize video file writer */ public static native CvVideoWriter cvCreateVideoWriter( @Cast("const char*") BytePointer filename, int fourcc, double fps, @ByVal CvSize frame_size, int is_color/*CV_DEFAULT(1)*/); public static native CvVideoWriter cvCreateVideoWriter( @Cast("const char*") BytePointer filename, int fourcc, double fps, @ByVal CvSize frame_size); public static native CvVideoWriter cvCreateVideoWriter( String filename, int fourcc, double fps, @ByVal CvSize frame_size, int is_color/*CV_DEFAULT(1)*/); public static native CvVideoWriter cvCreateVideoWriter( String filename, int fourcc, double fps, @ByVal CvSize frame_size); //CVAPI(CvVideoWriter*) cvCreateImageSequenceWriter( const char* filename, // int is_color CV_DEFAULT(1)); /* write frame to video file */ public static native int cvWriteFrame( CvVideoWriter writer, @Const IplImage image ); /* close video file writer */ public static native void cvReleaseVideoWriter( @Cast("CvVideoWriter**") PointerPointer writer ); public static native void cvReleaseVideoWriter( @ByPtrPtr CvVideoWriter writer ); /****************************************************************************************\ * Obsolete functions/synonyms * \****************************************************************************************/ public static native CvCapture cvCaptureFromFile(@Cast("const char*") BytePointer arg1); public static native CvCapture cvCaptureFromFile(String arg1); public static native CvCapture cvCaptureFromCAM(int arg1); public static native CvCapture cvCaptureFromAVI(@Cast("const char*") BytePointer arg1); public static native CvCapture cvCaptureFromAVI(String arg1); public static native CvVideoWriter cvCreateAVIWriter(@Cast("const char*") BytePointer arg1, int arg2, double arg3, @ByVal CvSize arg4, int arg5); public static native CvVideoWriter cvCreateAVIWriter(String arg1, int arg2, double arg3, @ByVal CvSize arg4, int arg5); public static native int cvWriteToAVI(CvVideoWriter arg1, IplImage arg2); public static native void cvAddSearchPath(@Cast("const char*") BytePointer path); public static native void cvAddSearchPath(String path); public static native int cvvInitSystem(int arg1, @Cast("char**") PointerPointer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr BytePointer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr ByteBuffer arg2); public static native int cvvInitSystem(int arg1, @Cast("char**") @ByPtrPtr byte[] arg2); public static native void cvvNamedWindow(@Cast("const char*") BytePointer arg1, int arg2); public static native void cvvNamedWindow(String arg1, int arg2); public static native void cvvShowImage(@Cast("const char*") BytePointer arg1, CvArr arg2); public static native void cvvShowImage(String arg1, CvArr arg2); public static native void cvvResizeWindow(@Cast("const char*") BytePointer arg1, int arg2, int arg3); public static native void cvvResizeWindow(String arg1, int arg2, int arg3); public static native void cvvDestroyWindow(@Cast("const char*") BytePointer arg1); public static native void cvvDestroyWindow(String arg1); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, IntPointer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, IntBuffer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, int[] arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, IntPointer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(@Cast("const char*") BytePointer arg1, @Cast("const char*") BytePointer arg2, IntBuffer arg3, int arg4, CvTrackbarCallback arg5); public static native int cvvCreateTrackbar(String arg1, String arg2, int[] arg3, int arg4, CvTrackbarCallback arg5); public static native IplImage cvvLoadImage(@Cast("const char*") BytePointer name); public static native IplImage cvvLoadImage(String name); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, IntPointer arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, IntBuffer arg3); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, int[] arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, IntPointer arg3); public static native int cvvSaveImage(@Cast("const char*") BytePointer arg1, CvArr arg2, IntBuffer arg3); public static native int cvvSaveImage(String arg1, CvArr arg2, int[] arg3); public static native void cvvAddSearchPath(@Cast("const char*") BytePointer arg1); public static native void cvvAddSearchPath(String arg1); public static native int cvvWaitKey(@Cast("const char*") BytePointer name); public static native int cvvWaitKey(String name); public static native int cvvWaitKeyEx(@Cast("const char*") BytePointer name, int delay); public static native int cvvWaitKeyEx(String name, int delay); public static native void cvvConvertImage(CvArr arg1, CvArr arg2, int arg3); public static final int HG_AUTOSIZE = CV_WINDOW_AUTOSIZE; // #define set_preprocess_func cvSetPreprocessFuncWin32 // #define set_postprocess_func cvSetPostprocessFuncWin32 // #if defined WIN32 || defined _WIN32 // #endif // #ifdef __cplusplus // #endif // #endif // Parsed from /usr/local/include/opencv2/highgui/highgui.hpp /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ // #ifndef __OPENCV_HIGHGUI_HPP__ // #define __OPENCV_HIGHGUI_HPP__ // #include "opencv2/core/core.hpp" // #include "opencv2/highgui/highgui_c.h" // #ifdef __cplusplus /** enum cv:: */ public static final int // Flags for namedWindow WINDOW_NORMAL = CV_WINDOW_NORMAL, // the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size WINDOW_AUTOSIZE = CV_WINDOW_AUTOSIZE, // the user cannot resize the window, the size is constrainted by the image displayed WINDOW_OPENGL = CV_WINDOW_OPENGL, // window with opengl support // Flags for set / getWindowProperty WND_PROP_FULLSCREEN = CV_WND_PROP_FULLSCREEN, // fullscreen property WND_PROP_AUTOSIZE = CV_WND_PROP_AUTOSIZE, // autosize property WND_PROP_ASPECT_RATIO = CV_WND_PROP_ASPECTRATIO, // window's aspect ration WND_PROP_OPENGL = CV_WND_PROP_OPENGL; // opengl support @Namespace("cv") public static native void namedWindow(@StdString BytePointer winname, int flags/*=WINDOW_AUTOSIZE*/); @Namespace("cv") public static native void namedWindow(@StdString BytePointer winname); @Namespace("cv") public static native void namedWindow(@StdString String winname, int flags/*=WINDOW_AUTOSIZE*/); @Namespace("cv") public static native void namedWindow(@StdString String winname); @Namespace("cv") public static native void destroyWindow(@StdString BytePointer winname); @Namespace("cv") public static native void destroyWindow(@StdString String winname); @Namespace("cv") public static native void destroyAllWindows(); @Namespace("cv") public static native int startWindowThread(); @Namespace("cv") public static native int waitKey(int delay/*=0*/); @Namespace("cv") public static native int waitKey(); @Namespace("cv") public static native void imshow(@StdString BytePointer winname, @ByVal Mat mat); @Namespace("cv") public static native void imshow(@StdString String winname, @ByVal Mat mat); @Namespace("cv") public static native void resizeWindow(@StdString BytePointer winname, int width, int height); @Namespace("cv") public static native void resizeWindow(@StdString String winname, int width, int height); @Namespace("cv") public static native void moveWindow(@StdString BytePointer winname, int x, int y); @Namespace("cv") public static native void moveWindow(@StdString String winname, int x, int y); @Namespace("cv") public static native void setWindowProperty(@StdString BytePointer winname, int prop_id, double prop_value); @Namespace("cv") public static native void setWindowProperty(@StdString String winname, int prop_id, double prop_value);//YV @Namespace("cv") public static native double getWindowProperty(@StdString BytePointer winname, int prop_id); @Namespace("cv") public static native double getWindowProperty(@StdString String winname, int prop_id);//YV /** enum cv:: */ public static final int EVENT_MOUSEMOVE = 0, EVENT_LBUTTONDOWN = 1, EVENT_RBUTTONDOWN = 2, EVENT_MBUTTONDOWN = 3, EVENT_LBUTTONUP = 4, EVENT_RBUTTONUP = 5, EVENT_MBUTTONUP = 6, EVENT_LBUTTONDBLCLK = 7, EVENT_RBUTTONDBLCLK = 8, EVENT_MBUTTONDBLCLK = 9; /** enum cv:: */ public static final int EVENT_FLAG_LBUTTON = 1, EVENT_FLAG_RBUTTON = 2, EVENT_FLAG_MBUTTON = 4, EVENT_FLAG_CTRLKEY = 8, EVENT_FLAG_SHIFTKEY = 16, EVENT_FLAG_ALTKEY = 32; public static class MouseCallback extends FunctionPointer { static { Loader.load(); } public MouseCallback(Pointer p) { super(p); } protected MouseCallback() { allocate(); } private native void allocate(); public native void call(int event, int x, int y, int flags, Pointer userdata); } /** assigns callback for mouse events */ @Namespace("cv") public static native void setMouseCallback(@StdString BytePointer winname, MouseCallback onMouse, Pointer userdata/*=0*/); @Namespace("cv") public static native void setMouseCallback(@StdString BytePointer winname, MouseCallback onMouse); @Namespace("cv") public static native void setMouseCallback(@StdString String winname, MouseCallback onMouse, Pointer userdata/*=0*/); @Namespace("cv") public static native void setMouseCallback(@StdString String winname, MouseCallback onMouse); @Convention("CV_CDECL") public static class TrackbarCallback extends FunctionPointer { static { Loader.load(); } public TrackbarCallback(Pointer p) { super(p); } protected TrackbarCallback() { allocate(); } private native void allocate(); public native void call(int pos, Pointer userdata); } @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntPointer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntPointer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntBuffer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntBuffer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, int[] value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, int[] value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntPointer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, IntPointer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntBuffer value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString BytePointer trackbarname, @StdString BytePointer winname, IntBuffer value, int count); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, int[] value, int count, TrackbarCallback onChange/*=0*/, Pointer userdata/*=0*/); @Namespace("cv") public static native int createTrackbar(@StdString String trackbarname, @StdString String winname, int[] value, int count); @Namespace("cv") public static native int getTrackbarPos(@StdString BytePointer trackbarname, @StdString BytePointer winname); @Namespace("cv") public static native int getTrackbarPos(@StdString String trackbarname, @StdString String winname); @Namespace("cv") public static native void setTrackbarPos(@StdString BytePointer trackbarname, @StdString BytePointer winname, int pos); @Namespace("cv") public static native void setTrackbarPos(@StdString String trackbarname, @StdString String winname, int pos); // OpenGL support public static class OpenGlDrawCallback extends FunctionPointer { static { Loader.load(); } public OpenGlDrawCallback(Pointer p) { super(p); } protected OpenGlDrawCallback() { allocate(); } private native void allocate(); public native void call(Pointer userdata); } @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString BytePointer winname, OpenGlDrawCallback onOpenGlDraw, Pointer userdata/*=0*/); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString BytePointer winname, OpenGlDrawCallback onOpenGlDraw); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString String winname, OpenGlDrawCallback onOpenGlDraw, Pointer userdata/*=0*/); @Namespace("cv") public static native void setOpenGlDrawCallback(@StdString String winname, OpenGlDrawCallback onOpenGlDraw); @Namespace("cv") public static native void setOpenGlContext(@StdString BytePointer winname); @Namespace("cv") public static native void setOpenGlContext(@StdString String winname); @Namespace("cv") public static native void updateWindow(@StdString BytePointer winname); @Namespace("cv") public static native void updateWindow(@StdString String winname); // < Deperecated @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @Const @ByRef GlArrays arr); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @Const @ByRef GlArrays arr); @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @ByVal Mat points, @ByVal Mat colors/*=noArray()*/); @Namespace("cv") public static native void pointCloudShow(@StdString BytePointer winname, @Const @ByRef GlCamera camera, @ByVal Mat points); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @ByVal Mat points, @ByVal Mat colors/*=noArray()*/); @Namespace("cv") public static native void pointCloudShow(@StdString String winname, @Const @ByRef GlCamera camera, @ByVal Mat points); // > //Only for Qt @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString BytePointer nameFont, int pointSize/*=-1*/, @ByVal Scalar color/*=Scalar::all(0)*/, int weight/*=CV_FONT_NORMAL*/, int style/*=CV_STYLE_NORMAL*/, int spacing/*=0*/); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString BytePointer nameFont); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString String nameFont, int pointSize/*=-1*/, @ByVal Scalar color/*=Scalar::all(0)*/, int weight/*=CV_FONT_NORMAL*/, int style/*=CV_STYLE_NORMAL*/, int spacing/*=0*/); @Namespace("cv") public static native @ByVal CvFont fontQt(@StdString String nameFont); @Namespace("cv") public static native void addText( @Const @ByRef Mat img, @StdString BytePointer text, @ByVal Point org, @ByVal CvFont font); @Namespace("cv") public static native void addText( @Const @ByRef Mat img, @StdString String text, @ByVal Point org, @ByVal CvFont font); @Namespace("cv") public static native void displayOverlay(@StdString BytePointer winname, @StdString BytePointer text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayOverlay(@StdString BytePointer winname, @StdString BytePointer text); @Namespace("cv") public static native void displayOverlay(@StdString String winname, @StdString String text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayOverlay(@StdString String winname, @StdString String text); @Namespace("cv") public static native void displayStatusBar(@StdString BytePointer winname, @StdString BytePointer text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayStatusBar(@StdString BytePointer winname, @StdString BytePointer text); @Namespace("cv") public static native void displayStatusBar(@StdString String winname, @StdString String text, int delayms/*CV_DEFAULT(0)*/); @Namespace("cv") public static native void displayStatusBar(@StdString String winname, @StdString String text); @Namespace("cv") public static native void saveWindowParameters(@StdString BytePointer windowName); @Namespace("cv") public static native void saveWindowParameters(@StdString String windowName); @Namespace("cv") public static native void loadWindowParameters(@StdString BytePointer windowName); @Namespace("cv") public static native void loadWindowParameters(@StdString String windowName); @Namespace("cv") public static native int startLoop(Pt2Func_int_PointerPointer pt2Func, int argc, @Cast("char**") PointerPointer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_BytePointer pt2Func, int argc, @Cast("char**") @ByPtrPtr BytePointer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_ByteBuffer pt2Func, int argc, @Cast("char**") @ByPtrPtr ByteBuffer argv); @Namespace("cv") public static native int startLoop(Pt2Func_int_byte__ pt2Func, int argc, @Cast("char**") @ByPtrPtr byte[] argv); @Namespace("cv") public static native void stopLoop(); @Convention("CV_CDECL") public static class ButtonCallback extends FunctionPointer { static { Loader.load(); } public ButtonCallback(Pointer p) { super(p); } protected ButtonCallback() { allocate(); } private native void allocate(); public native void call(int state, Pointer userdata); } @Namespace("cv") public static native int createButton( @StdString BytePointer bar_name, ButtonCallback on_change, Pointer userdata/*=NULL*/, int type/*=CV_PUSH_BUTTON*/, @Cast("bool") boolean initial_button_state/*=0*/); @Namespace("cv") public static native int createButton( @StdString BytePointer bar_name, ButtonCallback on_change); @Namespace("cv") public static native int createButton( @StdString String bar_name, ButtonCallback on_change, Pointer userdata/*=NULL*/, int type/*=CV_PUSH_BUTTON*/, @Cast("bool") boolean initial_button_state/*=0*/); @Namespace("cv") public static native int createButton( @StdString String bar_name, ButtonCallback on_change); //------------------------- /** enum cv:: */ public static final int // 8bit, color or not IMREAD_UNCHANGED = -1, // 8bit, gray IMREAD_GRAYSCALE = 0, // ?, color IMREAD_COLOR = 1, // any depth, ? IMREAD_ANYDEPTH = 2, // ?, any color IMREAD_ANYCOLOR = 4; /** enum cv:: */ public static final int IMWRITE_JPEG_QUALITY = 1, IMWRITE_PNG_COMPRESSION = 16, IMWRITE_PNG_STRATEGY = 17, IMWRITE_PNG_BILEVEL = 18, IMWRITE_PNG_STRATEGY_DEFAULT = 0, IMWRITE_PNG_STRATEGY_FILTERED = 1, IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, IMWRITE_PNG_STRATEGY_RLE = 3, IMWRITE_PNG_STRATEGY_FIXED = 4, IMWRITE_PXM_BINARY = 32; @Namespace("cv") public static native @ByVal Mat imread( @StdString BytePointer filename, int flags/*=1*/ ); @Namespace("cv") public static native @ByVal Mat imread( @StdString BytePointer filename ); @Namespace("cv") public static native @ByVal Mat imread( @StdString String filename, int flags/*=1*/ ); @Namespace("cv") public static native @ByVal Mat imread( @StdString String filename ); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString BytePointer filename, @ByVal Mat img, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imwrite( @StdString String filename, @ByVal Mat img, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @ByVal Mat imdecode( @ByVal Mat buf, int flags ); @Namespace("cv") public static native @ByVal Mat imdecode( @ByVal Mat buf, int flags, Mat dst ); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf, @StdVector IntPointer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector BytePointer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf, @StdVector IntBuffer params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString BytePointer ext, @ByVal Mat img, @Cast("uchar*") @StdVector ByteBuffer buf); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf, @StdVector int[] params/*=vector<int>()*/); @Namespace("cv") public static native @Cast("bool") boolean imencode( @StdString String ext, @ByVal Mat img, @Cast("uchar*") @StdVector byte[] buf); // #ifndef CV_NO_VIDEO_CAPTURE_CPP_API @Namespace("cv") @NoOffset public static class VideoCapture extends Pointer { static { Loader.load(); } public VideoCapture(Pointer p) { super(p); } public VideoCapture() { allocate(); } private native void allocate(); public VideoCapture(@StdString BytePointer filename) { allocate(filename); } private native void allocate(@StdString BytePointer filename); public VideoCapture(@StdString String filename) { allocate(filename); } private native void allocate(@StdString String filename); public VideoCapture(int device) { allocate(device); } private native void allocate(int device); public native @Cast("bool") boolean open(@StdString BytePointer filename); public native @Cast("bool") boolean open(@StdString String filename); public native @Cast("bool") boolean open(int device); public native @Cast("bool") boolean isOpened(); public native void release(); public native @Cast("bool") boolean grab(); public native @Cast("bool") boolean retrieve(@ByRef Mat image, int channel/*=0*/); public native @Cast("bool") boolean retrieve(@ByRef Mat image); public native @ByRef @Name("operator>>") VideoCapture shiftRight(@ByRef Mat image); public native @Cast("bool") boolean read(@ByRef Mat image); public native @Cast("bool") boolean set(int propId, double value); public native double get(int propId); } @Namespace("cv") @NoOffset public static class VideoWriter extends Pointer { static { Loader.load(); } public VideoWriter(Pointer p) { super(p); } public VideoWriter(int size) { allocateArray(size); } private native void allocateArray(int size); @Override public VideoWriter position(int position) { return (VideoWriter)super.position(position); } public VideoWriter() { allocate(); } private native void allocate(); public VideoWriter(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/) { allocate(filename, fourcc, fps, frameSize, isColor); } private native void allocate(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public VideoWriter(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize) { allocate(filename, fourcc, fps, frameSize); } private native void allocate(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize); public VideoWriter(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/) { allocate(filename, fourcc, fps, frameSize, isColor); } private native void allocate(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public VideoWriter(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize) { allocate(filename, fourcc, fps, frameSize); } private native void allocate(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean open(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public native @Cast("bool") boolean open(@StdString BytePointer filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean open(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize, @Cast("bool") boolean isColor/*=true*/); public native @Cast("bool") boolean open(@StdString String filename, int fourcc, double fps, @ByVal Size frameSize); public native @Cast("bool") boolean isOpened(); public native void release(); public native @ByRef @Name("operator<<") VideoWriter shiftLeft(@Const @ByRef Mat image); public native void write(@Const @ByRef Mat image); } // #endif // #endif // #endif }
duongtung4691/javacpp.presets
opencv/src/main/java/com/googlecode/javacpp/opencv_highgui.java
Java
gpl-2.0
75,386
/** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition 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. * * OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @package out * @copyright (C) OXID eSales AG 2003-2013 * @version OXID eShop CE * @version SVN: $Id: oxpromocategory.js 35529 2011-05-23 07:31:20Z vilma $ */ ( function( $ ) { oxCenterElementOnHover = { _create: function(){ var self = this; var el = self.element; el.hover(function(){ var targetObj = $(".viewAllHover", el); var targetObjWidth = targetObj.outerWidth() / 2; var parentObjWidth = el.width() / 2; targetObj.css("left", parentObjWidth - targetObjWidth + "px"); targetObj.show(); }, function(){ $(".viewAllHover", el).hide(); }); } } $.widget( "ui.oxCenterElementOnHover", oxCenterElementOnHover ); } )( jQuery );
apnfq/oxid_test
out/azure/src/js/widgets/oxcenterelementonhover.js
JavaScript
gpl-3.0
1,679
<?php /** * This file is part of OXID eShop Community Edition. * * OXID eShop Community Edition 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. * * OXID eShop Community Edition 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 OXID eShop Community Edition. If not, see <http://www.gnu.org/licenses/>. * * @link http://www.oxid-esales.com * @package core * @copyright (C) OXID eSales AG 2003-2011 * @version OXID eShop CE * @version SVN: $Id: oxfb.php 25467 2010-02-01 14:14:26Z alfonsas $ */ try { include_once getShopBasePath() . "core/facebook/facebook.php"; } catch ( Exception $oEx ) { // skipping class includion if curl or json is not active oxConfig::getInstance()->setConfigParam( "bl_showFbConnect", false ); return; } error_reporting($iOldErrorReproting); /** * Facebook API * * @package core */ class oxFb extends Facebook { /** * oxUtils class instance. * * @var oxutils */ private static $_instance = null; /** * oxUtils class instance. * * @var oxutils */ protected $_blIsConnected = null; /** * Sets default application parameters - FB application ID, * secure key and cookie support. * * @return null */ public function __construct() { $oConfig = oxConfig::getInstance(); $aFbConfig["appId"] = $oConfig->getConfigParam( "sFbAppId" ); $aFbConfig["secret"] = $oConfig->getConfigParam( "sFbSecretKey" ); $aFbConfig["cookie"] = true; parent::__construct( $aFbConfig ); } /** * Returns object instance * * @return oxPictureHandler */ public static function getInstance() { // disable caching for test modules if ( defined( 'OXID_PHP_UNIT' ) ) { self::$_instance = modInstances::getMod( __CLASS__ ); } if ( !self::$_instance instanceof oxFb ) { self::$_instance = oxNew( 'oxFb' ); if ( defined( 'OXID_PHP_UNIT' ) ) { modInstances::addMod( __CLASS__, self::$_instance); } } return self::$_instance; } /** * Checks is user is connected using Facebook connect. * * @return bool */ public function isConnected() { $oConfig = oxConfig::getInstance(); if ( !$oConfig->getConfigParam( "bl_showFbConnect" ) ) { return false; } if ( $this->_blIsConnected !== null ) { return $this->_blIsConnected; } $this->_blIsConnected = false; $oSession = $this->getSession(); if ( $oSession ) { try { if ( $this->getUser() ) { $this->_blIsConnected = true; } } catch (FacebookApiException $e) { $this->_blIsConnected = false; } } return $this->_blIsConnected; } }
OXIDprojects/oxid-ce-hot-offer
core/oxfb.php
PHP
gpl-3.0
3,426
// Generated by CoffeeScript 1.5.0 var auth, changeDashboard, createGraph, dashboard, dataPoll, default_graphite_url, default_period, description, generateDataURL, generateEventsURL, generateGraphiteTargets, getTargetColor, graphScaffold, graphite_url, graphs, init, metrics, period, refresh, refreshSummary, refreshTimer, scheme, toggleCss, _avg, _formatBase1024KMGTP, _last, _max, _min, _sum; graphite_url = graphite_url || 'demo'; default_graphite_url = graphite_url; default_period = 1440; if (scheme === void 0) { scheme = 'classic9'; } period = default_period; dashboard = dashboards[0]; metrics = dashboard['metrics']; description = dashboard['description']; refresh = dashboard['refresh']; refreshTimer = null; auth = auth != null ? auth : false; graphs = []; dataPoll = function() { var graph, _i, _len, _results; _results = []; for (_i = 0, _len = graphs.length; _i < _len; _i++) { graph = graphs[_i]; _results.push(graph.refreshGraph(period)); } return _results; }; _sum = function(series) { return _.reduce(series, (function(memo, val) { return memo + val; }), 0); }; _avg = function(series) { return _sum(series) / series.length; }; _max = function(series) { return _.reduce(series, (function(memo, val) { if (memo === null) { return val; } if (val > memo) { return val; } return memo; }), null); }; _min = function(series) { return _.reduce(series, (function(memo, val) { if (memo === null) { return val; } if (val < memo) { return val; } return memo; }), null); }; _last = function(series) { return _.reduce(series, (function(memo, val) { if (val !== null) { return val; } return memo; }), null); }; _formatBase1024KMGTP = function(y, formatter) { var abs_y; if (formatter == null) { formatter = d3.format(".2r"); } abs_y = Math.abs(y); if (abs_y >= 1125899906842624) { return formatter(y / 1125899906842624) + "P"; } else if (abs_y >= 1099511627776) { return formatter(y / 1099511627776) + "T"; } else if (abs_y >= 1073741824) { return formatter(y / 1073741824) + "G"; } else if (abs_y >= 1048576) { return formatter(y / 1048576) + "M"; } else if (abs_y >= 1024) { return formatter(y / 1024) + "K"; } else if (abs_y < 1 && y > 0) { return formatter(y); } else if (abs_y === 0) { return 0; } else { return formatter(y); } }; refreshSummary = function(graph) { var summary_func, y_data, _ref; if (!((_ref = graph.args) != null ? _ref.summary : void 0)) { return; } if (graph.args.summary === "sum") { summary_func = _sum; } if (graph.args.summary === "avg") { summary_func = _avg; } if (graph.args.summary === "min") { summary_func = _min; } if (graph.args.summary === "max") { summary_func = _max; } if (graph.args.summary === "last") { summary_func = _last; } if (typeof graph.args.summary === "function") { summary_func = graph.args.summary; } if (!summary_func) { console.log("unknown summary function " + graph.args.summary); } y_data = _.map(_.flatten(_.pluck(graph.graph.series, 'data')), function(d) { return d.y; }); return $("" + graph.args.anchor + " .graph-summary").html(graph.args.summary_formatter(summary_func(y_data))); }; graphScaffold = function() { var colspan, context, converter, graph_template, i, metric, offset, _i, _len; graph_template = "{{#dashboard_description}}\n <div class=\"well\">{{{dashboard_description}}}</div>\n{{/dashboard_description}}\n{{#metrics}}\n {{#start_row}}\n <div class=\"row-fluid\">\n {{/start_row}}\n <div class=\"{{span}}\" id=\"graph-{{graph_id}}\">\n <h2>{{metric_alias}} <span class=\"pull-right graph-summary\"><span></h2>\n <div class=\"chart\"></div>\n <div class=\"timeline\"></div>\n <p>{{metric_description}}</p>\n <div class=\"legend\"></div>\n </div>\n {{#end_row}}\n </div>\n {{/end_row}}\n{{/metrics}}"; $('#graphs').empty(); context = { metrics: [] }; converter = new Markdown.Converter(); if (description) { context['dashboard_description'] = converter.makeHtml(description); } offset = 0; for (i = _i = 0, _len = metrics.length; _i < _len; i = ++_i) { metric = metrics[i]; colspan = metric.colspan != null ? metric.colspan : 1; context['metrics'].push({ start_row: offset % 3 === 0, end_row: offset % 3 === 2, graph_id: i, span: 'span' + (4 * colspan), metric_alias: metric.alias, metric_description: metric.description }); offset += colspan; } return $('#graphs').append(Mustache.render(graph_template, context)); }; init = function() { var dash, i, metric, refreshInterval, _i, _j, _len, _len1; $('.dropdown-menu').empty(); for (_i = 0, _len = dashboards.length; _i < _len; _i++) { dash = dashboards[_i]; $('.dropdown-menu').append("<li><a href=\"#\">" + dash.name + "</a></li>"); } graphScaffold(); graphs = []; for (i = _j = 0, _len1 = metrics.length; _j < _len1; i = ++_j) { metric = metrics[i]; graphs.push(createGraph("#graph-" + i, metric)); } $('.page-header h1').empty().append(dashboard.name); refreshInterval = refresh || 10000; if (refreshTimer) { clearInterval(refreshTimer); } return refreshTimer = setInterval(dataPoll, refreshInterval); }; getTargetColor = function(targets, target) { var t, _i, _len; if (typeof targets !== 'object') { return; } for (_i = 0, _len = targets.length; _i < _len; _i++) { t = targets[_i]; if (!t.color) { continue; } if (t.target === target || t.alias === target) { return t.color; } } }; generateGraphiteTargets = function(targets) { var graphite_targets, target, _i, _len; if (typeof targets === "string") { return "&target=" + targets; } if (typeof targets === "function") { return "&target=" + (targets()); } graphite_targets = ""; for (_i = 0, _len = targets.length; _i < _len; _i++) { target = targets[_i]; if (typeof target === "string") { graphite_targets += "&target=" + target; } if (typeof target === "function") { graphite_targets += "&target=" + (target()); } if (typeof target === "object") { graphite_targets += "&target=" + ((target != null ? target.target : void 0) || ''); } } return graphite_targets; }; generateDataURL = function(targets, annotator_target, max_data_points) { var data_targets; annotator_target = annotator_target ? "&target=" + annotator_target : ""; data_targets = generateGraphiteTargets(targets); return "" + graphite_url + "/render?from=-" + period + "minutes&" + data_targets + annotator_target + "&maxDataPoints=" + max_data_points + "&format=json&jsonp=?"; }; generateEventsURL = function(event_tags) { var jsonp, tags; tags = event_tags === '*' ? '' : "&tags=" + event_tags; jsonp = window.json_fallback ? '' : "&jsonp=?"; return "" + graphite_url + "/events/get_data?from=-" + period + "minutes" + tags + jsonp; }; createGraph = function(anchor, metric) { var graph, graph_provider, _ref, _ref1; if (graphite_url === 'demo') { graph_provider = Rickshaw.Graph.Demo; } else { graph_provider = Rickshaw.Graph.JSONP.Graphite; } return graph = new graph_provider({ anchor: anchor, targets: metric.target || metric.targets, summary: metric.summary, summary_formatter: metric.summary_formatter || _formatBase1024KMGTP, scheme: metric.scheme || dashboard.scheme || scheme || 'classic9', annotator_target: ((_ref = metric.annotator) != null ? _ref.target : void 0) || metric.annotator, annotator_description: ((_ref1 = metric.annotator) != null ? _ref1.description : void 0) || 'deployment', events: metric.events, element: $("" + anchor + " .chart")[0], width: $("" + anchor + " .chart").width(), height: metric.height || 300, min: metric.min || 0, max: metric.max, null_as: metric.null_as === void 0 ? null : metric.null_as, renderer: metric.renderer || 'area', interpolation: metric.interpolation || 'step-before', unstack: metric.unstack, stroke: metric.stroke === false ? false : true, strokeWidth: metric.stroke_width, dataURL: generateDataURL(metric.target || metric.targets), onRefresh: function(transport) { return refreshSummary(transport); }, onComplete: function(transport) { var detail, hover_formatter, shelving, xAxis, yAxis; graph = transport.graph; xAxis = new Rickshaw.Graph.Axis.Time({ graph: graph }); xAxis.render(); yAxis = new Rickshaw.Graph.Axis.Y({ graph: graph, tickFormat: function(y) { return _formatBase1024KMGTP(y); }, ticksTreatment: 'glow' }); yAxis.render(); hover_formatter = metric.hover_formatter || _formatBase1024KMGTP; detail = new Rickshaw.Graph.HoverDetail({ graph: graph, yFormatter: function(y) { return hover_formatter(y); } }); $("" + anchor + " .legend").empty(); this.legend = new Rickshaw.Graph.Legend({ graph: graph, element: $("" + anchor + " .legend")[0] }); shelving = new Rickshaw.Graph.Behavior.Series.Toggle({ graph: graph, legend: this.legend }); if (metric.annotator || metric.events) { this.annotator = new GiraffeAnnotate({ graph: graph, element: $("" + anchor + " .timeline")[0] }); } return refreshSummary(this); } }); }; Rickshaw.Graph.JSONP.Graphite = Rickshaw.Class.create(Rickshaw.Graph.JSONP, { request: function() { return this.refreshGraph(period); }, refreshGraph: function(period) { var deferred, _this = this; deferred = this.getAjaxData(period); return deferred.done(function(result) { var annotations, el, i, result_data, series, _i, _len; if (result.length <= 0) { return; } result_data = _.filter(result, function(el) { var _ref; return el.target !== ((_ref = _this.args.annotator_target) != null ? _ref.replace(/["']/g, '') : void 0); }); result_data = _this.preProcess(result_data); if (!_this.graph) { _this.success(_this.parseGraphiteData(result_data, _this.args.null_as)); } series = _this.parseGraphiteData(result_data, _this.args.null_as); if (_this.args.annotator_target) { annotations = _this.parseGraphiteData(_.filter(result, function(el) { return el.target === _this.args.annotator_target.replace(/["']/g, ''); }), _this.args.null_as); } for (i = _i = 0, _len = series.length; _i < _len; i = ++_i) { el = series[i]; _this.graph.series[i].data = el.data; _this.addTotals(i); } _this.graph.renderer.unstack = _this.args.unstack; _this.graph.render(); if (_this.args.events) { deferred = _this.getEvents(period); deferred.done(function(result) { return _this.addEventAnnotations(result); }); } _this.addAnnotations(annotations, _this.args.annotator_description); return _this.args.onRefresh(_this); }); }, addTotals: function(i) { var avg, label, max, min, series_data, sum; label = $(this.legend.lines[i].element).find('span.label').text(); $(this.legend.lines[i].element).find('span.totals').remove(); series_data = _.map(this.legend.lines[i].series.data, function(d) { return d.y; }); sum = _formatBase1024KMGTP(_sum(series_data)); max = _formatBase1024KMGTP(_max(series_data)); min = _formatBase1024KMGTP(_min(series_data)); avg = _formatBase1024KMGTP(_avg(series_data)); return $(this.legend.lines[i].element).append("<span class='totals pull-right'> &Sigma;: " + sum + " <i class='icon-caret-down'></i>: " + min + " <i class='icon-caret-up'></i>: " + max + " <i class='icon-sort'></i>: " + avg + "</span>"); }, preProcess: function(result) { var item, _i, _len; for (_i = 0, _len = result.length; _i < _len; _i++) { item = result[_i]; if (item.datapoints.length === 1) { item.datapoints[0][1] = 0; if (this.args.unstack) { item.datapoints.push([0, 1]); } else { item.datapoints.push([item.datapoints[0][0], 1]); } } } return result; }, parseGraphiteData: function(d, null_as) { var palette, rev_xy, targets; if (null_as == null) { null_as = null; } rev_xy = function(datapoints) { return _.map(datapoints, function(point) { return { 'x': point[1], 'y': point[0] !== null ? point[0] : null_as }; }); }; palette = new Rickshaw.Color.Palette({ scheme: this.args.scheme }); targets = this.args.target || this.args.targets; d = _.map(d, function(el) { var color, _ref; if ((_ref = typeof targets) === "string" || _ref === "function") { color = palette.color(); } else { color = getTargetColor(targets, el.target) || palette.color(); } return { "color": color, "name": el.target, "data": rev_xy(el.datapoints) }; }); Rickshaw.Series.zeroFill(d); return d; }, addEventAnnotations: function(events_json) { var active_annotation, event, _i, _len, _ref, _ref1; if (!events_json) { return; } this.annotator || (this.annotator = new GiraffeAnnotate({ graph: this.graph, element: $("" + this.args.anchor + " .timeline")[0] })); this.annotator.data = {}; $(this.annotator.elements.timeline).empty(); active_annotation = $(this.annotator.elements.timeline).parent().find('.annotation_line.active').size() > 0; if ((_ref = $(this.annotator.elements.timeline).parent()) != null) { _ref.find('.annotation_line').remove(); } for (_i = 0, _len = events_json.length; _i < _len; _i++) { event = events_json[_i]; this.annotator.add(event.when, "" + event.what + " " + (event.data || '')); } this.annotator.update(); if (active_annotation) { return (_ref1 = $(this.annotator.elements.timeline).parent()) != null ? _ref1.find('.annotation_line').addClass('active') : void 0; } }, addAnnotations: function(annotations, description) { var annotation_timestamps, _ref; if (!annotations) { return; } annotation_timestamps = _((_ref = annotations[0]) != null ? _ref.data : void 0).filter(function(el) { return el.y !== 0 && el.y !== null; }); return this.addEventAnnotations(_.map(annotation_timestamps, function(a) { return { when: a.x, what: description }; })); }, getEvents: function(period) { var deferred, _this = this; this.period = period; return deferred = $.ajax({ dataType: 'json', url: generateEventsURL(this.args.events), error: function(xhr, textStatus, errorThrown) { if (textStatus === 'parsererror' && /was not called/.test(errorThrown.message)) { window.json_fallback = true; return _this.refreshGraph(period); } else { return console.log("error loading eventsURL: " + generateEventsURL(_this.args.events)); } } }); }, getAjaxData: function(period) { var deferred; this.period = period; return deferred = $.ajax({ dataType: 'json', url: generateDataURL(this.args.targets, this.args.annotator_target, this.args.width), error: this.error.bind(this) }); } }); Rickshaw.Graph.Demo = Rickshaw.Class.create(Rickshaw.Graph.JSONP.Graphite, { success: function(data) { var i, palette, _i; palette = new Rickshaw.Color.Palette({ scheme: this.args.scheme }); this.seriesData = [[], [], [], [], [], [], [], [], []]; this.random = new Rickshaw.Fixtures.RandomData(period / 60 + 10); for (i = _i = 0; _i <= 60; i = ++_i) { this.random.addData(this.seriesData); } this.graph = new Rickshaw.Graph({ element: this.args.element, width: this.args.width, height: this.args.height, min: this.args.min, max: this.args.max, renderer: this.args.renderer, interpolation: this.args.interpolation, stroke: this.args.stroke, strokeWidth: this.args.strokeWidth, series: [ { color: palette.color(), data: this.seriesData[0], name: 'Moscow' }, { color: palette.color(), data: this.seriesData[1], name: 'Shanghai' }, { color: palette.color(), data: this.seriesData[2], name: 'Amsterdam' }, { color: palette.color(), data: this.seriesData[3], name: 'Paris' }, { color: palette.color(), data: this.seriesData[4], name: 'Tokyo' }, { color: palette.color(), data: this.seriesData[5], name: 'London' }, { color: palette.color(), data: this.seriesData[6], name: 'New York' } ] }); this.graph.renderer.unstack = this.args.unstack; this.graph.render(); return this.onComplete(this); }, refreshGraph: function(period) { var i, _i, _ref, _results; if (!this.graph) { return this.success(); } else { this.random.addData(this.seriesData); this.random.addData(this.seriesData); _.each(this.seriesData, function(d) { return d.shift(); }); this.args.onRefresh(this); this.graph.render(); _results = []; for (i = _i = 0, _ref = this.graph.series.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(this.addTotals(i)); } return _results; } } }); /* # Events and interaction */ $('.dropdown-menu').on('click', 'a', function() { changeDashboard($(this).text()); $('.dropdown').removeClass('open'); return false; }); changeDashboard = function(dash_name) { dashboard = _.where(dashboards, { name: dash_name })[0] || dashboards[0]; graphite_url = dashboard['graphite_url'] || default_graphite_url; description = dashboard['description']; metrics = dashboard['metrics']; refresh = dashboard['refresh']; period || (period = default_period); init(); return $.bbq.pushState({ dashboard: dashboard.name }); }; $('.timepanel').on('click', 'a.range', function() { var dash, timeFrame, _ref; if (graphite_url === 'demo') { changeDashboard(dashboard.name); } period = $(this).attr('data-timeframe') || default_period; dataPoll(); timeFrame = $(this).attr('href').replace(/^#/, ''); dash = (_ref = $.bbq.getState()) != null ? _ref.dashboard : void 0; $.bbq.pushState({ timeFrame: timeFrame, dashboard: dash || dashboard.name }); $(this).parent('.btn-group').find('a').removeClass('active'); $(this).addClass('active'); return false; }); toggleCss = function(css_selector) { if ($.rule(css_selector).text().match('display: ?none')) { return $.rule(css_selector, 'style').remove(); } else { return $.rule("" + css_selector + " {display:none;}").appendTo('style'); } }; $('#legend-toggle').on('click', function() { $(this).toggleClass('active'); $('.legend').toggle(); return false; }); $('#axis-toggle').on('click', function() { $(this).toggleClass('active'); toggleCss('.y_grid'); toggleCss('.y_ticks'); toggleCss('.x_tick'); return false; }); $('#x-label-toggle').on('click', function() { toggleCss('.rickshaw_graph .detail .x_label'); $(this).toggleClass('active'); return false; }); $('#x-item-toggle').on('click', function() { toggleCss('.rickshaw_graph .detail .item.active'); $(this).toggleClass('active'); return false; }); $(window).bind('hashchange', function(e) { var dash, timeFrame, _ref, _ref1; timeFrame = ((_ref = e.getState()) != null ? _ref.timeFrame : void 0) || $(".timepanel a.range[data-timeframe='" + default_period + "']")[0].text || "1d"; dash = (_ref1 = e.getState()) != null ? _ref1.dashboard : void 0; if (dash !== dashboard.name) { changeDashboard(dash); } return $('.timepanel a.range[href="#' + timeFrame + '"]').click(); }); $(function() { $(window).trigger('hashchange'); return init(); });
Stub-O-Matic-BA/stubo-app
stubo/static/giraffe/js/giraffe.js
JavaScript
gpl-3.0
20,491
<?php /* * @copyright 2015 Mautic Contributors. All rights reserved * @author Mautic * * @link http://mautic.org * * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ $isPrototype = ($form->vars['name'] == '__name__'); $filterType = $form['field']->vars['value']; $inGroup = $form->vars['data']['glue'] === 'and'; $object = (isset($form->vars['data']['object'])) ? $form->vars['data']['object'] : 'lead'; $class = (isset($form->vars['data']['object']) && $form->vars['data']['object'] == 'company') ? 'fa-building' : 'fa-user'; ?> <div class="panel<?php echo ($inGroup && $first === false) ? ' in-group' : ''; ?>"> <div class="panel-heading <?php if (!$isPrototype && $form->vars['name'] === '0') { echo ' hide'; } ?>"> <div class="panel-glue col-sm-2 pl-0 "> <?php echo $view['form']->widget($form['glue']); ?> </div> </div> <div class="panel-body"> <div class="col-xs-6 col-sm-3 field-name"> <i class="object-icon fa <?php echo $class; ?>" aria-hidden="true"></i> <span><?php echo ($isPrototype) ? '__label__' : $fields[$object][$filterType]['label']; ?></span> </div> <div class="col-xs-6 col-sm-3 padding-none"> <?php echo $view['form']->widget($form['operator']); ?> </div> <?php $hasErrors = count($form['filter']->vars['errors']) || count($form['display']->vars['errors']); ?> <div class="col-xs-10 col-sm-5 padding-none<?php if ($hasErrors) { echo ' has-error'; } ?>"> <?php echo $view['form']->widget($form['filter']); ?> <?php echo $view['form']->errors($form['filter']); ?> <?php echo $view['form']->widget($form['display']); ?> <?php echo $view['form']->errors($form['display']); ?> </div> <div class="col-xs-2 col-sm-1"> <a href="javascript: void(0);" class="remove-selected btn btn-default text-danger pull-right"><i class="fa fa-trash-o"></i></a> </div> <?php echo $view['form']->widget($form['field']); ?> <?php echo $view['form']->widget($form['type']); ?> <?php echo $view['form']->widget($form['object']); ?> </div> </div>
PatchRanger/mautic
app/bundles/LeadBundle/Views/FormTheme/Filter/_leadlist_filters_entry_widget.html.php
PHP
gpl-3.0
2,233
--TEST-- IntlTimeZone::createEnumeration(): variant with country --SKIPIF-- <?php if (!extension_loaded('intl')) die('skip intl extension not enabled'); --FILE-- <?php ini_set("intl.error_level", E_WARNING); $tz = IntlTimeZone::createEnumeration('NL'); var_dump(get_class($tz)); $count = count(iterator_to_array($tz)); var_dump($count >= 1); $tz->rewind(); var_dump(in_array('Europe/Amsterdam', iterator_to_array($tz))); ?> ==DONE== --EXPECT-- string(12) "IntlIterator" bool(true) bool(true) ==DONE==
tukusejssirs/eSpievatko
spievatko/espievatko/prtbl/srv/php-5.5.11/ext/intl/tests/timezone_createEnumeration_variation2.phpt
PHP
gpl-3.0
504
/* eslint-disable jest/no-export, jest/no-disabled-tests */ /** * Internal dependencies */ const { shopper, merchant, createVariableProduct, } = require( '@woocommerce/e2e-utils' ); let variablePostIdValue; const cartDialogMessage = 'Please select some product options before adding this product to your cart.'; const runVariableProductUpdateTest = () => { describe('Shopper > Update variable product',() => { beforeAll(async () => { await merchant.login(); variablePostIdValue = await createVariableProduct(); await merchant.logout(); }); it('shopper can change variable attributes to the same value', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val1'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '9.99' }); }); it('shopper can change attributes to combination with dimensions and weight', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val2'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '20.00' }); await expect(page).toMatchElement('.woocommerce-variation-availability', { text: 'Out of stock' }); await expect(page).toMatchElement('.woocommerce-product-attributes-item--weight', { text: '200 kg' }); await expect(page).toMatchElement('.woocommerce-product-attributes-item--dimensions', { text: '10 × 20 × 15 cm' }); }); it('shopper can change variable product attributes to variation with a different price', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val1'); await expect(page).toSelect('#attr-3', 'val2'); await expect(page).toMatchElement('.woocommerce-variation-price', { text: '11.99' }); }); it('shopper can reset variations', async () => { await shopper.goToProduct(variablePostIdValue); await expect(page).toSelect('#attr-1', 'val1'); await expect(page).toSelect('#attr-2', 'val2'); await expect(page).toSelect('#attr-3', 'val1'); await expect(page).toClick('.reset_variations'); // Verify the reset by attempting to add the product to the cart const couponDialog = await expect(page).toDisplayDialog(async () => { await expect(page).toClick('.single_add_to_cart_button'); }); expect(couponDialog.message()).toMatch(cartDialogMessage); // Accept the dialog await couponDialog.accept(); }); }); }; module.exports = runVariableProductUpdateTest;
Ninos/woocommerce
tests/e2e/core-tests/specs/shopper/front-end-variable-product-updates.test.js
JavaScript
gpl-3.0
2,776
<?php namespace Safe; use Safe\Exceptions\SwooleException; /** * * * @param string $filename The filename being written. * @param string $content The content writing to the file. * @param int $offset The offset. * @param callable $callback * @throws SwooleException * */ function swoole_async_write(string $filename, string $content, int $offset = null, callable $callback = null): void { error_clear_last(); if ($callback !== null) { $result = \swoole_async_write($filename, $content, $offset, $callback); } elseif ($offset !== null) { $result = \swoole_async_write($filename, $content, $offset); } else { $result = \swoole_async_write($filename, $content); } if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param string $filename The filename being written. * @param string $content The content writing to the file. * @param callable $callback * @param int $flags * @throws SwooleException * */ function swoole_async_writefile(string $filename, string $content, callable $callback = null, int $flags = 0): void { error_clear_last(); if ($flags !== 0) { $result = \swoole_async_writefile($filename, $content, $callback, $flags); } elseif ($callback !== null) { $result = \swoole_async_writefile($filename, $content, $callback); } else { $result = \swoole_async_writefile($filename, $content); } if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param callable $callback * @throws SwooleException * */ function swoole_event_defer(callable $callback): void { error_clear_last(); $result = \swoole_event_defer($callback); if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param int $fd * @throws SwooleException * */ function swoole_event_del(int $fd): void { error_clear_last(); $result = \swoole_event_del($fd); if ($result === false) { throw SwooleException::createFromPhpError(); } } /** * * * @param int $fd * @param string $data * @throws SwooleException * */ function swoole_event_write(int $fd, string $data): void { error_clear_last(); $result = \swoole_event_write($fd, $data); if ($result === false) { throw SwooleException::createFromPhpError(); } }
Irstea/collec
vendor/thecodingmachine/safe/generated/swoole.php
PHP
agpl-3.0
2,407