answer
stringlengths
15
1.25M
$VERSION = 1; package Y; $VERSION = 2; package NotX; $VERSION = 3; package X; $VERSION = 4; 1;
#endif /* !NO_SYS */ #endif /* __LWIPOPTS_H__ */
// This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #import <XCTest/XCTest.h> #import "GCPrivate.h" #pragma clang diagnostic ignored "-<API key>" #pragma clang diagnostic ignored "-Wsign-compare" @interface GCTestCase : XCTestCase @property(nonatomic, readonly, getter=isBotMode) BOOL botMode; - (GCRepository*)<API key>:(NSString*)path bare:(BOOL)bare; - (void)<API key>:(GCRepository*)repository; - (NSString*)<API key>:(GCRepository*)repository command:(NSString*)command, ... <API key>; @end @interface GCTestCase (Extensions) - (void)<API key>:(NSString*)string withRepository:(GCRepository*)repository command:(NSString*)command, ... <API key>; - (void)<API key>:(NSString*)string withRepository:(GCRepository*)repository command:(NSString*)command, ... <API key>; - (void)<API key>:(NSString*)string withRepository:(GCRepository*)repository command:(NSString*)command, ... <API key>; @end @interface GCTests : GCTestCase @end @interface <API key> : GCTestCase @property(nonatomic, readonly) NSString* temporaryPath; @property(nonatomic, readonly) GCRepository* repository; @end @interface <API key> (Extensions) - (void)updateFileAtPath:(NSString*)path withString:(NSString*)string; - (void)deleteFileAtPath:(NSString*)path; - (GCCommit*)<API key>:(NSString*)path string:(NSString*)string message:(NSString*)message; - (GCCommit*)<API key>:(NSString*)path message:(NSString*)message; - (void)<API key>:(NSString*)path equalsString:(NSString*)string; @end @interface <API key> : <API key> @end /* c0 (master) */ @interface <API key> : <API key> @property(nonatomic, readonly) GCLocalBranch* masterBranch; @property(nonatomic, readonly) GCCommit* initialCommit; @end @interface <API key> : <API key> @end /* c0 -> c1 -> c2 -> c3 (master) \ \-> cA (topic) */ @interface <API key> : <API key> @property(nonatomic, readonly) GCLocalBranch* topicBranch; @property(nonatomic, readonly) GCCommit* commit1; @property(nonatomic, readonly) GCCommit* commit2; @property(nonatomic, readonly) GCCommit* commit3; @property(nonatomic, readonly) GCCommit* commitA; @end @interface <API key> : <API key> @end @interface <API key> : GCTestCase @property(nonatomic, readonly) GCSQLiteRepository* repository; @property(nonatomic, readonly) NSString* databasePath; @property(nonatomic, readonly) NSString* configPath; @end @interface <API key> : <API key> @end
#ifndef <API key> #define <API key> #include <asn_application.h> /* Including external dependencies */ #include <asn_SEQUENCE_OF.h> #include <constr_SEQUENCE_OF.h> #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct <API key>; /* <API key> */ typedef struct <API key> { A_SEQUENCE_OF(struct <API key>) list; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } <API key>; /* Implementation */ extern <API key> <API key>; #ifdef __cplusplus } #endif /* Referred external types */ #include "<API key>.h" #endif /* <API key> */ #include <asn_internal.h>
using uint8_t = System.Byte; using uint16_t = System.UInt16; using uint32_t = System.UInt32; using uint64_t = System.UInt64; using int8_t = System.SByte; using int16_t = System.Int16; using int32_t = System.Int32; using int64_t = System.Int64; using float32 = System.Single; using System; using System.Linq; using System.Runtime.InteropServices; using System.Collections.Generic; namespace DroneCAN { public partial class DroneCAN { static void <API key>(<API key> msg, <API key> chunk_cb, object ctx) { uint8_t[] buffer = new uint8_t[8]; <API key>(buffer, msg, chunk_cb, ctx, true); } static uint32_t <API key>(CanardRxTransfer transfer, <API key> msg) { uint32_t bit_ofs = 0; <API key>(transfer, ref bit_ofs, msg, true); return (bit_ofs+7)/8; } static void <API key>(uint8_t[] buffer, <API key> msg, <API key> chunk_cb, object ctx, bool tao) { memset(buffer,0,8); canardEncodeScalar(buffer, 0, 8, msg.button); chunk_cb(buffer, 8, ctx); memset(buffer,0,8); canardEncodeScalar(buffer, 0, 8, msg.press_time); chunk_cb(buffer, 8, ctx); } static void <API key>(CanardRxTransfer transfer,ref uint32_t bit_ofs, <API key> msg, bool tao) { canardDecodeScalar(transfer, bit_ofs, 8, false, ref msg.button); bit_ofs += 8; canardDecodeScalar(transfer, bit_ofs, 8, false, ref msg.press_time); bit_ofs += 8; } } }
@echo off set dir=%~dp0 if "%1" == "config" ( set script=\lib\conf\cli.js ) else if "%1" == "test" ( set script=\node_modules\mocha\bin\mocha ) else ( set script=\lib\agent\cli.js ) @IF EXIST "%dir%\node.exe" ( "%dir%\node.exe" "%dir%\..\%script%" %* ) ELSE ( node "%dir%\..\%script%" %* )
package br.calebe.ticketmachine.exception; /** * * @author Calebe de Paula Bianchini */ public class <API key> extends Exception { }
#include <QApplication> #include <<API key>> #include <QQuickView> #include <QtQml> #include "spheresimulator.h" #include <vendor.h> int main(int argc, char *argv[]) { qputenv("QSG_RENDER_LOOP", "basic"); qmlRegisterType<NoiseSimulator>("SphereSimulator", 1, 0, "SphereSimulator"); QApplication app(argc, argv); QQuickView view; qpm::init(app, *view.engine()); QSurfaceFormat format; format.setMajorVersion(4); format.setMinorVersion(1); format.setProfile(QSurfaceFormat::CoreProfile); #ifndef Q_OS_IOS view.setFormat(format); #endif view.setSource(QUrl("qrc:/main_spheres.qml")); view.show(); return app.exec(); }
// SuperTux // This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #include <math.h> #include "object/tilemap.hpp" #include "scripting/squirrel_util.hpp" #include "scripting/tilemap.hpp" #include "supertux/globals.hpp" #include "supertux/object_factory.hpp" #include "supertux/tile_manager.hpp" #include "supertux/tile_set.hpp" #include "util/reader.hpp" TileMap::TileMap(const TileSet *new_tileset) : tileset(new_tileset), tiles(), real_solid(false), effective_solid(false), speed_x(1), speed_y(1), width(0), height(0), z_pos(0), offset(Vector(0,0)), movement(0,0), drawing_effect(NO_EFFECT), alpha(1.0), current_alpha(1.0), remaining_fade_time(0), path(), walker(), draw_target(DrawingContext::NORMAL) { } TileMap::TileMap(const Reader& reader) : tileset(), tiles(), real_solid(false), effective_solid(false), speed_x(1), speed_y(1), width(-1), height(-1), z_pos(0), offset(Vector(0,0)), movement(Vector(0,0)), drawing_effect(NO_EFFECT), alpha(1.0), current_alpha(1.0), remaining_fade_time(0), path(), walker(), draw_target(DrawingContext::NORMAL) { tileset = current_tileset; assert(tileset != NULL); reader.get("name", name); reader.get("solid", real_solid); reader.get("speed", speed_x); reader.get("speed-y", speed_y); z_pos = reader_get_layer (reader, /* default = */ 0); if(real_solid && ((speed_x != 1) || (speed_y != 1))) { log_warning << "Speed of solid tilemap is not 1. fixing" << std::endl; speed_x = 1; speed_y = 1; } const lisp::Lisp* pathLisp = reader.get_lisp("path"); if (pathLisp) { path.reset(new Path()); path->read(*pathLisp); walker.reset(new PathWalker(path.get(), /*running*/false)); Vector v = path->get_base(); set_offset(v); } std::string draw_target_s = "normal"; reader.get("draw-target", draw_target_s); if (draw_target_s == "normal") draw_target = DrawingContext::NORMAL; if (draw_target_s == "lightmap") draw_target = DrawingContext::LIGHTMAP; if (reader.get("alpha", alpha)) { current_alpha = alpha; } /* Initialize effective_solid based on real_solid and current_alpha. */ effective_solid = real_solid; <API key> (); reader.get("width", width); reader.get("height", height); if(width < 0 || height < 0) throw std::runtime_error("Invalid/No width/height specified in tilemap."); if(!reader.get("tiles", tiles)) throw std::runtime_error("No tiles in tilemap."); if(int(tiles.size()) != width*height) { throw std::runtime_error("wrong number of tiles in tilemap."); } bool empty = true; // make sure all tiles used on the tilemap are loaded and tilemap isn't empty for(Tiles::iterator i = tiles.begin(); i != tiles.end(); ++i) { if(*i != 0) { empty = false; } tileset->get(*i); } if(empty) log_info << "Tilemap '" << name << "', z-pos '" << z_pos << "' is empty." << std::endl; } TileMap::TileMap(const TileSet *new_tileset, std::string name, int z_pos, bool solid, size_t width, size_t height) : tileset(new_tileset), tiles(), real_solid(solid), effective_solid(solid), speed_x(1), speed_y(1), width(0), height(0), z_pos(z_pos), offset(Vector(0,0)), movement(Vector(0,0)), drawing_effect(NO_EFFECT), alpha(1.0), current_alpha(1.0), remaining_fade_time(0), path(), walker(), draw_target(DrawingContext::NORMAL) { this->name = name; if (this->z_pos > (LAYER_GUI - 100)) this->z_pos = LAYER_GUI - 100; resize(width, height); } TileMap::~TileMap() { } void TileMap::update(float elapsed_time) { // handle tilemap fading if (current_alpha != alpha) { remaining_fade_time = std::max(0.0f, remaining_fade_time - elapsed_time); if (remaining_fade_time == 0.0f) { current_alpha = alpha; } else { float amt = (alpha - current_alpha) / (remaining_fade_time / elapsed_time); if (amt > 0) current_alpha = std::min(current_alpha + amt, alpha); if (amt < 0) current_alpha = std::max(current_alpha + amt, alpha); } <API key> (); } movement = Vector(0,0); // if we have a path to follow, follow it if (walker.get()) { Vector v = walker->advance(elapsed_time); movement = v - get_offset(); set_offset(v); } } void TileMap::draw(DrawingContext& context) { // skip draw if current opacity is 0.0 if (current_alpha == 0.0) return; context.push_transform(); if(draw_target != DrawingContext::NORMAL) { context.push_target(); context.set_target(draw_target); } if(drawing_effect != 0) context.set_drawing_effect(drawing_effect); if(current_alpha != 1.0) context.set_alpha(current_alpha); /* Force the translation to be an integer so that the tiles appear sharper. * For consistency (i.e., to avoid 1-pixel gaps), this needs to be done even * for solid tilemaps that are guaranteed to have speed 1. * FIXME Force integer translation for all graphics, not just tilemaps. */ float trans_x = roundf(context.get_translation().x); float trans_y = roundf(context.get_translation().y); context.set_translation(Vector(int(trans_x * speed_x), int(trans_y * speed_y))); Rectf draw_rect = Rectf(context.get_translation(), context.get_translation() + Vector(SCREEN_WIDTH, SCREEN_HEIGHT)); Rect t_draw_rect = <API key>(draw_rect); Vector start = get_tile_position(t_draw_rect.left, t_draw_rect.top); Vector pos; int tx, ty; for(pos.x = start.x, tx = t_draw_rect.left; tx < t_draw_rect.right; pos.x += 32, ++tx) { for(pos.y = start.y, ty = t_draw_rect.top; ty < t_draw_rect.bottom; pos.y += 32, ++ty) { int index = ty*width + tx; assert (index >= 0); assert (index < (width * height)); if (tiles[index] == 0) continue; const Tile* tile = tileset->get(tiles[index]); assert(tile != 0); tile->draw(context, pos, z_pos); } /* for (pos y) */ } /* for (pos x) */ if(draw_target != DrawingContext::NORMAL) { context.pop_target(); } context.pop_transform(); } void TileMap::goto_node(int node_no) { if (!walker.get()) return; walker->goto_node(node_no); } void TileMap::start_moving() { if (!walker.get()) return; walker->start_moving(); } void TileMap::stop_moving() { if (!walker.get()) return; walker->stop_moving(); } void TileMap::expose(HSQUIRRELVM vm, SQInteger table_idx) { if (name.empty()) return; scripting::TileMap* _this = new scripting::TileMap(this); expose_object(vm, table_idx, _this, name, true); } void TileMap::unexpose(HSQUIRRELVM vm, SQInteger table_idx) { if (name.empty()) return; scripting::unexpose_object(vm, table_idx, name); } void TileMap::set(int newwidth, int newheight, const std::vector<unsigned int>&newt, int new_z_pos, bool newsolid) { if(int(newt.size()) != newwidth * newheight) throw std::runtime_error("Wrong tilecount count."); width = newwidth; height = newheight; tiles.resize(newt.size()); tiles = newt; if (new_z_pos > (LAYER_GUI - 100)) z_pos = LAYER_GUI - 100; else z_pos = new_z_pos; real_solid = newsolid; <API key> (); // make sure all tiles are loaded for(Tiles::iterator i = tiles.begin(); i != tiles.end(); ++i) tileset->get(*i); } void TileMap::resize(int new_width, int new_height, int fill_id) { if(new_width < width) { // remap tiles for new width for(int y = 0; y < height && y < new_height; ++y) { for(int x = 0; x < new_width; ++x) { tiles[y * new_width + x] = tiles[y * width + x]; } } } tiles.resize(new_width * new_height, fill_id); if(new_width > width) { // remap tiles for(int y = std::min(height, new_height)-1; y >= 0; --y) { for(int x = new_width-1; x >= 0; --x) { if(x >= width) { tiles[y * new_width + x] = fill_id; continue; } tiles[y * new_width + x] = tiles[y * width + x]; } } } height = new_height; width = new_width; } Rect TileMap::<API key>(const Rectf &rect) const { Rectf rect2 = rect; rect2.move(-offset); int t_left = std::max(0 , int(floorf(rect2.get_left () / 32))); int t_right = std::min(width , int(ceilf (rect2.get_right () / 32))); int t_top = std::max(0 , int(floorf(rect2.get_top () / 32))); int t_bottom = std::min(height, int(ceilf (rect2.get_bottom() / 32))); return Rect(t_left, t_top, t_right, t_bottom); } void TileMap::set_solid(bool solid) { this->real_solid = solid; <API key> (); } uint32_t TileMap::get_tile_id(int x, int y) const { if(x < 0 || x >= width || y < 0 || y >= height) { //log_warning << "tile outside tilemap requested" << std::endl; return 0; } return tiles[y*width + x]; } const Tile* TileMap::get_tile(int x, int y) const { uint32_t id = get_tile_id(x, y); return tileset->get(id); } uint32_t TileMap::get_tile_id_at(const Vector& pos) const { Vector xy = (pos - offset) / 32; return get_tile_id(int(xy.x), int(xy.y)); } const Tile* TileMap::get_tile_at(const Vector& pos) const { uint32_t id = get_tile_id_at(pos); return tileset->get(id); } void TileMap::change(int x, int y, uint32_t newtile) { assert(x >= 0 && x < width && y >= 0 && y < height); tiles[y*width + x] = newtile; } void TileMap::change_at(const Vector& pos, uint32_t newtile) { Vector xy = (pos - offset) / 32; change(int(xy.x), int(xy.y), newtile); } void TileMap::change_all(uint32_t oldtile, uint32_t newtile) { for (size_t x = 0; x < get_width(); x++) { for (size_t y = 0; y < get_height(); y++) { if (get_tile_id(x,y) != oldtile) continue; change(x,y,newtile); } } } void TileMap::fade(float alpha, float seconds) { this->alpha = alpha; this->remaining_fade_time = seconds; } void TileMap::set_alpha(float alpha) { this->alpha = alpha; this->current_alpha = alpha; this->remaining_fade_time = 0; <API key> (); } float TileMap::get_alpha() { return this->current_alpha; } /* * Private methods */ void TileMap::<API key> (void) { if (!real_solid) effective_solid = false; else if (effective_solid && (current_alpha < .25)) effective_solid = false; else if (!effective_solid && (current_alpha >= .75)) effective_solid = true; } /* EOF */
#endregion using System.Collections.Generic; using System.Linq; namespace OpenRA { public sealed class HotkeyDefinition { public readonly string Name; public readonly Hotkey Default = Hotkey.Invalid; public readonly string Description = ""; public readonly HashSet<string> Types = new HashSet<string>(); public HotkeyDefinition(string name, MiniYaml node) { Name = name; if (!string.IsNullOrEmpty(node.Value)) Default = FieldLoader.GetValue<Hotkey>("value", node.Value); var descriptionNode = node.Nodes.FirstOrDefault(n => n.Key == "Description"); if (descriptionNode != null) Description = descriptionNode.Value.Value; var typesNode = node.Nodes.FirstOrDefault(n => n.Key == "Types"); if (typesNode != null) Types = FieldLoader.GetValue<HashSet<string>>("Types", typesNode.Value.Value); } } }
package t::lib::QA::TemplateFilters; use Modern::Perl; our @tt_directives = ( qr{^\s*INCLUDE}, qr{^\s*USE}, qr{^\s*IF}, qr{^\s*UNLESS}, qr{^\s*ELSE}, qr{^\s*ELSIF}, qr{^\s*END}, qr{^\s*SET}, qr{^\s*WHILE}, qr{^\s*FOR}, qr{^\s*FOREACH}, qr{^\s*MACRO}, qr{^\s*SWITCH}, qr{^\s*CASE}, qr{^\s*PROCESS}, qr{^\s*DEFAULT}, qr{^\s*TRY}, qr{^\s*CATCH}, qr{^\s*BLOCK}, qr{^\s*FILTER}, qr{^\s*STOP}, qr{^\s*NEXT}, qr{^\s*LAST}, ); our @tt_methods = ( qr{\.push\(}, ); sub fix_filters { return _process_tt_content( @_ )->{new_content}; } sub missing_filters { return @{_process_tt_content( @_ )->{errors}}; } sub _process_tt_content { my ($content) = @_; my ( $use_raw, $has_use_raw ); my @errors; my @new_lines; my $line_number; for my $line ( split "\n", $content ) { my $new_line = $line; $line_number++; if ( $line =~ m{\[%[^%]+%\]} ) { # handle exceptions first if ( $line =~ m{\|\s*\$raw} ) { # Is the file use the raw filter? $use_raw = 1; } # Do we have Asset without the raw filter? if ( $line =~ m{^\s*\[% Asset} && $line !~ m{\|\s*\$raw} ) { push @errors, { error => 'asset_must_be_raw', line => $line, line_number => $line_number }; $new_line =~ s/\)\s*%]/) | \$raw %]/; $use_raw = 1; push @new_lines, $new_line; next; } $has_use_raw++ if $line =~ m{\[%(\s|-|~)*USE raw(\s|-|~)*%\]}; # Does [% Use raw %] exist? my $e; if ( $line =~ qr{<a href="([^"]+)} ) { my $to_uri_escape = $1; while ( $to_uri_escape =~ m{ \[% (?<pre_chomp>(\s|\-|~)*) (?<tt_block>[^%\-~]+) (?<post_chomp>(\s|\-|~)*) %\]}gmxs ) { ( $new_line, $e ) = process_tt_block($new_line, { %+, filter => 'uri' }); push @errors, { line => $line, line_number => $line_number, error => $e } if $e; } } # Loop on TT blocks while ( $line =~ m{ \[% (?<pre_chomp>(\s|\-|~)*) (?<tt_block>[^%\-~]+) (?<post_chomp>(\s|\-|~)*) %\]}gmxs ) { ( $new_line, $e ) = process_tt_block($new_line, \%+); push @errors, { line => $line, line_number => $line_number, error => $e } if $e; } push @new_lines, $new_line; } else { push @new_lines, $new_line; } } # Adding [% USE raw %] on top if the filter is used @new_lines = ( '[% USE raw %]', @new_lines ) if $use_raw and not $has_use_raw; my $new_content = join "\n", @new_lines; return { errors => \@errors, new_content => $new_content }; } sub process_tt_block { my ( $line, $params ) = @_; my $tt_block = $params->{tt_block}; my $pre_chomp = $params->{pre_chomp}; my $post_chomp = $params->{post_chomp}; my $filter = $params->{filter} || 'html'; my $error; return ( $line, $error ) if # It's a TT directive, no filters needed grep { $tt_block =~ $_ } @tt_directives # It's a TT method or grep { $tt_block =~ $_ } @tt_methods # It is a comment or $tt_block =~ m{^\ # Already escaped with a special filter # We could escape it but should be safe or $tt_block =~ m{\s?\|\s?\$KohaDates[^\|]*$} or $tt_block =~ m{\s?\|\s?\$Price[^\|]*$} or $tt_block =~ m{\s?\|\s?\$HtmlTags[^\|]*$} or $tt_block =~ m{\s?\|\s?\$HtmlId[^\|]*$} # Already escaped correctly with raw or $tt_block =~ m{\|\s?\$raw} # Assignment, maybe we should require to use SET (?) or ( $tt_block =~ m{=} and not $tt_block =~ m{\s\|\s} ) # Already has url or uri filter or $tt_block =~ m{\|\s?ur(l|i)} # Specific for [% foo UNLESS bar %] or $tt_block =~ m{^(?<before>\S+)\s+UNLESS\s+(?<after>\S+)} ; $pre_chomp = $pre_chomp ? $pre_chomp =~ m|-| ? q|- | : $pre_chomp =~ m|~| ? q|~ | : q| | : q| |; $post_chomp = $post_chomp ? $post_chomp =~ m|-| ? q| -| : $post_chomp =~ m|~| ? q| ~| : q| | : q| |; if ( $tt_block =~ m{\s?\|\s?\$KohaDates[^\|]*\|.*$} or $tt_block =~ m{\s?\|\s?\$Price[^\|]*\|.*$} or $tt_block =~ m{\s?\|\s?\$HtmlTags[^\|]*\|.*$} ) { $tt_block =~ s/\s*\|\s*(uri|url|html)\s*$//; # Could be another filter... $line =~ s{ \[% \s*$pre_chomp\s* \Q$tt_block\E\s*\|\s*(uri|url|html) \s*$post_chomp\s* %\] }{[%$pre_chomp$tt_block$post_chomp%]}xms; return ( $line, '<API key>' ); } if ( # Use the uri filter is needed # If html filtered or not filtered $filter ne 'html' and ( $tt_block !~ m{\|} or ($tt_block =~ m{\|\s?html} and not $tt_block =~ m{\|\s?html_entity}) or $tt_block !~ m{\s*|\s*(uri|url)} ) ) { $tt_block =~ s/^\s*|\s*$//g; # trim $tt_block =~ s/\s*\|\s*html\s* $line =~ s{ \[% \s*$pre_chomp\s* \Q$tt_block\E(\s*\|\s*html)? \s*$post_chomp\s* %\] }{[%$pre_chomp$tt_block | uri$post_chomp%]}xms; $error = 'wrong_html_filter'; } elsif ( $tt_block !~ m{\|\s?html} # already has html filter ) { $tt_block =~ s/^\s*|\s*$//g; # trim $line =~ s{ \[% \s*$pre_chomp\s* \Q$tt_block\E \s*$post_chomp\s* %\] }{[%$pre_chomp$tt_block | html$post_chomp%]}xms; $error = 'missing_filter'; } return ( $line, $error ); } 1; =head1 NAME t::lib::QA::TemplateFilters - Module used by tests and QA script to catch missing filters in template files =head1 SYNOPSIS my $content = read_file($filename); my $new_content = t::lib::QA::TemplateFilters::fix_filters($content); my $errors = t::lib::QA::TemplateFilters::missing_filters($content); =head1 DESCRIPTION The goal of this module is to make the subroutine reusable from the QA scripts and to not duplicate the code. =head1 METHODS =head2 fix_filters Take a template content file in parameter and return the same content with the correct (guessed) filters. It will also add the [% USE raw %] statement if it is needed. =head2 missing_filters Take a template content file in parameter and return an arrayref of errors. An error is a hashref with 3 keys, error and line, line_number. * error can be: asset_must_be_raw - When Asset is called without using raw missing_filter - When a TT variable is displayed without filter wrong_html_filter - When a TT variable is using the html filter when uri (or url) should be used instead. * line is the line where the error has been found. * line_number is the line number where the error has been found. =head1 AUTHORS Jonathan Druart <jonathan.druart@bugs.koha-community.org> =head1 COPYRIGHT Copyright 2017 - Koha Development Team =head1 LICENSE This file is part of Koha. Koha 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. Koha 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 Koha; if not, see <http: =cut 1;
#!/usr/bin/perl # Submit standard neutrino event generation jobs for GENIE release validation # The outputs can be compared with outputs from past releases using GENIE's gvld_sample_comp utility. # Sanity checks can be performed using GENIE's gvld_sample_scan utility. # Syntax: # shell% perl <API key>.pl <options> # Options: # --version : GENIE version number # --run : Comma separated list of run numbers # [--arch] : <SL4_32bit, SL5_64bit>, default: SL5_64bit # [--production] : default: <version> # [--cycle] : default: 01 # [--ref-samples] : Path for reference samples, default: no reference samples / no plots will be generated # [--use-valgrind] : default: off # [--batch-system] : <PBS, LSF>, default: PBS # [--queue] : default: prod # [--softw-topdir] : default: /opt/ppd/t2k/softw/GENIE # Examples: # shell% perl <API key>.pl \ # --production 2.5.1_prelease_tests --cycle 01 --version v2.5.1 --run 1001 # shell% perl <API key>.pl \ # --production 2.5.1_prelease_tests --cycle 01 --version v2.5.1 --run 1000,1001,9203 # shell% perl <API key>.pl \ # --production 2.5.1_prelease_tests --cycle 01 --version v2.5.1 --run all # Tested at the RAL/PPD Tier2 PBS batch farm. # Costas Andreopoulos <costas.andreopoulos \at stfc.ac.uk> # STFC, Rutherford Appleton Lab # SAMPLES: # run | nev | init state | energy | processes # nu. | | | (GeV) | enabled # 1000 | 100k | numu + n | 0.5 | all # 1001 | 100k | numu + n | 1 | all # 1002 | 100k | numu + n | 5 | all # 1003 | 100k | numu + n | 50 | all # 1101 | 100k | numubar + p | 1 | all # 1102 | 100k | numubar + p | 5 | all # 1103 | 100k | numubar + p | 50 | all # 2001 | 100k | numu + Fe56 | 1 | all # 2002 | 100k | numu + Fe56 | 5 | all # 2003 | 100k | numu + Fe56 | 50 | all # 2101 | 100k | numubar + Fe56 | 1 | all # 2102 | 100k | numubar + Fe56 | 5 | all # 2103 | 100k | numubar + Fe56 | 50 | all # 9001 | 100k | numu + Fe56 | 5 | DIS charm # 9002 | 100k | numu + Fe56 | 5 | QEL charm # 9101 | 100k | numu + Fe56 | 2 | COH CC+NC # 9201 | 100k | nue + Fe56 | 1 | ve elastic # 9202 | 100k | numu + Fe56 | 1 | ve elastic # 9203 | 50k | numu + Fe56 | 20 | IMD # 9204 | 50k | nuebar + Fe56 | 20 | IMD (annihilation) use File::Path; # inputs $iarg=0; foreach (@ARGV) { if($_ eq '--version') { $genie_version = $ARGV[$iarg+1]; } if($_ eq '--run') { $runnu = $ARGV[$iarg+1]; } if($_ eq '--arch') { $arch = $ARGV[$iarg+1]; } if($_ eq '--production') { $production = $ARGV[$iarg+1]; } if($_ eq '--cycle') { $cycle = $ARGV[$iarg+1]; } if($_ eq '--ref-samples') { $ref_sample_path = $ARGV[$iarg+1]; } if($_ eq '--use-valgrind') { $use_valgrind = $ARGV[$iarg+1]; } if($_ eq '--batch-system') { $batch_system = $ARGV[$iarg+1]; } if($_ eq '--queue') { $queue = $ARGV[$iarg+1]; } if($_ eq '--softw-topdir') { $softw_topdir = $ARGV[$iarg+1]; } $iarg++; } die("** Aborting [Undefined benchmark runs #. Use the --run option]") unless defined $runnu; die("** Aborting [Undefined GENIE version. Use the --version option]") unless defined $genie_version; $use_valgrind = 0 unless defined $use_valgrind; $arch = "SL5_64bit" unless defined $arch; $production = "$genie_version" unless defined $production; $cycle = "01" unless defined $cycle; $batch_system = "PBS" unless defined $batch_system; $queue = "prod" unless defined $queue; $softw_topdir = "/opt/ppd/t2k/softw/GENIE" unless defined $softw_topdir; $ref_sample_path = 0 unless defined $ref_sample_path; $genie_setup = "$softw_topdir/builds/$arch/$genie_version-setup"; $jobs_dir = "$softw_topdir/scratch/vld\_vA-$production\_$cycle"; $xspl_file = "$softw_topdir/data/job_inputs/xspl/gxspl-vA-$genie_version.xml"; $mcseed = 210921029; %nevents_hash = ( '1000' => '100000', '1001' => '100000', '1002' => '100000', '1003' => '100000', '1101' => '100000', '1102' => '100000', '1103' => '100000', '2001' => '100000', '2002' => '100000', '2003' => '100000', '2101' => '100000', '2102' => '100000', '2103' => '100000', '9001' => '100000', '9002' => '100000', '9101' => '100000', '9201' => '50000', '9202' => '50000', '9203' => '50000', '9204' => '50000' ); %nupdg_hash = ( '1000' => '14', '1001' => '14', '1002' => '14', '1003' => '14', '1101' => '-14', '1102' => '-14', '1103' => '-14', '2001' => '14', '2002' => '14', '2003' => '14', '2101' => '-14', '2102' => '-14', '2103' => '-14', '9001' => '14', '9002' => '14', '9101' => '14', '9201' => '12', '9202' => '14', '9203' => '14', '9204' => '-12' ); %tgtpdg_hash = ( '1000' => '1000000010', '1001' => '1000000010', '1002' => '1000000010', '1003' => '1000000010', '1101' => '1000010010', '1102' => '1000010010', '1103' => '1000010010', '2001' => '1000260560', '2002' => '1000260560', '2003' => '1000260560', '2101' => '1000260560', '2102' => '1000260560', '2103' => '1000260560', '9001' => '1000260560', '9002' => '1000260560', '9101' => '1000260560', '9201' => '1000260560', '9202' => '1000260560', '9203' => '1000260560', '9204' => '1000260560' ); %energy_hash = ( '1000' => '0.5', '1001' => '1.0', '1002' => '5.0', '1003' => '50.0', '1101' => '1.0', '1102' => '5.0', '1103' => '50.0', '2001' => '1.0', '2002' => '5.0', '2003' => '50.0', '2101' => '1.0', '2102' => '5.0', '2103' => '50.0', '9001' => '5.0', '9002' => '5.0', '9101' => '2.0', '9201' => '1.0', '9202' => '1.0', '9203' => '20.0', '9204' => '20.0' ); %gevgl_hash = ( '1000' => 'Default', '1001' => 'Default', '1002' => 'Default', '1003' => 'Default', '1101' => 'Default', '1102' => 'Default', '1103' => 'Default', '2001' => 'Default', '2002' => 'Default', '2003' => 'Default', '2101' => 'Default', '2102' => 'Default', '2103' => 'Default', '9001' => 'CharmCCDIS', '9002' => 'CharmCCQE', '9101' => 'COH', '9201' => 'NuEElastic', '9202' => 'NuEElastic', '9203' => 'IMD', '9204' => 'IMD' ); # make the jobs directory mkpath ($jobs_dir, {verbose => 1, mode=>0777}); print "Input runs: $runnu \n"; for my $curr_runnu (keys %gevgl_hash) { print "Checking benchmark run: ...... $curr_runnu \n"; if($runnu=~m/$curr_runnu/ || $runnu eq "all") { print "** matched -> submitting job \n"; # get runnu-dependent info $nev = $nevents_hash {$curr_runnu}; $nu = $nupdg_hash {$curr_runnu}; $tgt = $tgtpdg_hash {$curr_runnu}; $en = $energy_hash {$curr_runnu}; $gevgl = $gevgl_hash {$curr_runnu}; $fntemplate = "$jobs_dir/job_vA-$curr_runnu"; $grep_pipe = "grep -B 20 -A 30 -i \"warn\\|error\\|fatal\""; $valgrind_cmd = "valgrind --tool=memcheck --error-limit=no --leak-check=yes --show-reachable=yes"; $evgen_opt = "-n $nev -e $en -p $nu -t $tgt -r $curr_runnu --seed $mcseed --cross-sections $xspl_file --<API key> $gevgl"; $evgen_cmd = "gevgen $evgen_opt | $grep_pipe &> $fntemplate.evgen.log"; $conv_cmd = "gntpc -f gst -i gntp.$curr_runnu.ghep.root | $grep_pipe &> $fntemplate.conv.log"; $comp_cmd = "gvld_sample_comp -f gntp.$curr_runnu.gst.root -r $ref_sample_path/gntp.$curr_runnu.gst.root | $grep_pipe &> $fntemplate.comp.log"; print "@@ exec: $evgen_cmd \n"; # submit # PBS case if($batch_system eq 'PBS') { $batch_script = "$fntemplate.pbs"; open(PBS, ">$batch_script") or die("Can not create the PBS batch script"); print PBS "#!/bin/bash \n"; print PBS "#PBS -o $fntemplate.pbsout.log \n"; print PBS "#PBS -e $fntemplate.pbserr.log \n"; print PBS "source $genie_setup \n"; print PBS "cd $jobs_dir \n"; print PBS "$evgen_cmd \n"; print PBS "$conv_cmd \n"; if(-d $ref_sample_path) { print PBS "$comp_cmd \n"; } close(PBS); `qsub -q $queue $batch_script`; } #PBS # LSF case if($batch_system eq 'LSF') { $batch_script = "$fntemplate.sh"; open(LSF, ">$batch_script") or die("Can not create the LSF batch script"); print LSF "#!/bin/bash \n"; print LSF "#BSUB-q $queue \n"; print LSF "#BSUB-o $fntemplate.lsfout.log \n"; print LSF "#BSUB-e $fntemplate.lsferr.log \n"; print LSF "source $genie_setup \n"; print LSF "cd $jobs_dir \n"; print LSF "$evgen_cmd \n"; print LSF "$conv_cmd \n"; if(-d $ref_sample_path) { print LSF "$comp_cmd \n"; } close(LSF); `bsub < $batch_script`; } #LSF } }
#ifndef <API key> #define <API key> #include <QtCore/QUrl> #include <QtNetwork/<API key>> namespace Otter { class CookieJar; class <API key>; class NetworkManager final : public <API key> { Q_OBJECT public: enum ResourceMetaData { UnknownMetaData = 0, <API key>, <API key> }; enum ResourceType { OtherType = 0, MainFrameType, SubFrameType, PopupType, StyleSheetType, ScriptType, ImageType, ObjectType, <API key>, XmlHttpRequestType, WebSocketType }; struct ResourceInformation final { QUrl url; QMap<ResourceMetaData, QVariant> metaData; ResourceType resourceType = OtherType; }; explicit NetworkManager(bool isPrivate = false, QObject *parent = nullptr); CookieJar* getCookieJar() const; static ResourceType getResourceType(const QNetworkRequest &request, const QUrl &firstPartyUrl = {}); protected: QNetworkReply* createRequest(Operation operation, const QNetworkRequest &request, QIODevice *outgoingData) override; protected slots: void handle<API key>(QNetworkReply *reply, QAuthenticator *authenticator); void handleProxy<API key>(const QNetworkProxy &proxy, QAuthenticator *authenticator); void handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors); void <API key>(bool isOnline); private: CookieJar *m_cookieJar; friend class <API key>; }; } #endif
package com.krawler.esp.servlets; import com.krawler.common.service.ServiceException; import com.krawler.common.util.KWLErrorMsgs; import com.krawler.common.util.StringUtil; import com.krawler.controller.<API key>; import com.krawler.controller.CustomColumnFactory; import com.krawler.database.DbPool; import com.krawler.database.DbPool.Connection; import com.krawler.utils.json.base.JSONException; import com.krawler.utils.json.base.JSONObject; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.<API key>; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author krawler */ public class CCController extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Connection conn = null; Object result = null; String mname = ""; CustomColumnFactory factory = null; try { conn = DbPool.getConnection(); if (!StringUtil.isNullOrEmpty(request.getParameter("m"))) { // m is method name mname = request.getParameter("m"); factory = new <API key>(); Method methodObj = factory.getClass().getMethod(mname, new Class[]{Connection.class, HttpServletRequest.class}); result = methodObj.invoke(factory, conn, request); } conn.commit(); } catch (<API key> ex) { DbPool.quietRollback(conn); result = KWLErrorMsgs.rsFalseData + ex.getMessage() + "\"}"; }catch (ServiceException ex) { DbPool.quietRollback(conn); result = KWLErrorMsgs.rsFalseData + ex.getMessage() + "\"}"; } catch (<API key> ex) { DbPool.quietRollback(conn); result = KWLErrorMsgs.rsFalseData + ex.getTargetException().getMessage() + "\"}"; } catch (<API key> ex) { DbPool.quietRollback(conn); result = KWLErrorMsgs.rsFalseData + ex.getMessage() + "\"}"; } catch (<API key> ex) { DbPool.quietRollback(conn); result = KWLErrorMsgs.rsFalseData + ex.getMessage() + "\"}"; } catch (SecurityException ex) { DbPool.quietRollback(conn); result = KWLErrorMsgs.rsFalseData + ex.getMessage() + "\"}"; } finally { DbPool.quietClose(conn); try { if (!factory.isFormSubmit()) { JSONObject jbj = new com.krawler.utils.json.base.JSONObject(); jbj.put("valid", "true"); jbj.put("data", result.toString()); out.println(jbj.toString()); } else { out.println(result); } } catch (JSONException ex) { Logger.getLogger(CCController.class.getName()).log(Level.SEVERE, null, ex); } out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package net.minecraft.client.tutorial; import net.minecraft.client.gui.toasts.TutorialToast; import net.minecraft.util.MouseHelper; import net.minecraft.util.MovementInput; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.<API key>; import net.minecraft.world.GameType; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class MovementStep implements ITutorialStep { private static final ITextComponent MOVE_TITLE = new <API key>("tutorial.move.title", new Object[] {Tutorial.<API key>("forward"), Tutorial.<API key>("left"), Tutorial.<API key>("back"), Tutorial.<API key>("right")}); private static final ITextComponent MOVE_DESCRIPTION = new <API key>("tutorial.move.description", new Object[] {Tutorial.<API key>("jump")}); private static final ITextComponent LOOK_TITLE = new <API key>("tutorial.look.title", new Object[0]); private static final ITextComponent LOOK_DESCRIPTION = new <API key>("tutorial.look.description", new Object[0]); private final Tutorial tutorial; private TutorialToast moveToast; private TutorialToast lookToast; private int timeWaiting; private int timeMoved; private int timeLooked; private boolean moved; private boolean turned; private int moveCompleted = -1; private int lookCompleted = -1; public MovementStep(Tutorial tutorial) { this.tutorial = tutorial; } public void update() { ++this.timeWaiting; if (this.moved) { ++this.timeMoved; this.moved = false; } if (this.turned) { ++this.timeLooked; this.turned = false; } if (this.moveCompleted == -1 && this.timeMoved > 40) { if (this.moveToast != null) { this.moveToast.hide(); this.moveToast = null; } this.moveCompleted = this.timeWaiting; } if (this.lookCompleted == -1 && this.timeLooked > 40) { if (this.lookToast != null) { this.lookToast.hide(); this.lookToast = null; } this.lookCompleted = this.timeWaiting; } if (this.moveCompleted != -1 && this.lookCompleted != -1) { if (this.tutorial.getGameType() == GameType.SURVIVAL) { this.tutorial.setStep(TutorialSteps.FIND_TREE); } else { this.tutorial.setStep(TutorialSteps.NONE); } } if (this.moveToast != null) { this.moveToast.setProgress((float)this.timeMoved / 40.0F); } if (this.lookToast != null) { this.lookToast.setProgress((float)this.timeLooked / 40.0F); } if (this.timeWaiting >= 100) { if (this.moveCompleted == -1 && this.moveToast == null) { this.moveToast = new TutorialToast(TutorialToast.Icons.MOVEMENT_KEYS, MOVE_TITLE, MOVE_DESCRIPTION, true); this.tutorial.getMinecraft().getToastGui().add(this.moveToast); } else if (this.moveCompleted != -1 && this.timeWaiting - this.moveCompleted >= 20 && this.lookCompleted == -1 && this.lookToast == null) { this.lookToast = new TutorialToast(TutorialToast.Icons.MOUSE, LOOK_TITLE, LOOK_DESCRIPTION, true); this.tutorial.getMinecraft().getToastGui().add(this.lookToast); } } } public void onStop() { if (this.moveToast != null) { this.moveToast.hide(); this.moveToast = null; } if (this.lookToast != null) { this.lookToast.hide(); this.lookToast = null; } } /** * Handles the player movement * * @param input The movement inputs of the player */ public void handleMovement(MovementInput input) { if (input.forwardKeyDown || input.backKeyDown || input.leftKeyDown || input.rightKeyDown || input.jump) { this.moved = true; } } /** * Handles mouse mouvement * * @param mouseHelperIn A MouseHelper providing you informations about the player mouse */ public void handleMouse(MouseHelper mouseHelperIn) { if ((double)MathHelper.abs(mouseHelperIn.deltaX) > 0.01D || (double)MathHelper.abs(mouseHelperIn.deltaY) > 0.01D) { this.turned = true; } } }
'use strict'; var Component = require('../component'); /** * Base progress bar implementation. * * @constructor * @extends Component * * @param {Object} [config={}] init parameters (all inherited from the parent) * @param {number} [config.value=0] initial value * @param {number} [config.max=100] max progress value * @param {number} [config.min=0] min progress value * * @example * var ProgressBar = require('stb/ui/progress.bar'), * progressBar = new ProgressBar({ * min: -100, * max: 200, * events: { * done: function () { * debug.log('ProgressBar: done'); * }, * change: function ( data ) { * debug.log('ProgressBar: change to ' + data.curr + ' from ' + data.prev); * } * } * }); */ function ProgressBar ( config ) { // sanitize config = config || {}; if ( DEBUG ) { if ( typeof config !== 'object' ) { throw new Error(__filename + ': wrong config type'); } // init parameters checks if ( config.className && typeof config.className !== 'string' ) { throw new Error(__filename + ': wrong or empty config.className'); } } /** * Max progress value. * * @type {number} */ this.max = 100; /** * Min progress value. * * @type {number} */ this.min = 0; /** * Initial progress position. * * @type {number} */ this.value = 0; /** * Value of the one percent step * * @type {number} */ this.step = 1; // can't accept focus config.focusable = config.focusable || false; // set default className if classList property empty or undefined config.className = 'progressBar ' + (config.className || ''); // parent constructor call Component.call(this, config); // insert bar line this.$value = this.$body.appendChild(document.createElement('div')); // correct CSS class name this.$value.className = 'value'; // component setup this.init(config); } // inheritance ProgressBar.prototype = Object.create(Component.prototype); ProgressBar.prototype.constructor = ProgressBar; /** * Set position of the given value. * Does nothing in case when progress is end and passed value is more than max value. * * @param {number} value new value to set * @return {boolean} operation result * * @fires module:stb/ui/progress.bar~ProgressBar#done * @fires module:stb/ui/progress.bar~ProgressBar#change */ ProgressBar.prototype.set = function ( value ) { var prevValue = this.value; if ( DEBUG ) { if ( arguments.length !== 1 ) { throw new Error(__filename + ': wrong arguments number'); } if ( Number(value) !== value ) { throw new Error(__filename + ': value must be a number'); } } // value changed but in the given range if ( this.value !== value && value <= this.max && value >= this.min ) { // set new value this.value = value; // get value in percents value = Math.abs(this.value - this.min) / this.step; if ( value === 100 ) { // there are some listeners if ( this.events['done'] ) { /** * Set progress to its maximum value. * * @event module:stb/ui/progress.bar~ProgressBar#done */ this.emit('done'); } } // set progress bar width this.$value.style.width = value + '%'; // there are some listeners if ( this.events['change'] ) { /** * Update progress value. * * @event module:stb/ui/progress.bar~ProgressBar#change * * @type {Object} * @property {number} prev old/previous progress value * @property {number} curr new/current progress value */ this.emit('change', {curr: this.value, prev: prevValue}); } return true; } // nothing was done return false; }; /** * Init or re-init current max or/and min or/and value. * * @param {Object} config init parameters (subset of constructor config params) */ ProgressBar.prototype.init = function ( config ) { if ( DEBUG ) { if ( arguments.length !== 1 ) { throw new Error(__filename + ': wrong arguments number'); } if ( typeof config !== 'object' ) { throw new Error(__filename + ': wrong config type'); } } // set max progress value if ( config.max !== undefined ) { if ( DEBUG ) { if ( Number(config.max) !== config.max ) { throw new Error(__filename + ': config.max value must be a number'); } } // apply this.max = config.max; } // set min progress value if ( config.min !== undefined ) { if ( DEBUG ) { if ( Number(config.min) !== config.min ) { throw new Error(__filename + ': config.min value must be a number'); } } // apply this.min = config.min; } if ( DEBUG ) { if ( this.min >= this.max ) { throw new Error(__filename + ': this.min value must be less than this.max'); } } // set actual progress value if ( config.value !== undefined ) { if ( DEBUG ) { if ( Number(config.value) !== config.value ) { throw new Error(__filename + ': config.value must be a number'); } if ( config.value > this.max ) { throw new Error(__filename + ': config.value more than config.maximum'); } if ( config.value < this.min ) { throw new Error(__filename + ': config.value less than config.minimum'); } } // apply this.value = config.value; } this.step = Math.abs(this.max - this.min) / 100; // init bar size, (this.min - this.value) - calculate distance from start this.$value.style.width = (Math.abs(this.min - this.value) / this.step) + '%'; }; if ( DEBUG ) { // expose to the global scope window.<API key> = ProgressBar; } // public module.exports = ProgressBar;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; namespace NeoComp.Threading { [ContractClass(typeof(<API key>))] public interface ISynchronized { SyncContext SyncRoot { get; } } [ContractClassFor(typeof(ISynchronized))] sealed class <API key> : ISynchronized { SyncContext ISynchronized.SyncRoot { get { return null; } } [<API key>] private void ObjectInvariant() { ISynchronized s = this; Contract.Invariant(s.SyncRoot != null); } } }
<?php namespace Drupal\<API key>\Plugin\views\field; use Drupal\<API key>\Entity\<API key>; use Drupal\views\Plugin\views\field\FieldPluginBase; use Drupal\views\ResultRow; /** * Display counter of Register clicks. * * @ViewsField("<API key>") */ class RegisterCounter extends FieldPluginBase { /** * {@inheritdoc} */ public function render(ResultRow $values) { /** @var \Drupal\openy_repeat\Entity\ProgramSearchLog $revision */ $log = $values->_entity; $query = \Drupal::entityTypeManager()->getStorage('<API key>')->getQuery(); $details_ids = $query ->condition('log_id', $log->id()) ->condition('type', <API key>::TYPE_REGISTER) ->execute(); return ['counter' => [ '#markup' => count($details_ids), ]]; } /** * {@inheritdoc} */ public function query() {} }
<!DOCTYPE html> <html> <head> <title>Donate - privacytools.io</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="favicon.ico" type="image/ico"> </head> <body> <center> <br> <p> <a href="https: </p> <h1>Please Donate</h1> <p> Our website is free of advertisement and not affiliated with any listed providers.<br/> Your donation will cover our cost for server, domains, coffee, beer and pizza. </p> <p> <h2>Bitcoin:</h2> <p> <a href="bitcoin:<API key>?message=privacytools.io%20(Coffee,%20Beer%20and%20Pizza)" target="_blank"><img src="img/layout/qr.png"></a> </p> <p> <input type="text" value="<API key>" onclick="this.focus();this.select()" class="form-control input-lg" style="width:400px;"> <span class="help-block">For easy copy and paste. <a href="bitcoin:<API key>?message=privacytools.io%20(Coffee,%20Beer%20and%20Pizza)">Or use this link.</a></span> </p> </p> <br> <p> <a href="https: </p> <h3>Thanks for your support. You are awesome!</h3> <p> <img src="img/misc/smile.png" class="img-responsive" alt="Smile"> </p> </center> </body> </html>
<?php $class = ( 'c' === get_user_setting( 'basismt' . get_the_ID() ) ) ? 'closed' : 'opened'; ?> <div class="basis-menu-product basis-menu-product-<?php echo esc_attr( $class ); ?>" id="basis-menu-product"> <div class="<API key>"> <ul class="<API key>"> <?php foreach ( <API key>()-><API key>() as $id => $item ) : ?> <li class="<API key>"> <a href="#" title="<?php esc_attr_e( 'Add', 'basis' ); ?>" class="<API key>" id="<API key>-<?php echo esc_attr( $id ); ?>" data-section="<?php echo esc_attr( $id ); ?>"> <div class="<API key> clear"> <span class="<API key>"></span> </div> <div class="<API key>"> <h4> <?php echo esc_html( $item['label'] ); ?> </h4> <p> <?php echo esc_html( $item['description'] ); ?> </p> </div> </a> </li> <?php endforeach; ?> </ul> </div> <div class="<API key>"> <a href="#" class="<API key>"> <span><?php _e( 'Add New Section', 'basis' ); ?></span> </a> </div> </div>
using System; using System.ComponentModel; using System.Windows.Forms; using Meridian59.Protocol.Events; using Meridian59.Protocol.GameMessages; using Meridian59.Data.Models; using Meridian59.Common.Events; namespace Meridian59.AdminUI.Viewers { <summary> View for Data.Models.AdminInfo </summary> public partial class AdminInfoView : UserControl { <summary> Will be raised when the object wants to send a GameMessage instance </summary> public event <API key> MessageSend; protected AdminInfo dataSource; <summary> The model to be shown in the View </summary> [<API key>(<API key>.Hidden), DefaultValue(null), Browsable(true)] public AdminInfo DataSource { get { return dataSource; } set { if (dataSource != value) { if (dataSource != null) { dataSource.ServerResponses.ListChanged -= <API key>; dataSource.TrackedObjects.ListChanged -= <API key>; } dataSource = value; if (dataSource != null) { dataSource.ServerResponses.ListChanged += <API key>; dataSource.TrackedObjects.ListChanged += <API key>; } } } } <summary> Constructor </summary> public AdminInfoView() { InitializeComponent(); // register disposed event this.Disposed += OnDisposed; // add default commands txtCommand.<API key>.AddRange(AdminInfo.DEFAULTCOMMANDS); } protected void OnDisposed(object sender, EventArgs e) { // detach listeners if (dataSource != null) { dataSource.ServerResponses.ListChanged -= <API key>; dataSource.TrackedObjects.ListChanged -= <API key>; } } protected void OnCommandKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) { e.Handled = true; e.SuppressKeyPress = true; } } protected void OnCommandKeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) { string s = txtCommand.Text.TrimEnd().TrimStart(); ReqAdminMessage msg = new ReqAdminMessage(s); if (MessageSend != null) MessageSend(this, new <API key>(msg)); // track it in autocompletion txtCommand.<API key>.Add(s); // prepare for next command txtCommand.Clear(); } } protected void OnCommandKeyPress(object sender, KeyPressEventArgs e) { } protected void <API key>(object sender, <API key> e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: txtConsole.AppendText(dataSource.ServerResponses[e.NewIndex] + Environment.NewLine); txtConsole.ScrollToCaret(); break; case ListChangedType.Reset: txtConsole.Clear(); break; } } protected void <API key>(object sender, <API key> e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: AdminInfoObject obj = dataSource.TrackedObjects[e.NewIndex]; // create view usercontrol AdminInfoObjectView view = new AdminInfoObjectView(); view.Dock = DockStyle.Fill; view.DataSource = dataSource.TrackedObjects[e.NewIndex]; view.Close += <API key>; view.CommandSend += <API key>; // create tabpage and add view TabPage tabPage = new TabPage(); tabPage.Text = "(" + obj.ID.ToString() + ") " + obj.ClassName; tabPage.Controls.Add(view); // add tabpage an set active tabObjects.TabPages.Add(tabPage); tabObjects.SelectedTab = tabPage; break; case ListChangedType.ItemDeleted: break; case ListChangedType.Reset: tabObjects.TabPages.Clear(); break; } } protected void <API key>(object sender, StringEventArgs e) { ReqAdminMessage msg = new ReqAdminMessage(e.Value); if (MessageSend != null) MessageSend(this, new <API key>(msg)); } protected void <API key>(object sender, EventArgs e) { foreach(TabPage tabPage in tabObjects.TabPages) if (tabPage.Controls.Contains((AdminInfoObjectView)sender)) tabObjects.TabPages.Remove(tabPage); } protected void OnClearLogClick(object sender, EventArgs e) { dataSource.ServerResponses.Clear(); } } }
#ifndef LIBOPENCM3_RNG_H #define LIBOPENCM3_RNG_H #include <libopencm3/stm32/memorymap.h> #include <libopencm3/cm3/common.h> /* Control register */ #define RNG_CR MMIO32(RNG_BASE + 0x00) /* Status register */ #define RNG_SR MMIO32(RNG_BASE + 0x04) /* Data register */ #define RNG_DR MMIO32(RNG_BASE + 0x08) /* RNG ENABLE */ #define RNG_CR_EN (1 << 2) /* RNG interupt enable */ #define RNG_CR_IE (1 << 3) /* Data ready */ #define RNG_SR_DRDY (1 << 0) /* Clock error current status */ #define RNG_SR_CECS (1 << 1) /* Seed error current status */ #define RNG_SR_SECS (1 << 2) /* Clock error interup status */ #define RNG_SR_CEIS (1 << 5) /* Seed error interup status */ #define RNG_SR_SEIS (1 << 6) #endif
package org.omnirom.omniswitch.ui; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Point; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Handler; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.TextView; import org.omnirom.omniswitch.PackageManager; import org.omnirom.omniswitch.SettingsActivity; import org.omnirom.omniswitch.SwitchConfiguration; import org.omnirom.omniswitch.SwitchManager; import org.omnirom.omniswitch.Utils; import org.omnirom.omniswitch.R; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class <API key> extends HorizontalListView { private static final String TAG = "<API key>"; private static final boolean DEBUG = false; private SwitchConfiguration mConfiguration; private FavoriteListAdapter <API key>; private boolean mTransparent; protected List<String> mFavoriteList; private SwitchManager mRecentsManager; private Typeface mLabelFont; public class FavoriteListAdapter extends ArrayAdapter<String> { public FavoriteListAdapter(Context context, int resource, List<String> values) { super(context, R.layout.package_item, resource, values); } @Override public View getView(int position, View convertView, ViewGroup parent) { PackageTextView item = null; if (convertView == null) { item = <API key>(); } else { item = (PackageTextView) convertView; } String intent = getItem(position); PackageManager.PackageItem packageItem = PackageManager .getInstance(mContext).getPackageItem(intent); item.setIntent(packageItem.getIntent()); if (mConfiguration.mShowLabels) { item.setText(packageItem.getTitle()); } else { item.setText(""); } Drawable d = BitmapCache.getInstance(mContext).<API key>(getResources(), packageItem, mConfiguration); d.setBounds(0, 0, mConfiguration.mIconSizePx, mConfiguration.mIconSizePx); item.<API key>(null, d, null, null); return item; } } public <API key>(Context context, AttributeSet attrs) { super(context, attrs); mConfiguration = SwitchConfiguration.getInstance(mContext); mLabelFont = Typeface.create("<API key>", Typeface.NORMAL); mFavoriteList = new ArrayList<String>(); <API key> = new FavoriteListAdapter(mContext, android.R.layout.<API key>, mFavoriteList); setAdapter(<API key>); <API key>(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { doOnCLickAction(position); } }); <API key>(new AdapterView.<API key>() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { doOnLongClickAction(position, view); return true; } }); } public void setTransparentMode(boolean value) { mTransparent = value; } public void setRecentsManager(SwitchManager recentsManager) { mRecentsManager = recentsManager; } protected PackageTextView <API key>() { PackageTextView item = new PackageTextView(mContext); if (mTransparent) { item.setTextColor(mContext.getResources().getColor(R.color.text_color_dark)); item.setShadowLayer(5, 0, 0, Color.BLACK); } else { if (mConfiguration.mBgStyle == SwitchConfiguration.BgStyle.SOLID_LIGHT) { item.setTextColor(mContext.getResources().getColor(R.color.text_color_light)); item.setShadowLayer(0, 0, 0, Color.BLACK); } else { item.setTextColor(mContext.getResources().getColor(R.color.text_color_dark)); item.setShadowLayer(5, 0, 0, Color.BLACK); } } item.setTextSize(mConfiguration.mLabelFontSize); item.setEllipsize(TextUtils.TruncateAt.END); item.setGravity(Gravity.CENTER); item.setLayoutParams(getListItemParams()); item.setPadding(0, mConfiguration.mIconBorderPx, 0, 0); item.setMaxLines(1); item.setTypeface(mLabelFont); if (mTransparent) { item.<API key>(R.drawable.ripple_dark); } else { item.<API key>(mConfiguration.mBgStyle == SwitchConfiguration.BgStyle.SOLID_LIGHT ? R.drawable.ripple_dark : R.drawable.ripple_light); } return item; } public void updatePrefs(SharedPreferences prefs, String key) { if (DEBUG) { Log.d(TAG, "updatePrefs " + key); } if (key != null && key.equals(SettingsActivity.PREF_FAVORITE_APPS)) { updateFavoritesList(); } if (key != null && Utils.<API key>(key)) { setAdapter(<API key>); } if (key != null && key.equals(PackageManager.<API key>)) { <API key>.<API key>(); } } public void init() { updateFavoritesList(); } private LinearLayout.LayoutParams getListItemParams() { return new LinearLayout.LayoutParams(mConfiguration.mMaxWidth + mConfiguration.<API key>, mConfiguration.getItemMaxHeight()); } private void updateFavoritesList() { Utils.updateFavoritesList(mContext, mConfiguration, mFavoriteList); if (DEBUG) { Log.d(TAG, "updateFavoritesList " + mFavoriteList); } <API key>.<API key>(); } protected void doOnCLickAction(int position) { String intent = mFavoriteList.get(position); if (mRecentsManager != null) { mRecentsManager.<API key>(intent, true); } else { SwitchManager.<API key>(mContext, intent); } } protected void doOnLongClickAction(int position, View view) { String intent = mFavoriteList.get(position); PackageManager.PackageItem packageItem = PackageManager .getInstance(mContext).getPackageItem(intent); <API key>(packageItem, view); } private void <API key>(final PackageManager.PackageItem packageItem, View view) { ContextMenuUtils.<API key>(mContext, packageItem, view, mRecentsManager, mFavoriteList); } }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>DbSequence::initial_value()</title> <link rel="stylesheet" href="apiReference.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Berkeley DB C++ API Reference" /> <link rel="up" href="seq.html" title="Chapter 12.  The DbSequence Handle" /> <link rel="prev" href="seqget_range.html" title="DbSequence::get_range()" /> <link rel="next" href="seqopen.html" title="DbSequence::open()" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 12.1.6.1</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">DbSequence::initial_value()</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="seqget_range.html">Prev</a> </td> <th width="60%" align="center">Chapter 12. The DbSequence Handle </th> <td width="20%" align="right"> <a accesskey="n" href="seqopen.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="seqinitial_value"></a>DbSequence::initial_value()</h2> </div> </div> </div> <pre class="programlisting">#include &lt;db_cxx.h&gt; int DbSequence::initial_value(db_seq_t value);</pre> <p> Set the initial value for a sequence. This call is only effective when the sequence is being created. </p> <p> The <code class="methodname">DbSequence::initial_value()</code> method may not be called after the <a class="xref" href="seqopen.html" title="DbSequence::open()">DbSequence::open()</a> method is called. </p> <p> The <code class="methodname">DbSequence::initial_value()</code> <span> <span> method either returns a non-zero error value or throws an exception that encapsulates a non-zero error value on failure, and returns 0 on success. </span> </span> </p> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp5957504"></a>Parameters</h3> </div> </div> </div> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="idp5956856"></a>value</h4> </div> </div> </div> <p> The initial value to set. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp5958584"></a>Errors</h3> </div> </div> </div> <p> The <code class="methodname">DbSequence::initial_value()</code> <span> <span> method may fail and throw a <a class="link" href="dbexception.html" title="Chapter 6. The DbException Class">DbException</a> exception, encapsulating one of the following non-zero errors, or return one of the following non-zero errors: </span> </span> </p> <div class="sect3" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h4 class="title"><a id="idp5962224"></a>EINVAL</h4> </div> </div> </div> <p> An invalid flag value or parameter was specified. </p> </div> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp5960928"></a>Class</h3> </div> </div> </div> <p> <a class="link" href="seq.html" title="Chapter 12.  The DbSequence Handle">DbSequence</a> </p> </div> <div class="sect2" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h3 class="title"><a id="idp5956640"></a>See Also</h3> </div> </div> </div> <p> <a class="xref" href="seq.html#seqlist" title="Sequences and Related Methods">Sequences and Related Methods</a> </p> </div> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="seqget_range.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="seq.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="seqopen.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">DbSequence::get_range() </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> DbSequence::open()</td> </tr> </table> </div> </body> </html>
#include "<API key>.h" static <API key> <API key> = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 5, 5, 1, 27 } /* (SIZE(1..27)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t <API key>[] = { { ATF_POINTER, 0, 0, (<API key> | (16 << 2)), 0, &<API key>, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "" }, }; static ber_tlv_tag_t <API key>[] = { (<API key> | (16 << 2)) }; static <API key> <API key> = { sizeof(struct <API key>), offsetof(struct <API key>, _asn_ctx), 0, /* XER encoding is <API key> */ }; <API key> <API key> = { "<API key>", "<API key>", SEQUENCE_OF_free, SEQUENCE_OF_print, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, 0, /* Use generic outmost tag fetcher */ <API key>, sizeof(<API key>) /sizeof(<API key>[0]), <API key>, /* Same as above */ sizeof(<API key>) /sizeof(<API key>[0]), &<API key>, <API key>, 1, /* Single element */ &<API key> /* Additional specs */ };
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include "utils/tracers/<API key>.hpp" #include <boost/filesystem.hpp> #include <boost/test/output_test_stream.hpp> #include "../../tests-common.hpp" namespace ns3 { namespace ndn { const boost::filesystem::path TEST_TRACE = boost::filesystem::path(TEST_CONFIG_PATH) / "trace.txt"; class <API key> : public <API key> { public: <API key>() { boost::filesystem::create_directories(TEST_CONFIG_PATH); // setting default parameters for PointToPoint links and channels Config::SetDefault("ns3::<API key>::DataRate", StringValue("10Mbps")); Config::SetDefault("ns3::PointToPointChannel::Delay", StringValue("10ms")); Config::SetDefault("ns3::QueueBase::MaxSize", StringValue("20p")); createTopology({ {"1", "2"}, {"2", "3"} }); addRoutes({ {"1", "2", "/prefix", 1}, {"2", "3", "/prefix", 1} }); addApps({ {"1", "ns3::ndn::ConsumerCbr", {{"Prefix", "/prefix"}, {"Frequency", "1"}}, "1s", "1.9s"}, // send just one packet // Second consumer will capture effect of the bug #2764 {"2", "ns3::ndn::ConsumerCbr", {{"Prefix", "/prefix"}, {"Frequency", "1"}}, "2s", "100s"}, {"3", "ns3::ndn::Producer", {{"Prefix", "/prefix"}, {"PayloadSize", "1024"}}, "0s", "100s"} }); } ~<API key>() { boost::filesystem::remove(TEST_TRACE); AppDelayTracer::Destroy(); // additional cleanup } }; <API key>(<API key>, <API key>) <API key>(InstallAll) { AppDelayTracer::InstallAll(TEST_TRACE.string()); Simulator::Stop(Seconds(4)); Simulator::Run(); AppDelayTracer::Destroy(); // to force log to be written std::ifstream t(TEST_TRACE.string().c_str()); std::stringstream buffer; buffer << t.rdbuf(); BOOST_CHECK_EQUAL(buffer.str(), R"STR(Time Node AppId SeqNo Type DelayS DelayUS RetxCount HopCount 1.04177 1 0 0 LastDelay 0.0417664 41766.4 1 2 1.04177 1 0 0 FullDelay 0.0417664 41766.4 1 2 2 2 0 0 LastDelay 0 0 1 1 2 2 0 0 FullDelay 0 0 1 1 3.02088 2 0 1 LastDelay 0.0208832 20883.2 1 1 3.02088 2 0 1 FullDelay 0.0208832 20883.2 1 1 )STR"); } <API key>(<API key>) { NodeContainer nodes; nodes.Add(getNode("1")); AppDelayTracer::Install(nodes, TEST_TRACE.string()); Simulator::Stop(Seconds(4)); Simulator::Run(); AppDelayTracer::Destroy(); // to force log to be written std::ifstream t(TEST_TRACE.string().c_str()); std::stringstream buffer; buffer << t.rdbuf(); BOOST_CHECK_EQUAL(buffer.str(), R"STR(Time Node AppId SeqNo Type DelayS DelayUS RetxCount HopCount 1.04177 1 0 0 LastDelay 0.0417664 41766.4 1 2 1.04177 1 0 0 FullDelay 0.0417664 41766.4 1 2 )STR"); } <API key>(InstallNode) { AppDelayTracer::Install(getNode("2"), TEST_TRACE.string()); Simulator::Stop(Seconds(4)); Simulator::Run(); AppDelayTracer::Destroy(); // to force log to be written std::ifstream t(TEST_TRACE.string().c_str()); std::stringstream buffer; buffer << t.rdbuf(); BOOST_CHECK_EQUAL(buffer.str(), R"STR(Time Node AppId SeqNo Type DelayS DelayUS RetxCount HopCount 2 2 0 0 LastDelay 0 0 1 1 2 2 0 0 FullDelay 0 0 1 1 3.02088 2 0 1 LastDelay 0.0208832 20883.2 1 1 3.02088 2 0 1 FullDelay 0.0208832 20883.2 1 1 )STR"); } <API key>(<API key>) { auto output = make_shared<boost::test_tools::output_test_stream>(); Ptr<AppDelayTracer> tracer = AppDelayTracer::Install(getNode("2"), output); Simulator::Stop(Seconds(4)); Simulator::Run(); tracer = nullptr; // destroy tracer BOOST_CHECK(output->is_equal( R"STR(2 2 0 0 LastDelay 0 0 1 1 2 2 0 0 FullDelay 0 0 1 1 3.02088 2 0 1 LastDelay 0.0208832 20883.2 1 1 3.02088 2 0 1 FullDelay 0.0208832 20883.2 1 1 )STR")); } <API key>() } // namespace ndn } // namespace ns3
/* * Implementation of registry frontend view functions. * Functions moved from reg_frontend.c to minimize linker deps. */ #include "includes.h" #include "system/passwd.h" /* uid_wrapper */ #include "registry.h" #include "reg_dispatcher.h" #include "../libcli/security/security.h" #undef DBGC_CLASS #define DBGC_CLASS DBGC_REGISTRY static const struct generic_mapping reg_generic_map = { REG_KEY_READ, REG_KEY_WRITE, REG_KEY_EXECUTE, REG_KEY_ALL }; static WERROR <API key>(TALLOC_CTX *ctx, struct security_descriptor **psd) { struct security_ace ace[3]; size_t i = 0; struct security_descriptor *sd; struct security_acl *theacl; size_t sd_size; /* basic access for Everyone */ init_sec_ace(&ace[i++], &global_sid_World, <API key>, REG_KEY_READ, 0); /* Full Access 'BUILTIN\Administrators' */ init_sec_ace(&ace[i++], &<API key>, <API key>, REG_KEY_ALL, 0); /* Full Access 'NT Authority\System' */ init_sec_ace(&ace[i++], &global_sid_System, <API key>, REG_KEY_ALL, 0); /* create the security descriptor */ theacl = make_sec_acl(ctx, NT4_ACL_REVISION, i, ace); if (theacl == NULL) { return WERR_NOMEM; } sd = make_sec_desc(ctx, SD_REVISION, <API key>, &<API key>, &global_sid_System, NULL, theacl, &sd_size); if (sd == NULL) { return WERR_NOMEM; } *psd = sd; return WERR_OK; } bool store_reg_keys(struct registry_key_handle *key, struct regsubkey_ctr *subkeys) { if (key->ops && key->ops->store_subkeys) return key->ops->store_subkeys(key->name, subkeys); return false; } bool store_reg_values(struct registry_key_handle *key, struct regval_ctr *val) { if (key->ops && key->ops->store_values) return key->ops->store_values(key->name, val); return false; } WERROR create_reg_subkey(struct registry_key_handle *key, const char *subkey) { if (key->ops && key->ops->create_subkey) { return key->ops->create_subkey(key->name, subkey); } return WERR_NOT_SUPPORTED; } WERROR delete_reg_subkey(struct registry_key_handle *key, const char *subkey, bool lazy) { if (key->ops && key->ops->delete_subkey) { return key->ops->delete_subkey(key->name, subkey, lazy); } return WERR_NOT_SUPPORTED; } int fetch_reg_keys(struct registry_key_handle *key, struct regsubkey_ctr *subkey_ctr) { int result = -1; if (key->ops && key->ops->fetch_subkeys) result = key->ops->fetch_subkeys(key->name, subkey_ctr); return result; } int fetch_reg_values(struct registry_key_handle *key, struct regval_ctr *val) { int result = -1; DEBUG(10, ("fetch_reg_values called for key '%s' (ops %p)\n", key->name, (key->ops) ? (void *)key->ops : NULL)); if (key->ops && key->ops->fetch_values) result = key->ops->fetch_values(key->name, val); return result; } bool regkey_access_check(struct registry_key_handle *key, uint32 requested, uint32 *granted, const struct security_token *token ) { struct security_descriptor *sec_desc; NTSTATUS status; WERROR err; /* root free-pass, like we have on all other pipes like samr, lsa, etc. */ if (geteuid() == sec_initial_uid()) { *granted = REG_KEY_ALL; return true; } /* use the default security check if the backend has not defined its * own */ if (key->ops && key->ops->reg_access_check) { return key->ops->reg_access_check(key->name, requested, granted, token); } err = regkey_get_secdesc(talloc_tos(), key, &sec_desc); if (!W_ERROR_IS_OK(err)) { return false; } se_map_generic( &requested, &reg_generic_map ); status =se_access_check(sec_desc, token, requested, granted); TALLOC_FREE(sec_desc); if (!NT_STATUS_IS_OK(status)) { return false; } return NT_STATUS_IS_OK(status); } WERROR regkey_get_secdesc(TALLOC_CTX *mem_ctx, struct registry_key_handle *key, struct security_descriptor **psecdesc) { struct security_descriptor *secdesc; WERROR werr; if (key->ops && key->ops->get_secdesc) { werr = key->ops->get_secdesc(mem_ctx, key->name, psecdesc); if (W_ERROR_IS_OK(werr)) { return WERR_OK; } } werr = <API key>(mem_ctx, &secdesc); if (!W_ERROR_IS_OK(werr)) { return werr; } *psecdesc = secdesc; return WERR_OK; } WERROR regkey_set_secdesc(struct registry_key_handle *key, struct security_descriptor *psecdesc) { if (key->ops && key->ops->set_secdesc) { return key->ops->set_secdesc(key->name, psecdesc); } return WERR_ACCESS_DENIED; } /** * Check whether the in-memory version of the subkyes of a * registry key needs update from disk. */ bool <API key>(struct registry_key_handle *key, struct regsubkey_ctr *subkeys) { if (key->ops && key->ops->subkeys_need_update) { return key->ops->subkeys_need_update(subkeys); } return false; } /** * Check whether the in-memory version of the values of a * registry key needs update from disk. */ bool <API key>(struct registry_key_handle *key, struct regval_ctr *values) { if (key->ops && key->ops->values_need_update) { return key->ops->values_need_update(values); } return false; }
#include <config.h> #include "system.h" #include <bitsetv.h> #include "getargs.h" #include "relation.h" void relation_print (relation r, relation_node size, FILE *out) { relation_node i; relation_node j; for (i = 0; i < size; ++i) { fprintf (out, "%3lu: ", (unsigned long int) i); if (r[i]) for (j = 0; r[i][j] != END_NODE; ++j) fprintf (out, "%3lu ", (unsigned long int) r[i][j]); fputc ('\n', out); } fputc ('\n', out); } static relation R; static relation_nodes INDEX; static relation_nodes VERTICES; static relation_node top; static relation_node infinity; static bitsetv F; static void traverse (relation_node i) { relation_node j; relation_node height; VERTICES[++top] = i; INDEX[i] = height = top; if (R[i]) for (j = 0; R[i][j] != END_NODE; ++j) { if (INDEX[R[i][j]] == 0) traverse (R[i][j]); if (INDEX[i] > INDEX[R[i][j]]) INDEX[i] = INDEX[R[i][j]]; bitset_or (F[i], F[i], F[R[i][j]]); } if (INDEX[i] == height) for (;;) { j = VERTICES[top INDEX[j] = infinity; if (i == j) break; bitset_copy (F[j], F[i]); } } void relation_digraph (relation r, relation_node size, bitsetv *function) { relation_node i; infinity = size + 2; INDEX = xcalloc (size + 1, sizeof *INDEX); VERTICES = xnmalloc (size + 1, sizeof *VERTICES); top = 0; R = r; F = *function; for (i = 0; i < size; i++) if (INDEX[i] == 0 && R[i]) traverse (i); free (INDEX); free (VERTICES); *function = F; } void relation_transpose (relation *R_arg, relation_node n) { relation r = *R_arg; /* The result. */ relation new_R = xnmalloc (n, sizeof *new_R); /* END_R[I] -- next entry of NEW_R[I]. */ relation end_R = xnmalloc (n, sizeof *end_R); /* NEDGES[I] -- total size of NEW_R[I]. */ size_t *nedges = xcalloc (n, sizeof *nedges); relation_node i; relation_node j; if (trace_flag & trace_sets) { fputs ("relation_transpose: input\n", stderr); relation_print (r, n, stderr); } /* Count. */ for (i = 0; i < n; i++) if (r[i]) for (j = 0; r[i][j] != END_NODE; ++j) ++nedges[r[i][j]]; /* Allocate. */ for (i = 0; i < n; i++) { relation_node *sp = NULL; if (nedges[i] > 0) { sp = xnmalloc (nedges[i] + 1, sizeof *sp); sp[nedges[i]] = END_NODE; } new_R[i] = sp; end_R[i] = sp; } /* Store. */ for (i = 0; i < n; i++) if (r[i]) for (j = 0; r[i][j] != END_NODE; ++j) *end_R[r[i][j]]++ = i; free (nedges); free (end_R); /* Free the input: it is replaced with the result. */ for (i = 0; i < n; i++) free (r[i]); free (r); if (trace_flag & trace_sets) { fputs ("relation_transpose: output\n", stderr); relation_print (new_R, n, stderr); } *R_arg = new_R; }
//{{NO_DEPENDENCIES}} // Microsoft Developer Studio generated include file. // Used by Bomberman.rc #define IDI_BOMBER 101 // Next default values for new objects #ifdef APSTUDIO_INVOKED #ifndef <API key> #define <API key> 102 #define <API key> 40001 #define <API key> 1000 #define <API key> 101 #endif #endif
from __future__ import with_statement from sympy.printing.mathml import mathml import tempfile import os def print_gtk(x, start_viewer=True): """Print to Gtkmathview, a gtk widget capable of rendering MathML. Needs libgtkmathview-bin""" from sympy.utilities.mathml import c2p tmp = tempfile.mktemp() # create a temp file to store the result with open(tmp, 'wb') as file: file.write( c2p(mathml(x), simple=True) ) if start_viewer: os.system("mathmlviewer " + tmp)
static uint8_t p_css_tab1[ 256 ] = { 0x33, 0x73, 0x3b, 0x26, 0x63, 0x23, 0x6b, 0x76, 0x3e, 0x7e, 0x36, 0x2b, 0x6e, 0x2e, 0x66, 0x7b, 0xd3, 0x93, 0xdb, 0x06, 0x43, 0x03, 0x4b, 0x96, 0xde, 0x9e, 0xd6, 0x0b, 0x4e, 0x0e, 0x46, 0x9b, 0x57, 0x17, 0x5f, 0x82, 0xc7, 0x87, 0xcf, 0x12, 0x5a, 0x1a, 0x52, 0x8f, 0xca, 0x8a, 0xc2, 0x1f, 0xd9, 0x99, 0xd1, 0x00, 0x49, 0x09, 0x41, 0x90, 0xd8, 0x98, 0xd0, 0x01, 0x48, 0x08, 0x40, 0x91, 0x3d, 0x7d, 0x35, 0x24, 0x6d, 0x2d, 0x65, 0x74, 0x3c, 0x7c, 0x34, 0x25, 0x6c, 0x2c, 0x64, 0x75, 0xdd, 0x9d, 0xd5, 0x04, 0x4d, 0x0d, 0x45, 0x94, 0xdc, 0x9c, 0xd4, 0x05, 0x4c, 0x0c, 0x44, 0x95, 0x59, 0x19, 0x51, 0x80, 0xc9, 0x89, 0xc1, 0x10, 0x58, 0x18, 0x50, 0x81, 0xc8, 0x88, 0xc0, 0x11, 0xd7, 0x97, 0xdf, 0x02, 0x47, 0x07, 0x4f, 0x92, 0xda, 0x9a, 0xd2, 0x0f, 0x4a, 0x0a, 0x42, 0x9f, 0x53, 0x13, 0x5b, 0x86, 0xc3, 0x83, 0xcb, 0x16, 0x5e, 0x1e, 0x56, 0x8b, 0xce, 0x8e, 0xc6, 0x1b, 0xb3, 0xf3, 0xbb, 0xa6, 0xe3, 0xa3, 0xeb, 0xf6, 0xbe, 0xfe, 0xb6, 0xab, 0xee, 0xae, 0xe6, 0xfb, 0x37, 0x77, 0x3f, 0x22, 0x67, 0x27, 0x6f, 0x72, 0x3a, 0x7a, 0x32, 0x2f, 0x6a, 0x2a, 0x62, 0x7f, 0xb9, 0xf9, 0xb1, 0xa0, 0xe9, 0xa9, 0xe1, 0xf0, 0xb8, 0xf8, 0xb0, 0xa1, 0xe8, 0xa8, 0xe0, 0xf1, 0x5d, 0x1d, 0x55, 0x84, 0xcd, 0x8d, 0xc5, 0x14, 0x5c, 0x1c, 0x54, 0x85, 0xcc, 0x8c, 0xc4, 0x15, 0xbd, 0xfd, 0xb5, 0xa4, 0xed, 0xad, 0xe5, 0xf4, 0xbc, 0xfc, 0xb4, 0xa5, 0xec, 0xac, 0xe4, 0xf5, 0x39, 0x79, 0x31, 0x20, 0x69, 0x29, 0x61, 0x70, 0x38, 0x78, 0x30, 0x21, 0x68, 0x28, 0x60, 0x71, 0xb7, 0xf7, 0xbf, 0xa2, 0xe7, 0xa7, 0xef, 0xf2, 0xba, 0xfa, 0xb2, 0xaf, 0xea, 0xaa, 0xe2, 0xff }; static uint8_t p_css_tab2[ 256 ] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c, 0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23, 0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a, 0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x49, 0x48, 0x4b, 0x4a, 0x4d, 0x4c, 0x4f, 0x4e, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x5b, 0x5a, 0x59, 0x58, 0x5f, 0x5e, 0x5d, 0x5c, 0x52, 0x53, 0x50, 0x51, 0x56, 0x57, 0x54, 0x55, 0x6d, 0x6c, 0x6f, 0x6e, 0x69, 0x68, 0x6b, 0x6a, 0x64, 0x65, 0x66, 0x67, 0x60, 0x61, 0x62, 0x63, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x76, 0x77, 0x74, 0x75, 0x72, 0x73, 0x70, 0x71, 0x92, 0x93, 0x90, 0x91, 0x96, 0x97, 0x94, 0x95, 0x9b, 0x9a, 0x99, 0x98, 0x9f, 0x9e, 0x9d, 0x9c, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x89, 0x88, 0x8b, 0x8a, 0x8d, 0x8c, 0x8f, 0x8e, 0xb6, 0xb7, 0xb4, 0xb5, 0xb2, 0xb3, 0xb0, 0xb1, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xa4, 0xa5, 0xa6, 0xa7, 0xa0, 0xa1, 0xa2, 0xa3, 0xad, 0xac, 0xaf, 0xae, 0xa9, 0xa8, 0xab, 0xaa, 0xdb, 0xda, 0xd9, 0xd8, 0xdf, 0xde, 0xdd, 0xdc, 0xd2, 0xd3, 0xd0, 0xd1, 0xd6, 0xd7, 0xd4, 0xd5, 0xc9, 0xc8, 0xcb, 0xca, 0xcd, 0xcc, 0xcf, 0xce, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf6, 0xf7, 0xf4, 0xf5, 0xf2, 0xf3, 0xf0, 0xf1, 0xed, 0xec, 0xef, 0xee, 0xe9, 0xe8, 0xeb, 0xea, 0xe4, 0xe5, 0xe6, 0xe7, 0xe0, 0xe1, 0xe2, 0xe3 }; static uint8_t p_css_tab3[ 512 ] = { 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff }; static uint8_t p_css_tab4[ 256 ] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff }; static uint8_t p_css_tab5[ 256 ] = { 0xff, 0x7f, 0xbf, 0x3f, 0xdf, 0x5f, 0x9f, 0x1f, 0xef, 0x6f, 0xaf, 0x2f, 0xcf, 0x4f, 0x8f, 0x0f, 0xf7, 0x77, 0xb7, 0x37, 0xd7, 0x57, 0x97, 0x17, 0xe7, 0x67, 0xa7, 0x27, 0xc7, 0x47, 0x87, 0x07, 0xfb, 0x7b, 0xbb, 0x3b, 0xdb, 0x5b, 0x9b, 0x1b, 0xeb, 0x6b, 0xab, 0x2b, 0xcb, 0x4b, 0x8b, 0x0b, 0xf3, 0x73, 0xb3, 0x33, 0xd3, 0x53, 0x93, 0x13, 0xe3, 0x63, 0xa3, 0x23, 0xc3, 0x43, 0x83, 0x03, 0xfd, 0x7d, 0xbd, 0x3d, 0xdd, 0x5d, 0x9d, 0x1d, 0xed, 0x6d, 0xad, 0x2d, 0xcd, 0x4d, 0x8d, 0x0d, 0xf5, 0x75, 0xb5, 0x35, 0xd5, 0x55, 0x95, 0x15, 0xe5, 0x65, 0xa5, 0x25, 0xc5, 0x45, 0x85, 0x05, 0xf9, 0x79, 0xb9, 0x39, 0xd9, 0x59, 0x99, 0x19, 0xe9, 0x69, 0xa9, 0x29, 0xc9, 0x49, 0x89, 0x09, 0xf1, 0x71, 0xb1, 0x31, 0xd1, 0x51, 0x91, 0x11, 0xe1, 0x61, 0xa1, 0x21, 0xc1, 0x41, 0x81, 0x01, 0xfe, 0x7e, 0xbe, 0x3e, 0xde, 0x5e, 0x9e, 0x1e, 0xee, 0x6e, 0xae, 0x2e, 0xce, 0x4e, 0x8e, 0x0e, 0xf6, 0x76, 0xb6, 0x36, 0xd6, 0x56, 0x96, 0x16, 0xe6, 0x66, 0xa6, 0x26, 0xc6, 0x46, 0x86, 0x06, 0xfa, 0x7a, 0xba, 0x3a, 0xda, 0x5a, 0x9a, 0x1a, 0xea, 0x6a, 0xaa, 0x2a, 0xca, 0x4a, 0x8a, 0x0a, 0xf2, 0x72, 0xb2, 0x32, 0xd2, 0x52, 0x92, 0x12, 0xe2, 0x62, 0xa2, 0x22, 0xc2, 0x42, 0x82, 0x02, 0xfc, 0x7c, 0xbc, 0x3c, 0xdc, 0x5c, 0x9c, 0x1c, 0xec, 0x6c, 0xac, 0x2c, 0xcc, 0x4c, 0x8c, 0x0c, 0xf4, 0x74, 0xb4, 0x34, 0xd4, 0x54, 0x94, 0x14, 0xe4, 0x64, 0xa4, 0x24, 0xc4, 0x44, 0x84, 0x04, 0xf8, 0x78, 0xb8, 0x38, 0xd8, 0x58, 0x98, 0x18, 0xe8, 0x68, 0xa8, 0x28, 0xc8, 0x48, 0x88, 0x08, 0xf0, 0x70, 0xb0, 0x30, 0xd0, 0x50, 0x90, 0x10, 0xe0, 0x60, 0xa0, 0x20, 0xc0, 0x40, 0x80, 0x00 }; static uint8_t p_crypt_tab0[ 256 ] = { 0xB7, 0xF4, 0x82, 0x57, 0xDA, 0x4D, 0xDB, 0xE2, 0x2F, 0x52, 0x1A, 0xA8, 0x68, 0x5A, 0x8A, 0xFF, 0xFB, 0x0E, 0x6D, 0x35, 0xF7, 0x5C, 0x76, 0x12, 0xCE, 0x25, 0x79, 0x29, 0x39, 0x62, 0x08, 0x24, 0xA5, 0x85, 0x7B, 0x56, 0x01, 0x23, 0x68, 0xCF, 0x0A, 0xE2, 0x5A, 0xED, 0x3D, 0x59, 0xB0, 0xA9, 0xB0, 0x2C, 0xF2, 0xB8, 0xEF, 0x32, 0xA9, 0x40, 0x80, 0x71, 0xAF, 0x1E, 0xDE, 0x8F, 0x58, 0x88, 0xB8, 0x3A, 0xD0, 0xFC, 0xC4, 0x1E, 0xB5, 0xA0, 0xBB, 0x3B, 0x0F, 0x01, 0x7E, 0x1F, 0x9F, 0xD9, 0xAA, 0xB8, 0x3D, 0x9D, 0x74, 0x1E, 0x25, 0xDB, 0x37, 0x56, 0x8F, 0x16, 0xBA, 0x49, 0x2B, 0xAC, 0xD0, 0xBD, 0x95, 0x20, 0xBE, 0x7A, 0x28, 0xD0, 0x51, 0x64, 0x63, 0x1C, 0x7F, 0x66, 0x10, 0xBB, 0xC4, 0x56, 0x1A, 0x04, 0x6E, 0x0A, 0xEC, 0x9C, 0xD6, 0xE8, 0x9A, 0x7A, 0xCF, 0x8C, 0xDB, 0xB1, 0xEF, 0x71, 0xDE, 0x31, 0xFF, 0x54, 0x3E, 0x5E, 0x07, 0x69, 0x96, 0xB0, 0xCF, 0xDD, 0x9E, 0x47, 0xC7, 0x96, 0x8F, 0xE4, 0x2B, 0x59, 0xC6, 0xEE, 0xB9, 0x86, 0x9A, 0x64, 0x84, 0x72, 0xE2, 0x5B, 0xA2, 0x96, 0x58, 0x99, 0x50, 0x03, 0xF5, 0x38, 0x4D, 0x02, 0x7D, 0xE7, 0x7D, 0x75, 0xA7, 0xB8, 0x67, 0x87, 0x84, 0x3F, 0x1D, 0x11, 0xE5, 0xFC, 0x1E, 0xD3, 0x83, 0x16, 0xA5, 0x29, 0xF6, 0xC7, 0x15, 0x61, 0x29, 0x1A, 0x43, 0x4F, 0x9B, 0xAF, 0xC5, 0x87, 0x34, 0x6C, 0x0F, 0x3B, 0xA8, 0x1D, 0x45, 0x58, 0x25, 0xDC, 0xA8, 0xA3, 0x3B, 0xD1, 0x79, 0x1B, 0x48, 0xF2, 0xE9, 0x93, 0x1F, 0xFC, 0xDB, 0x2A, 0x90, 0xA9, 0x8A, 0x3D, 0x39, 0x18, 0xA3, 0x8E, 0x58, 0x6C, 0xE0, 0x12, 0xBB, 0x25, 0xCD, 0x71, 0x22, 0xA2, 0x64, 0xC6, 0xE7, 0xFB, 0xAD, 0x94, 0x77, 0x04, 0x9A, 0x39, 0xCF, 0x7C }; static uint8_t p_crypt_tab1[ 256 ] = { 0x8C, 0x47, 0xB0, 0xE1, 0xEB, 0xFC, 0xEB, 0x56, 0x10, 0xE5, 0x2C, 0x1A, 0x5D, 0xEF, 0xBE, 0x4F, 0x08, 0x75, 0x97, 0x4B, 0x0E, 0x25, 0x8E, 0x6E, 0x39, 0x5A, 0x87, 0x53, 0xC4, 0x1F, 0xF4, 0x5C, 0x4E, 0xE6, 0x99, 0x30, 0xE0, 0x42, 0x88, 0xAB, 0xE5, 0x85, 0xBC, 0x8F, 0xD8, 0x3C, 0x54, 0xC9, 0x53, 0x47, 0x18, 0xD6, 0x06, 0x5B, 0x41, 0x2C, 0x67, 0x1E, 0x41, 0x74, 0x33, 0xE2, 0xB4, 0xE0, 0x23, 0x29, 0x42, 0xEA, 0x55, 0x0F, 0x25, 0xB4, 0x24, 0x2C, 0x99, 0x13, 0xEB, 0x0A, 0x0B, 0xC9, 0xF9, 0x63, 0x67, 0x43, 0x2D, 0xC7, 0x7D, 0x07, 0x60, 0x89, 0xD1, 0xCC, 0xE7, 0x94, 0x77, 0x74, 0x9B, 0x7E, 0xD7, 0xE6, 0xFF, 0xBB, 0x68, 0x14, 0x1E, 0xA3, 0x25, 0xDE, 0x3A, 0xA3, 0x54, 0x7B, 0x87, 0x9D, 0x50, 0xCA, 0x27, 0xC3, 0xA4, 0x50, 0x91, 0x27, 0xD4, 0xB0, 0x82, 0x41, 0x97, 0x79, 0x94, 0x82, 0xAC, 0xC7, 0x8E, 0xA5, 0x4E, 0xAA, 0x78, 0x9E, 0xE0, 0x42, 0xBA, 0x28, 0xEA, 0xB7, 0x74, 0xAD, 0x35, 0xDA, 0x92, 0x60, 0x7E, 0xD2, 0x0E, 0xB9, 0x24, 0x5E, 0x39, 0x4F, 0x5E, 0x63, 0x09, 0xB5, 0xFA, 0xBF, 0xF1, 0x22, 0x55, 0x1C, 0xE2, 0x25, 0xDB, 0xC5, 0xD8, 0x50, 0x03, 0x98, 0xC4, 0xAC, 0x2E, 0x11, 0xB4, 0x38, 0x4D, 0xD0, 0xB9, 0xFC, 0x2D, 0x3C, 0x08, 0x04, 0x5A, 0xEF, 0xCE, 0x32, 0xFB, 0x4C, 0x92, 0x1E, 0x4B, 0xFB, 0x1A, 0xD0, 0xE2, 0x3E, 0xDA, 0x6E, 0x7C, 0x4D, 0x56, 0xC3, 0x3F, 0x42, 0xB1, 0x3A, 0x23, 0x4D, 0x6E, 0x84, 0x56, 0x68, 0xF4, 0x0E, 0x03, 0x64, 0xD0, 0xA9, 0x92, 0x2F, 0x8B, 0xBC, 0x39, 0x9C, 0xAC, 0x09, 0x5E, 0xEE, 0xE5, 0x97, 0xBF, 0xA5, 0xCE, 0xFA, 0x28, 0x2C, 0x6D, 0x4F, 0xEF, 0x77, 0xAA, 0x1B, 0x79, 0x8E, 0x97, 0xB4, 0xC3, 0xF4 }; static uint8_t p_crypt_tab2[ 256 ] = { 0xB7, 0x75, 0x81, 0xD5, 0xDC, 0xCA, 0xDE, 0x66, 0x23, 0xDF, 0x15, 0x26, 0x62, 0xD1, 0x83, 0x77, 0xE3, 0x97, 0x76, 0xAF, 0xE9, 0xC3, 0x6B, 0x8E, 0xDA, 0xB0, 0x6E, 0xBF, 0x2B, 0xF1, 0x19, 0xB4, 0x95, 0x34, 0x48, 0xE4, 0x37, 0x94, 0x5D, 0x7B, 0x36, 0x5F, 0x65, 0x53, 0x07, 0xE2, 0x89, 0x11, 0x98, 0x85, 0xD9, 0x12, 0xC1, 0x9D, 0x84, 0xEC, 0xA4, 0xD4, 0x88, 0xB8, 0xFC, 0x2C, 0x79, 0x28, 0xD8, 0xDB, 0xB3, 0x1E, 0xA2, 0xF9, 0xD0, 0x44, 0xD7, 0xD6, 0x60, 0xEF, 0x14, 0xF4, 0xF6, 0x31, 0xD2, 0x41, 0x46, 0x67, 0x0A, 0xE1, 0x58, 0x27, 0x43, 0xA3, 0xF8, 0xE0, 0xC8, 0xBA, 0x5A, 0x5C, 0x80, 0x6C, 0xC6, 0xF2, 0xE8, 0xAD, 0x7D, 0x04, 0x0D, 0xB9, 0x3C, 0xC2, 0x25, 0xBD, 0x49, 0x63, 0x8C, 0x9F, 0x51, 0xCE, 0x20, 0xC5, 0xA1, 0x50, 0x92, 0x2D, 0xDD, 0xBC, 0x8D, 0x4F, 0x9A, 0x71, 0x2F, 0x30, 0x1D, 0x73, 0x39, 0x13, 0xFB, 0x1A, 0xCB, 0x24, 0x59, 0xFE, 0x05, 0x96, 0x57, 0x0F, 0x1F, 0xCF, 0x54, 0xBE, 0xF5, 0x06, 0x1B, 0xB2, 0x6D, 0xD3, 0x4D, 0x32, 0x56, 0x21, 0x33, 0x0B, 0x52, 0xE7, 0xAB, 0xEB, 0xA6, 0x74, 0x00, 0x4C, 0xB1, 0x7F, 0x82, 0x99, 0x87, 0x0E, 0x5E, 0xC0, 0x8F, 0xEE, 0x6F, 0x55, 0xF3, 0x7E, 0x08, 0x90, 0xFA, 0xB6, 0x64, 0x70, 0x47, 0x4A, 0x17, 0xA7, 0xB5, 0x40, 0x8A, 0x38, 0xE5, 0x68, 0x3E, 0x8B, 0x69, 0xAA, 0x9B, 0x42, 0xA5, 0x10, 0x01, 0x35, 0xFD, 0x61, 0x9E, 0xE6, 0x16, 0x9C, 0x86, 0xED, 0xCD, 0x2E, 0xFF, 0xC4, 0x5B, 0xA0, 0xAE, 0xCC, 0x4B, 0x3B, 0x03, 0xBB, 0x1C, 0x2A, 0xAC, 0x0C, 0x3F, 0x93, 0xC7, 0x72, 0x7A, 0x09, 0x22, 0x3D, 0x45, 0x78, 0xA9, 0xA8, 0xEA, 0xC9, 0x6A, 0xF7, 0x29, 0x91, 0xF0, 0x02, 0x18, 0x3A, 0x4E, 0x7C }; static uint8_t p_crypt_tab3[ 288 ] = { 0x73, 0x51, 0x95, 0xE1, 0x12, 0xE4, 0xC0, 0x58, 0xEE, 0xF2, 0x08, 0x1B, 0xA9, 0xFA, 0x98, 0x4C, 0xA7, 0x33, 0xE2, 0x1B, 0xA7, 0x6D, 0xF5, 0x30, 0x97, 0x1D, 0xF3, 0x02, 0x60, 0x5A, 0x82, 0x0F, 0x91, 0xD0, 0x9C, 0x10, 0x39, 0x7A, 0x83, 0x85, 0x3B, 0xB2, 0xB8, 0xAE, 0x0C, 0x09, 0x52, 0xEA, 0x1C, 0xE1, 0x8D, 0x66, 0x4F, 0xF3, 0xDA, 0x92, 0x29, 0xB9, 0xD5, 0xC5, 0x77, 0x47, 0x22, 0x53, 0x14, 0xF7, 0xAF, 0x22, 0x64, 0xDF, 0xC6, 0x72, 0x12, 0xF3, 0x75, 0xDA, 0xD7, 0xD7, 0xE5, 0x02, 0x9E, 0xED, 0xDA, 0xDB, 0x4C, 0x47, 0xCE, 0x91, 0x06, 0x06, 0x6D, 0x55, 0x8B, 0x19, 0xC9, 0xEF, 0x8C, 0x80, 0x1A, 0x0E, 0xEE, 0x4B, 0xAB, 0xF2, 0x08, 0x5C, 0xE9, 0x37, 0x26, 0x5E, 0x9A, 0x90, 0x00, 0xF3, 0x0D, 0xB2, 0xA6, 0xA3, 0xF7, 0x26, 0x17, 0x48, 0x88, 0xC9, 0x0E, 0x2C, 0xC9, 0x02, 0xE7, 0x18, 0x05, 0x4B, 0xF3, 0x39, 0xE1, 0x20, 0x02, 0x0D, 0x40, 0xC7, 0xCA, 0xB9, 0x48, 0x30, 0x57, 0x67, 0xCC, 0x06, 0xBF, 0xAC, 0x81, 0x08, 0x24, 0x7A, 0xD4, 0x8B, 0x19, 0x8E, 0xAC, 0xB4, 0x5A, 0x0F, 0x73, 0x13, 0xAC, 0x9E, 0xDA, 0xB6, 0xB8, 0x96, 0x5B, 0x60, 0x88, 0xE1, 0x81, 0x3F, 0x07, 0x86, 0x37, 0x2D, 0x79, 0x14, 0x52, 0xEA, 0x73, 0xDF, 0x3D, 0x09, 0xC8, 0x25, 0x48, 0xD8, 0x75, 0x60, 0x9A, 0x08, 0x27, 0x4A, 0x2C, 0xB9, 0xA8, 0x8B, 0x8A, 0x73, 0x62, 0x37, 0x16, 0x02, 0xBD, 0xC1, 0x0E, 0x56, 0x54, 0x3E, 0x14, 0x5F, 0x8C, 0x8F, 0x6E, 0x75, 0x1C, 0x07, 0x39, 0x7B, 0x4B, 0xDB, 0xD3, 0x4B, 0x1E, 0xC8, 0x7E, 0xFE, 0x3E, 0x72, 0x16, 0x83, 0x7D, 0xEE, 0xF5, 0xCA, 0xC5, 0x18, 0xF9, 0xD8, 0x68, 0xAB, 0x38, 0x85, 0xA8, 0xF0, 0xA1, 0x73, 0x9F, 0x5D, 0x19, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x72, 0x39, 0x25, 0x67, 0x26, 0x6D, 0x71, 0x36, 0x77, 0x3C, 0x20, 0x62, 0x23, 0x68, 0x74, 0xC3, 0x82, 0xC9, 0x15, 0x57, 0x16, 0x5D, 0x81 };
// detail/win_static_mutex.hpp #ifndef <API key> #define <API key> #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #if defined(BOOST_WINDOWS) #include <boost/asio/detail/scoped_lock.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace detail { struct win_static_mutex { typedef boost::asio::detail::scoped_lock<win_static_mutex> scoped_lock; // Initialise the mutex. BOOST_ASIO_DECL void init(); // Initialisation must be performed in a separate function to the "public" // init() function since the compiler does not support the use of structured // exceptions and C++ exceptions in the same function. BOOST_ASIO_DECL int do_init(); // Lock the mutex. void lock() { ::<API key>(&crit_section_); } // Unlock the mutex. void unlock() { ::<API key>(&crit_section_); } bool initialised_; ::CRITICAL_SECTION crit_section_; }; #if defined(UNDER_CE) # define <API key> { false, { 0, 0, 0, 0, 0 } } #else // defined(UNDER_CE) # define <API key> { false, { 0, 0, 0, 0, 0, 0 } } #endif // defined(UNDER_CE) } // namespace detail } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #if defined(<API key>) # include <boost/asio/detail/impl/win_static_mutex.ipp> #endif // defined(<API key>) #endif // defined(BOOST_WINDOWS) #endif // <API key>
<?php class Time extends \phpws\Time{}
package net.shadowmage.ancientwarfare.npc.render; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class RenderShield implements IItemRenderer { private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/<API key>.png"); public RenderShield() { } @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { return type == ItemRenderType.EQUIPPED; } @Override public boolean <API key>(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return type == ItemRenderType.EQUIPPED && helper == ItemRendererHelper.EQUIPPED_BLOCK; } @Override public void renderItem(ItemRenderType type, ItemStack item, Object... data) { render((EntityLivingBase) data[1], item); } private void render(EntityLivingBase entity, ItemStack stack) { IIcon iicon = entity.getItemIcon(stack, stack.getItemDamage()); if (iicon == null) { return; } GL11.glPushMatrix(); TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); texturemanager.bindTexture(texturemanager.getResourceLocation(stack.getItemSpriteNumber())); TextureUtil.func_152777_a(false, false, 1.0F); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glTranslatef(-0.0F, -0.3F, 0.0F); float f6 = 1.5F; GL11.glScalef(f6, f6, f6); GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(0.0625f, 0.125F, 0.6875f - 3.f * 0.0625f); GL11.glRotatef(90, 0, 1, 0); GL11.glTranslatef(-8.f * 0.0625f, 10.f * 0.0625f, 0); GL11.glRotatef(-80.f, 1, 0, 0); GL11.glTranslatef(0, -3.f * 0.0625f, 0); Tessellator tessellator = Tessellator.instance; float f = iicon.getMinU(); float f1 = iicon.getMaxU(); float f2 = iicon.getMinV(); float f3 = iicon.getMaxV(); ItemRenderer.renderItemIn2D(tessellator, f1, f2, f, f3, iicon.getIconWidth(), iicon.getIconHeight(), 0.0625F); if (stack.hasEffect(stack.getItemDamage())){ GL11.glDepthFunc(GL11.GL_EQUAL); GL11.glDisable(GL11.GL_LIGHTING); texturemanager.bindTexture(RES_ITEM_GLINT); GL11.glEnable(GL11.GL_BLEND); OpenGlHelper.glBlendFunc(768, 1, 1, 0); float f7 = 0.76F; GL11.glColor4f(0.5F * f7, 0.25F * f7, 0.8F * f7, 1.0F); GL11.glMatrixMode(GL11.GL_TEXTURE); GL11.glPushMatrix(); float f8 = 0.125F; GL11.glScalef(f8, f8, f8); float f9 = (float)(Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; GL11.glTranslatef(f9, 0.0F, 0.0F); GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 256, 256, 0.0625F); GL11.glPopMatrix(); GL11.glPushMatrix(); GL11.glScalef(f8, f8, f8); f9 = (float)(Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; GL11.glTranslatef(-f9, 0.0F, 0.0F); GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 256, 256, 0.0625F); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_LIGHTING); GL11.glDepthFunc(GL11.GL_LEQUAL); } GL11.glDisable(GL12.GL_RESCALE_NORMAL); texturemanager.bindTexture(texturemanager.getResourceLocation(stack.getItemSpriteNumber())); TextureUtil.func_147945_b(); GL11.glPopMatrix(); } }
// Use of this source code is governed by a BSD-style // +build !appengine // Package subtle implements functions that are often useful in cryptographic // code but require careful thought to use correctly. package subtle // import "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/internal/subtle" import "unsafe" // AnyOverlap reports whether x and y share memory at any (not necessarily // corresponding) index. The memory beyond the slice length is ignored. func AnyOverlap(x, y []byte) bool { return len(x) > 0 && len(y) > 0 && uintptr(unsafe.Pointer(&x[0])) <= uintptr(unsafe.Pointer(&y[len(y)-1])) && uintptr(unsafe.Pointer(&y[0])) <= uintptr(unsafe.Pointer(&x[len(x)-1])) } // InexactOverlap reports whether x and y share memory at any non-corresponding // index. The memory beyond the slice length is ignored. Note that x and y can // have different lengths and still not have any inexact overlap. // InexactOverlap can be used to implement the requirements of the crypto/cipher // AEAD, Block, BlockMode and Stream interfaces. func InexactOverlap(x, y []byte) bool { if len(x) == 0 || len(y) == 0 || &x[0] == &y[0] { return false } return AnyOverlap(x, y) }
<?php namespace ApacheSolrForTypo3\Solr\System\Environment; use TYPO3\CMS\Core\Core\Environment; use TYPO3\CMS\Core\SingletonInterface; /** * Helper class for the cli environment helps to define the variables and constants * that are required in the cli context to allow frontend related operations in the cli context. * * @author Timo Hund <timo.hund@dkd.de> */ class CliEnvironment implements SingletonInterface { /** * @var array */ protected $<API key> = []; /** * @var bool */ protected $isInitialized = false; /** * @return void */ public function backup() { $this-><API key> = $_SERVER; } /** * Initializes the frontend related server variables for the cli context. * * @param string $webRoot * @param string $scriptFileName * @param string $phpSelf * @param string $scriptName * @throws <API key> * @return bool */ public function initialize($webRoot, $scriptFileName = '', $phpSelf = '/index.php', $scriptName = '/index.php') { // if the environment has be initialized once, we do not need to initialize it twice. if ($this->isInitialized) { return false; } if (defined('TYPO3_PATH_WEB')) { throw new <API key>('TYPO3_PATH_WEB is already defined'); } if ($scriptFileName === '') { $scriptFileName = Environment::getPublicPath() . '/'; } define('TYPO3_PATH_WEB', $webRoot); $_SERVER['SCRIPT_FILENAME'] = $scriptFileName; $_SERVER['PHP_SELF'] = $phpSelf; $_SERVER['SCRIPT_NAME'] = $scriptName; $this->isInitialized = true; return true; } /** * @return bool */ public function getIsInitialized() { return $this->isInitialized; } /** * @return void */ public function restore() { $_SERVER = $this-><API key>; } }
package console import ( "github.com/cgrates/cgrates/apier/v1" "github.com/cgrates/cgrates/utils" ) func init() { c := &CmdRemoveBalance{ name: "balance_remove", rpcMethod: "ApierV1.RemoveBalances", } commands[c.Name()] = c c.CommandExecuter = &CommandExecuter{c} } // Commander implementation type CmdRemoveBalance struct { name string rpcMethod string rpcParams *v1.AttrAddBalance *CommandExecuter } func (self *CmdRemoveBalance) Name() string { return self.name } func (self *CmdRemoveBalance) RpcMethod() string { return self.rpcMethod } func (self *CmdRemoveBalance) RpcParams(reset bool) interface{} { if reset || self.rpcParams == nil { self.rpcParams = &v1.AttrAddBalance{BalanceType: utils.MONETARY, Overwrite: false} } return self.rpcParams } func (self *CmdRemoveBalance) <API key>() error { return nil } func (self *CmdRemoveBalance) RpcResult() interface{} { var s string return &s }
/* This program is free software: you can redistribute it and/or modify */ /* (at your option) any later version. */ /* This program is distributed in the hope that it will be useful, */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ #include <exception> #include "core/ini_parser.hpp" #include "core/io.hpp" #include "core/config.hpp" namespace { const std::string tag("config"); } namespace RHVoice { bool config::set(const std::string& name,const std::string& value) { registration_map::iterator it=registered_settings.find(name); if(it==registered_settings.end()) return false; else return it->second->set_from_string(value); } void config::reset() { for(registration_map::iterator it=registered_settings.begin();it!=registered_settings.end();++it) { it->second->reset(); } } void config::load(const std::string& file_path) { try { logger->log(tag,<API key>,"trying to load configuration file "+file_path); for(ini_parser p(file_path);!p.done();p.next()) { if(p.get_section().empty()) { logger->log(tag,<API key>,p.get_key()+"="+p.get_value()); set(p.get_key(),p.get_value()); } } logger->log(tag,<API key>,"configuration file processed"); } catch(const io::open_error& e) { logger->log(tag,<API key>,e.what()); } catch(const std::exception& e) { logger->log(tag,<API key>,e.what()); throw; } } }
#pragma once #include "ui/chat/attach/attach_prepare.h" #include "ui/image/image_prepare.h" #include <QtCore/QTimer> #include <QtCore/QMutex> namespace Core { class FileLocation; } // namespace Core namespace Media { namespace Clip { enum class State { Reading, Error, Finished, }; struct FrameRequest { bool valid() const { return factor > 0; } int factor = 0; int framew = 0; int frameh = 0; int outerw = 0; int outerh = 0; ImageRoundRadius radius = ImageRoundRadius::None; RectParts corners = RectPart::AllCorners; }; enum ReaderSteps : int { <API key> = -3, // before ReaderPrivate read the first image and got the original frame size <API key> = -2, // before Reader got the original frame size and prepared the frame request <API key> = -1, // before ReaderPrivate got the frame request and started waiting for the 1-2 delay }; enum Notification : int { NotificationReinit, NotificationRepaint, }; class ReaderPrivate; class Reader { public: using Callback = Fn<void(Notification)>; enum class Mode { Gif, Video, }; Reader(const Core::FileLocation &location, const QByteArray &data, Callback &&callback); Reader(const QString &filepath, Callback &&callback); Reader(const QByteArray &data, Callback &&callback); // Reader can be already deleted. static void callback(Reader *reader, qint32 threadIndex, qint32 notification); void start(int framew, int frameh, int outerw, int outerh, ImageRoundRadius radius, RectParts corners); QPixmap current(int framew, int frameh, int outerw, int outerh, ImageRoundRadius radius, RectParts corners, crl::time ms); QPixmap frameOriginal() const { if (auto frame = frameToShow()) { auto result = QPixmap::fromImage(frame->original); result.detach(); return result; } return QPixmap(); } bool currentDisplayed() const { auto frame = frameToShow(); return frame ? (frame->displayed.loadAcquire() != 0) : true; } bool autoPausedGif() const { return _autoPausedGif.loadAcquire(); } bool videoPaused() const; int threadIndex() const { return _threadIndex; } int width() const; int height() const; State state() const; bool started() const { auto step = _step.loadAcquire(); return (step == <API key>) || (step >= 0); } bool ready() const; crl::time getPositionMs() const; crl::time getDurationMs() const; void pauseResumeVideo(); void stop(); void error(); void finished(); ~Reader(); private: void init(const Core::FileLocation &location, const QByteArray &data); Callback _callback; State _state = State::Reading; crl::time _durationMs = 0; mutable int _width = 0; mutable int _height = 0; // -2, -1 - init, 0-5 - work, show ((state + 1) / 2) % 3 state, write ((state + 3) / 2) % 3 mutable QAtomicInt _step = <API key>; struct Frame { void clear() { pix = QPixmap(); original = QImage(); } QPixmap pix; QImage original; FrameRequest request; QAtomicInt displayed = 0; // Should be counted from the end, // so that positionMs <= _durationMs. crl::time positionMs = 0; }; mutable Frame _frames[3]; Frame *frameToShow(int *index = nullptr) const; // 0 means not ready Frame *frameToWrite(int *index = nullptr) const; // 0 means not ready Frame *frameToWriteNext(bool check, int *index = nullptr) const; void moveToNextShow() const; void moveToNextWrite() const; QAtomicInt _autoPausedGif = 0; QAtomicInt _videoPauseRequest = 0; int32 _threadIndex; friend class Manager; ReaderPrivate *_private = nullptr; }; class ReaderPointer { public: ReaderPointer(std::nullptr_t = nullptr) { } explicit ReaderPointer(Reader *pointer) : _pointer(pointer) { } ReaderPointer(const ReaderPointer &other) = delete; ReaderPointer &operator=(const ReaderPointer &other) = delete; ReaderPointer(ReaderPointer &&other) : _pointer(base::take(other._pointer)) { } ReaderPointer &operator=(ReaderPointer &&other) { swap(other); return *this; } void swap(ReaderPointer &other) { qSwap(_pointer, other._pointer); } Reader *get() const { return valid() ? _pointer : nullptr; } Reader *operator->() const { return get(); } void setBad() { reset(); _pointer = BadPointer; } void reset() { ReaderPointer temp; swap(temp); } bool isBad() const { return (_pointer == BadPointer); } bool valid() const { return _pointer && !isBad(); } explicit operator bool() const { return valid(); } static inline ReaderPointer Bad() { ReaderPointer result; result.setBad(); return result; } ~ReaderPointer(); private: Reader *_pointer = nullptr; static Reader *const BadPointer; }; template <typename ...Args> inline ReaderPointer MakeReader(Args&&... args) { return ReaderPointer(new Reader(std::forward<Args>(args)...)); } enum class ProcessResult { Error, Started, Finished, Paused, Repaint, CopyFrame, Wait, }; class Manager : public QObject { public: explicit Manager(QThread *thread); ~Manager(); int loadLevel() const { return _loadLevel; } void append(Reader *reader, const Core::FileLocation &location, const QByteArray &data); void start(Reader *reader); void update(Reader *reader); void stop(Reader *reader); bool carries(Reader *reader) const; private: void process(); void finish(); void callback(Reader *reader, Notification notification); void clear(); QAtomicInt _loadLevel; using ReaderPointers = QMap<Reader*, QAtomicInt>; ReaderPointers _readerPointers; mutable QMutex <API key>; ReaderPointers::const_iterator <API key>(ReaderPrivate *reader) const; ReaderPointers::iterator <API key>(ReaderPrivate *reader); bool handleProcessResult(ReaderPrivate *reader, ProcessResult result, crl::time ms); enum ResultHandleState { ResultHandleRemove, ResultHandleStop, <API key>, }; ResultHandleState handleResult(ReaderPrivate *reader, ProcessResult result, crl::time ms); using Readers = QMap<ReaderPrivate*, crl::time>; Readers _readers; QTimer _timer; QThread *_processingInThread = nullptr; bool _needReProcess = false; }; [[nodiscard]] Ui::<API key>::Video PrepareForSending( const QString &fname, const QByteArray &data); void Finish(); } // namespace Clip } // namespace Media
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2017-08-14 16:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('parlamentares', '<API key>'), ] operations = [ migrations.AlterModelOptions( name='frente', options={'verbose_name': 'Frente Parlamentar', 'verbose_name_plural': 'Frentes Parlamentares'}, ), ]
#include "SC_WorldOptions.h" #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <math.h> #include "clz.h" #include <stdexcept> #ifdef _WIN32 #include <pthread.h> #include <winsock2.h> #else #include <sys/wait.h> #endif #ifdef _WIN32 // setlinebuf is equivalent to the setvbuf call below. inline int setlinebuf(FILE *stream) { return setvbuf( stream, (char*)0, _IONBF, 0 ); } #endif void Usage(); void Usage() { scprintf( "supercollider_synth options:\n" " -u <udp-port-number> a port number 0-65535\n" " -t <tcp-port-number> a port number 0-65535\n" " -c <<API key>> (default %d)\n" " -a <<API key>> (default %d)\n" " -i <<API key>> (default %d)\n" " -o <<API key>> (default %d)\n" " -z <block-size> (default %d)\n" " -Z <<API key>> (default %d)\n" " -S <<API key>> (default %d)\n" " -b <<API key>> (default %d)\n" " -n <max-number-of-nodes> (default %d)\n" " -d <<API key>> (default %d)\n" " -m <<API key>> (default %d)\n" " -w <<API key>> (default %d)\n" " -r <<API key>> (default %d)\n" " -D <load synthdefs? 1 or 0> (default %d)\n" " -R <publish to Rendezvous? 1 or 0> (default %d)\n" " -l <max-logins> (default %d)\n" " maximum number of named return addresses stored\n" " also maximum number of tcp connections accepted\n" " -p <session-password>\n" " When using TCP, the session password must be the first command sent.\n" " The default is no password.\n" " UDP ports never require passwords, so for security use TCP.\n" " -N <cmd-filename> <input-filename> <output-filename> <sample-rate> <header-format> <sample-format>\n" #ifdef __APPLE__ " -I <<API key>>\n" " -O <<API key>>\n" " -M <<API key>> <<API key>>\n" #endif #if (_POSIX_MEMLOCK - 0) >= 200112L " -L enable memory locking\n" #endif " -H <<API key>>\n" " -v <verbosity>\n" " 0 is normal behaviour\n" " -1 suppresses informational messages\n" " -2 suppresses informational and many error messages\n" " -U <ugen-plugins-path> a colon-separated list of paths\n" " if -U is specified, the standard paths are NOT searched for plugins.\n" " -P <restricted-path> \n" " if specified, prevents file-accessing OSC commands from\n" " accessing files outside <restricted-path>.\n" "\nTo quit, send a 'quit' command via UDP or TCP, or press ctrl-C.\n\n", <API key>.<API key>, <API key>.<API key>, <API key>.<API key>, <API key>.<API key>, <API key>.mBufLength, <API key>.<API key>, <API key>.<API key>, <API key>.mNumBuffers, <API key>.mMaxNodes, <API key>.mMaxGraphDefs, <API key>.mRealTimeMemorySize, <API key>.mMaxWireBufs, <API key>.mNumRGens, <API key>.mRendezvous, <API key>.mLoadGraphDefs, <API key>.mMaxLogins ); exit(1); } #define checkNumArgs(n) \ if (i+n > argc) { \ if (n == 2) scprintf("ERROR: Argument expected after option %s\n", argv[j]); \ else scprintf("ERROR: More arguments expected after option %s\n", argv[j]); \ Usage(); \ } \ i += n; int main(int argc, char* argv[]); int main(int argc, char* argv[]) { setlinebuf(stdout); #ifdef _WIN32 #ifdef <API key> // initialize statically linked pthreads library <API key>(); #endif // initialize winsock WSAData wsaData; int nCode; if ((nCode = WSAStartup(MAKEWORD(1, 1), &wsaData)) != 0) { scprintf( "WSAStartup() failed with error code %d.\n", nCode ); return 1; } #endif int udpPortNum = -1; int tcpPortNum = -1; WorldOptions options = <API key>; for (int i=1; i<argc;) { if (argv[i][0] != '-' || argv[i][1] == 0 || strchr("<API key>", argv[i][1]) == 0) { scprintf("ERROR: Invalid option %s\n", argv[i]); Usage(); } int j = i; switch (argv[j][1]) { case 'u' : checkNumArgs(2); udpPortNum = atoi(argv[j+1]); break; case 't' : checkNumArgs(2); tcpPortNum = atoi(argv[j+1]); break; case 'a' : checkNumArgs(2); options.<API key> = atoi(argv[j+1]); break; case 'i' : checkNumArgs(2); options.<API key> = atoi(argv[j+1]); break; case 'o' : checkNumArgs(2); options.<API key> = atoi(argv[j+1]); break; case 'c' : checkNumArgs(2); options.<API key> = atoi(argv[j+1]); break; case 'z' : checkNumArgs(2); options.mBufLength = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'Z' : checkNumArgs(2); options.<API key> = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'b' : checkNumArgs(2); options.mNumBuffers = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'l' : checkNumArgs(2); options.mMaxLogins = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'n' : checkNumArgs(2); options.mMaxNodes = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'd' : checkNumArgs(2); options.mMaxGraphDefs = NEXTPOWEROFTWO(atoi(argv[j+1])); break; case 'p' : checkNumArgs(2); options.mPassword = argv[j+1]; break; case 'm' : checkNumArgs(2); options.mRealTimeMemorySize = atoi(argv[j+1]); break; case 'w' : checkNumArgs(2); options.mMaxWireBufs = atoi(argv[j+1]); break; case 'r' : checkNumArgs(2); options.mNumRGens = atoi(argv[j+1]); break; case 'S' : checkNumArgs(2); options.<API key> = (uint32)atof(argv[j+1]); break; case 'D' : checkNumArgs(2); options.mLoadGraphDefs = atoi(argv[j+1]); break; case 'N' : #ifdef NO_LIBSNDFILE scprintf("NRT mode not supported: scsynth compiled without libsndfile\n"); exit(0); #endif // -N cmd-filename input-filename output-filename sample-rate header-format sample-format checkNumArgs(7); options.mRealTime = false; options.<API key> = strcmp(argv[j+1], "_") ? argv[j+1] : 0; options.<API key> = strcmp(argv[j+2], "_") ? argv[j+2] : 0; options.<API key> = argv[j+3]; options.<API key> = (uint32)atof(argv[j+4]); options.<API key> = argv[j+5]; options.<API key> = argv[j+6]; break; #ifdef __APPLE__ case 'I' : checkNumArgs(2); options.<API key> = argv[j+1]; break; case 'O' : checkNumArgs(2); options.<API key> = argv[j+1]; break; case 'M': // -M serverPortName replyPortName checkNumArgs(3); options.mServerPortName = <API key>(NULL, argv[j + 1], <API key>, kCFAllocatorNull); options.mReplyPortName = <API key>(NULL, argv[j + 2], <API key>, kCFAllocatorNull); break; #endif case 'H' : checkNumArgs(2); options.mInDeviceName = argv[j+1]; #ifdef __APPLE__ if (i+1>argc || argv[j+2][0]=='-') { options.mOutDeviceName = options.mInDeviceName; } else { // If there's a second argument then the user wants separate I/O devices options.mOutDeviceName = argv[j+2]; ++i; } #else options.mOutDeviceName = options.mInDeviceName; // Non-Mac platforms always use same device #endif break; case 'L' : checkNumArgs(1); #if (_POSIX_MEMLOCK - 0) >= 200112L options.mMemoryLocking = true; #else options.mMemoryLocking = false; #endif break; case 'v' : checkNumArgs(2); options.mVerbosity = atoi(argv[j+1]); break; case 'R' : checkNumArgs(2); options.mRendezvous = atoi(argv[j+1]) > 0; break; case 'U' : checkNumArgs(2); options.mUGensPluginPath = argv[j+1]; break; case 'P' : checkNumArgs(2); options.mRestrictedPath = argv[j+1]; break; case 'h': default: Usage(); } } if (udpPortNum == -1 && tcpPortNum == -1 && options.mRealTime) { scprintf("ERROR: There must be a -u and/or a -t options, or -N for nonrealtime.\n"); Usage(); } if (options.<API key> + options.<API key> > options.<API key>) { scprintf("ERROR: number of audio bus channels < inputs + outputs.\n"); Usage(); } struct World *world = World_New(&options); if (!world) return 1; if (!options.mRealTime) { #ifdef NO_LIBSNDFILE return 1; #else int exitCode = 0; try { <API key>(world, &options); } catch (std::exception& exc) { scprintf("%s\n", exc.what()); exitCode = 1; } return exitCode; #endif } if (udpPortNum >= 0) { if (!World_OpenUDP(world, udpPortNum)) { World_Cleanup(world); return 1; } } if (tcpPortNum >= 0) { if (!World_OpenTCP(world, tcpPortNum, options.mMaxLogins, 8)) { World_Cleanup(world); return 1; } } #ifdef __APPLE__ //World_OpenMachPorts(world, options.mServerPortName, options.mReplyPortName); #endif if(options.mVerbosity >=0){ #ifdef NDEBUG scprintf("SuperCollider 3 server ready.\n"); #else scprintf("SuperCollider 3 server ready (debug build).\n"); #endif } fflush(stdout); World_WaitForQuit(world); #ifdef _WIN32 // clean up winsock WSACleanup(); #ifdef <API key> // clean up statically linked pthreads <API key>(); #endif #endif return 0; }
<?php $GLOBALS['<API key>'][] = 'pour'; $GLOBALS['<API key>'][] = 'condition'; /* le critere {tableau ...} des boucles pour:POUR */ function <API key>($idb, &$boucles, $crit) { $boucle = &$boucles[$idb]; if (isset($crit->param[0])){ $table = calculer_liste($crit->param[0], array(), $boucles, $boucle->id_parent); $boucle->having[]=array("'tableau'",$table); } } /* le critere {si ...} des boucles condition:CONDITION */ function <API key>($idb, &$boucles, $crit) { $boucle = &$boucles[$idb]; if (isset($crit->param[0])){ $si = calculer_liste($crit->param[0], array(), $boucles, $boucle->id_parent); $boucle->having[]='($test='.$si.')?array(\'tableau\',\'1:1\'):\'\''; } } function critere_compteur($idb, &$boucles, $crit, $left=false){ $boucle = &$boucles[$idb]; $_fusion = calculer_liste($crit->param[1], array(), $boucles, $boucle->id_parent); $params = $crit->param; $table = reset($params); $table = $table[0]->texte; $op = false; if(preg_match(',^(\w+)([<>=])([0-9]+)$,',$table,$r)){ $table=$r[1]; if (count($r)>=3) $op=$r[2]; if (count($r)>=4) $op_val=$r[3]; } $type = objet_type($table); $type_id = id_table_objet($type); $table_sql = table_objet_sql($type); $trouver_table = charger_fonction('trouver_table','base'); $arrivee = array($table, $trouver_table($table, $boucle->sql_serveur)); $depart = array($boucle->id_table,$trouver_table($boucle->id_table, $boucle->sql_serveur)); // noter les jointures deja installees $joins = array_keys($boucle->from); if ($compt = calculer_jointure($boucle,$depart,$arrivee)){ if ($_fusion!="''"){ // en cas de jointure, on ne veut pas du group_by sur la cle primaire ! // cela casse le compteur ! foreach($boucle->group as $k=>$group) if ($group == $boucle->id_table.'.'.$boucle->primary) unset($boucle->group[$k]); $boucle->group[] = '".($gb='.$_fusion.')."'; } $boucle->select[]= "COUNT($compt.$type_id) AS compteur_$table"; if ($op) $boucle->having[]= array("'".$op."'", "'compteur_".$table."'",$op_val); if ($left){ foreach($boucle->from as $k=>$val){ if (!in_array($k, $joins)){ $boucle->from_type[$k] = 'left'; } } } } } /** * {compteur_left xxx} permet de faire la meme chose que {compteur xxx} * mais avec un LEFT JOIN pour ne pas ignorer ceux qui ont un compteur nul * @param <type> $idb * @param <type> $boucles * @param <type> $crit */ function <API key>($idb, &$boucles, $crit){ critere_compteur($idb, $boucles, $crit, true); } /** Critere {somme champ} #SOMME{champ} */ function critere_somme($idb, &$boucles, $crit){ <API key>(array('SUM'=>'somme'), $idb, $boucles, $crit); } /** Critere {compte champ} #COMPTE{champ} */ function critere_compte($idb, &$boucles, $crit){ <API key>(array('COUNT'=>'compte'), $idb, $boucles, $crit); } /** Critere {moyenne champ} #MOYENNE{champ} */ function critere_moyenne($idb, &$boucles, $crit){ <API key>(array('AVG'=>'moyenne'), $idb, $boucles, $crit); } /** Critere {minimum champ} #MINIMUM{champ} */ function critere_minimum($idb, &$boucles, $crit){ <API key>(array('MIN'=>'minimum'), $idb, $boucles, $crit); } /** Critere {maximum champ} #MAXIMUM{champ} */ function critere_maximum($idb, &$boucles, $crit){ <API key>(array('MAX'=>'maximum'), $idb, $boucles, $crit); } /** Critere {stats champ} calcul la totale : somme, compte, minimum, moyenne, maximum */ function critere_stats($idb, &$boucles, $crit){ <API key>(array( 'SUM'=>'somme', 'COUNT'=>'compte', 'AVG'=>'moyenne', 'MIN'=>'minimum', 'MAX'=>'maximum', ), $idb, $boucles, $crit); } /* $func : array(FUNC => balise) */ function <API key>($func, $idb, &$boucles, $crit) { $boucle = &$boucles[$idb]; $_fusion = calculer_liste($crit->param[1], array(), $boucles, $boucle->id_parent); $params = $crit->param; $champ = reset($params); $champ = $champ[0]->texte; // option DISTINCT {compte DISTINCT(id_article) } $filter=""; if (preg_match('/^([a-zA-Z]+)\(\s*([a-zA-Z_]+)\s*\)$/', trim($champ), $r)) { $filter = $r[1]; // DISTINCT $champ = $r[2]; // id_article } $sel = $filter ? "$filter($champ)" : $champ; foreach ($func as $f => $as) { $boucle->select[]= "$f($sel) AS $as" . "_$champ"; } } /** * {tri [champ_par_defaut][,sens_par_defaut][,nom_variable]} * champ_par_defaut : un champ de la table sql * sens_par_defaut : -1 ou inverse pour decroissant, 1 ou direct pour croissant * nom_variable : nom de la variable utilisee (par defaut tri_nomboucle) * * {tri titre} * {tri titre,inverse} * {tri titre,-1} * {tri titre,-1,truc} * * @param unknown_type $idb * @param unknown_type $boucles * @param unknown_type $crit */ function critere_tri_dist($idb, &$boucles, $crit) { $boucle = &$boucles[$idb]; $id_table = $boucle->id_table; // definition du champ par defaut $_champ_defaut = !isset($crit->param[0][0]) ? "''" : calculer_liste(array($crit->param[0][0]), array(), $boucles, $boucle->id_parent); $_sens_defaut = !isset($crit->param[1][0]) ? "1" : calculer_liste(array($crit->param[1][0]), array(), $boucles, $boucle->id_parent); $_variable = !isset($crit->param[2][0]) ? "'$idb'" : calculer_liste(array($crit->param[2][0]), array(), $boucles, $boucle->id_parent); $_tri = "((\$t=(isset(\$Pile[0]['tri'.$_variable]))?\$Pile[0]['tri'.$_variable]:$_champ_defaut)?tri_protege_champ(\$t):'')"; $_sens_defaut = "(is_array(\$s=$_sens_defaut)?(isset(\$s[\$st=$_tri])?\$s[\$st]:reset(\$s)):\$s)"; $_sens ="((intval(\$t=(isset(\$Pile[0]['sens'.$_variable]))?\$Pile[0]['sens'.$_variable]:$_sens_defaut)==-1 OR \$t=='inverse')?-1:1)"; $boucle->modificateur['tri_champ'] = $_tri; $boucle->modificateur['tri_sens'] = $_sens; $boucle->modificateur['tri_nom'] = $_variable; // faut il inserer un test sur l'existence de $tri parmi les champs de la table ? // evite des erreurs sql, mais peut empecher des tri sur jointure ... $boucle->hash .= " \$senstri = ''; \$tri = $_tri; if (\$tri){ \$senstri = $_sens; \$senstri = (\$senstri<0)?' DESC':''; }; "; $field = serialize(array_keys($boucle->show['field'])); $boucle->select[] = "\".tri_champ_select(\$tri).\""; $boucle->order[] = "tri_champ_order(\$tri,'$id_table','$field').\$senstri"; } /** * Trouver toutes les objets qui ont des enfants (les noeuds de l'arbre) * {noeud} * {!noeud} retourne les feuilles * * @global array $<API key> * @param string $idb * @param array $boucles * @param <type> $crit */ function critere_noeud_dist($idb, &$boucles, $crit) { global $<API key>; $not = $crit->not; $boucle = &$boucles[$idb]; $primary = $boucle->primary; if (!$primary OR strpos($primary,',')) { erreur_squelette(_T('<API key>'), "BOUCLE$idb"); return; } $table = $boucle->type_requete; $table_sql = table_objet_sql(objet_type($table)); $id_parent = isset($<API key>[$boucle->id_table]['id_parent']) ? $<API key>[$boucle->id_table]['id_parent'] : 'id_parent'; $in = "IN"; $where= array("'IN'", "'$boucle->id_table." . "$primary'","'('.sql_get_select('$id_parent', '$table_sql').')'"); if ($not) $where = array("'NOT'",$where); $boucle->where[]= $where; } /** * Trouver toutes les objets qui n'ont pas d'enfants (les feuilles de l'arbre) * {feuille} * {!feuille} retourne les noeuds * * @global array $<API key> * @param string $idb * @param array $boucles * @param <type> $crit */ function <API key>($idb, &$boucles, $crit) { $not = $crit->not; $crit->not = $not ? false:true; critere_noeud_dist($idb,$boucles,$crit); $crit->not = $not; } ?>
import { Template } from "meteor/templating"; Template.notFound.onCreated(() => { document.<API key>("head")[0].insertAdjacentHTML("beforeend", "<meta name='<API key>' content='404'>"); // todo report not found source });
function ViewManager() { var self = this; this.init = function () { self.bottomPane = $('bottom-pane'); self.viewThemeSelect = $('viewtheme-select'); if (!self.isIE6) { // Set up the column container reference, and make the container the // base for positioned elements inside it self.columnContainer = $('column-container'); makePositioned(self.columnContainer); // Hide 'new block here' buttons forEach(<API key>('div', 'add-button', self.bottomPane), function(i) { removeElement(i); }); // Hide controls in each block instance that are not needed forEach(<API key>('input', 'movebutton', self.bottomPane), function(i) { removeElement(i); }); // Remove radio buttons for moving block types into place forEach(<API key>('input', 'blocktype-radio', 'top-pane'), function(i) { setNodeAttribute(i, 'type', 'hidden'); if (self.isIE7 || self.isIE6) { hideElement(i); } }); // Rewrite the links in the category select list to be ajax self.<API key>(); // Rewrite the configure buttons to be ajax self.<API key>(); // Rewrite the delete buttons to be ajax self.<API key>(); // Rewrite the 'add column' buttons to be ajax self.<API key>(); // Rewrite the 'remove column' buttons to be ajax self.<API key>(); // Ensure the enabled/disabled state of the add/remove buttons is correct self.<API key>(); // Make the block instances draggable self.<API key>(); // Make the block types draggable self.<API key>(); // Change the intruction to be for ajax self.ajaxInstructions(); // Wire up the view theme selector self.<API key>(); // Make the top pane a dropzone for cancelling adding block types if (!self.isIE6) { var count = 0; new Droppable('top-pane', { 'onhover': function() { if (count++ == 5) { count = 0; // Hide the dropzone hideElement(self.blockPlaceholder); } } }); } } // Unhide the radio button if the browser is iPhone, IPad or IPod else if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) { forEach(<API key>('input', 'blocktype-radio', 'top-pane'), function(i) { setNodeAttribute(i, 'style', 'display:inline'); }); } // Now we're done, remove the loading message and display the page removeElement('views-loading'); showElement(self.bottomPane); } /** * Adds a column to the view */ this.addColumn = function(id, data) { // Get the existing number of columns var numColumns = parseInt(getNodeAttribute(<API key>('div', 'column', self.bottomPane), 'class').match(/columns([0-9]+)/)[1]); // Here we are doing two things: // 1) The existing columns that are higher than the one being inserted need to be renumbered // 2) All columns need their 'columnsN' class renumbered one higher // 3) All columns need their 'width' style attribute removed, if they have one for (var oldID = numColumns; oldID >= 1; oldID var column = $('column_' + oldID); var newID = oldID + 1; if (oldID >= id) { $('column_' + oldID).setAttribute('id', 'column_' + newID); // Renumber the add/remove column buttons <API key>('input', 'addcolumn', 'column_' + newID).setAttribute('name', '<API key>' + (newID + 1)); <API key>('input', 'removecolumn', 'column_' + newID).setAttribute('name', '<API key>' + newID); } removeElementClass(column, 'columns' + numColumns); addElementClass(column, 'columns' + (numColumns + 1)); removeNodeAttribute(column, 'style'); } // If the column being added is the very first one, the 'left' add column button needs to be removed if (id == 1) { removeElement(<API key>('div', 'add-column-left', 'column_2')); } // If we're adding a column to the very right, move the add button between the columns if (id > numColumns) { var rightColumnDiv = <API key>('div', 'add-column-right', 'column_' + numColumns); removeElementClass(rightColumnDiv, 'add-column-right'); addElementClass(rightColumnDiv, 'add-column-center'); } // Now we insert the new column into the DOM. Inserting the HTML into a // new element and then into the DOM means we can add the new column // without changing any of the existing DOM tree (and thus destroying // events) var tempDiv = DIV(); tempDiv.innerHTML = data.data; if (id == 1) { <API key>('column_2', tempDiv.firstChild); } else { <API key>('column_' + (id - 1), tempDiv.firstChild); } if (numColumns == 1) { removeElementClass('layout-link', 'disabled'); } else if (numColumns == 4) { addElementClass('layout-link', 'disabled'); } // Wire up the new column buttons to be AJAX self.<API key>('column_' + id); self.<API key>('column_' + id); } /** * Removes a column from the view, sizes the others to take its place and * moves the blockinstances in it to the other columns */ this.removeColumn = function(id) { var <API key>; if (id == 1) { // We are removing the first column, which has the button for adding a column to the left of itself. We want to keep this <API key> = <API key>('div', 'add-column-left', 'column_1'); } // Save the blockinstances that are in the column to remove var blockInstances = <API key>('div', 'blockinstance', 'column_' + id); // Remove the column itself removeElement('column_' + id); // Get the existing number of columns var numColumns = parseInt(getNodeAttribute(<API key>('div', 'column', self.bottomPane), 'class').match(/columns([0-9]+)/)[1]); // Renumber the columnsN classes of the remaining columns, and remove any set widths forEach(<API key>('div', 'columns' + numColumns, self.bottomPane), function(i) { removeElementClass(i, 'columns' + numColumns); addElementClass(i, 'columns' + (numColumns - 1)); removeNodeAttribute(i, 'style'); }); // All columns above the one removed need to be renumbered if (id < numColumns) { for (var i = id; i < numColumns; i++) { var oldID = i + 1; var newID = i; $('column_' + oldID).setAttribute('id', 'column_' + newID); // Renumber the add/remove column buttons <API key>('input', 'addcolumn', 'column_' + newID).setAttribute('name', '<API key>' + oldID); <API key>('input', 'removecolumn', 'column_' + newID).setAttribute('name', '<API key>' + newID); } } if (numColumns == 2) { addElementClass('layout-link', 'disabled'); } else if (numColumns == 5) { removeElementClass('layout-link', 'disabled'); } // The last column needs the class of the header changed, the first column possibly too if (<API key>) { <API key>( <API key>('div', 'remove-column', 'column_1'), <API key> ); } var lastColumn = $('column_' + (numColumns - 1)); var <API key> = <API key>('div', 'add-column-right', lastColumn); if (!<API key>) { var <API key> = <API key>('div', 'add-column-center', lastColumn); removeElementClass(<API key>, 'add-column-center'); addElementClass(<API key>, 'add-column-right'); } // Put the block instances that were in the removed column into the other columns var i = 1; forEach(blockInstances, function(instance) { appendChildNodes(<API key>('div', 'column-content', 'column_' + i), instance); if (i < (numColumns - 1)) { i++; } else { i = 1; } }); } /** * Rewrites the category select links to be AJAX */ this.<API key> = function() { forEach(<API key>('a', null, 'category-list'), function(i) { connect(i, 'onclick', function(e) { var queryString = parseQueryString(i.href.substr(i.href.indexOf('?'))); removeElementClass(<API key>('li', 'current', 'category-list'), 'current'); addElementClass(i.parentNode, 'current'); sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', {'id': $('viewid').value, 'action': 'blocktype_list', 'c': queryString['c']}, 'POST', function(data) { setNodeAttribute('category', 'value', queryString['c']); $('blocktype-list').innerHTML = data.data; self.<API key>(); }); e.stop(); }); }); } /** * Rewrites the blockinstance configure buttons to be AJAX */ this.<API key> = function() { forEach(<API key>('input', 'configurebutton', self.bottomPane), function(i) { self.<API key>(i); }); } /** * Rewrites one configure button to be AJAX */ this.<API key> = function(button) { connect(button, 'onclick', function(e) { e.stop(); self.getConfigureForm(<API key>(button, 'div', 'blockinstance')); }); } this.getConfigureForm = function(blockinstance) { var button = <API key>('input', 'configurebutton', blockinstance); var blockinstanceId = blockinstance.id.substr(blockinstance.id.lastIndexOf('_') + 1); var contentDiv = <API key>('div', '<API key>', blockinstance); var pd = {'id': $('viewid').value, 'change': 1}; if (config.blockeditormaxwidth) { // Shouldn't have to pass browser window dimensions here, but can't find // another way to get tinymce elements to use up the available height. pd['cfheight'] = <API key>().h - 100; } pd[getNodeAttribute(button, 'name')] = 1; var oldContent = contentDiv.innerHTML; // Put a loading message in place while the form downloads replaceChildNodes(contentDiv, IMG({'src': config.theme['images/loading.gif']}), ' ', get_string('loading')); sendjsonrequest('blocks.json.php', pd, 'POST', function(data) { contentDiv.innerHTML = oldContent; self.addConfigureBlock(blockinstance, data.data); $('action-dummy').name = getNodeAttribute(button, 'name'); var cancelButton = $('<API key>' + blockinstanceId); connect(cancelButton, 'onclick', function(e) { e.stop(); self.<API key>(); self.showMediaPlayers(); }); }); } this.hideMediaPlayers = function () { var cols = $('column-container'); forEach(<API key>(null, '<API key>', cols), function (e) { var d = <API key>(e); setStyle(e, {'height': d.h+'px'}); hideElement(<API key>(null, 'mediaplayer', e)); forEach(<API key>('object', null, e), function(o) { addElementClass(o, 'in-mediaplayer'); }); }); // Try to find and hide players floating around in text blocks, etc. by looking for object elements forEach(<API key>('object', null, cols), function (e) { if (!hasElementClass(e, 'in-mediaplayer')) { var d = <API key>(e); var temp = DIV({'class': 'hidden <API key>'}); setStyle(temp, {'height': d.h+'px'}); <API key>(e, temp); addElementClass(e, 'hidden'); removeElementClass(temp, 'hidden'); } }); <API key>(document.body.firstChild, DIV({'id': 'overlay'})); } this.showMediaPlayers = function () { if (tinyMCE && tinyMCE.activeEditor && tinyMCE.activeEditor.editorId) { tinyMCE.execCommand('mceRemoveControl', false, tinyMCE.activeEditor.editorId); } var cols = $('column-container'); forEach(<API key>(null, '<API key>', cols), function (e) { showElement(<API key>(null, 'mediaplayer', e)); setStyle(e, {'height': 'auto'}); }); forEach(<API key>(null, '<API key>', cols), function (e) { addElementClass(e, 'hidden'); removeElementClass(e.previousSibling, 'hidden'); removeElement(e); }); removeElement('overlay'); } this.addConfigureBlock = function(oldblock, configblock, removeoncancel) { self.hideMediaPlayers(); var temp = DIV(); temp.innerHTML = configblock.html; var newblock = <API key>('div', 'blockinstance', temp); hideElement(newblock); appendChildNodes(<API key>('body'), newblock); var style = { 'position': 'absolute', 'z-index': 1 }; var d = <API key>(newblock); var vpdim = <API key>(); var h = Math.max(d.h, 200); var w = Math.max(d.w, 500); if (config.blockeditormaxwidth && <API key>('textarea', 'wysiwyg', newblock)) { w = vpdim.w - 80; style.height = h + 'px'; } var tborder = parseFloat(getStyle(newblock, 'border-top-width')); var tpadding = parseFloat(getStyle(newblock, 'padding-top')); var newtop = getViewportPosition().y + Math.max((vpdim.h - h) / 2 - tborder - tpadding, 5); style.top = newtop + 'px'; var lborder = parseFloat(getStyle(newblock, 'border-left-width')); var lpadding = parseFloat(getStyle(newblock, 'padding-left')); style.left = ((vpdim.w - w) / 2 - lborder - lpadding) + 'px'; style.width = w + 'px'; setStyle(newblock, style); var deletebutton = <API key>('input', 'deletebutton', newblock); if (removeoncancel) { self.rewriteDeleteButton(deletebutton); var oldblockid = newblock.id.substr(0, newblock.id.length - '_configure'.length); var blockinstanceId = oldblockid.substr(oldblockid.lastIndexOf('_') + 1); var cancelbutton = $('<API key>' + blockinstanceId); if (cancelbutton) { setNodeAttribute(cancelbutton, 'name', getNodeAttribute(deletebutton, 'name')); disconnectAll(cancelbutton); self.rewriteCancelButton(cancelbutton, blockinstanceId); } } else { disconnectAll(deletebutton); connect(deletebutton, 'onclick', function(e) { e.stop(); self.<API key>(); self.showMediaPlayers(); }); } showElement(newblock); eval(configblock.javascript); } this.<API key> = function(data) { var oldblock = $('blockinstance_' + data.blockid); if (oldblock) { var temp = DIV(); temp.innerHTML = data.data.html; var newblock = <API key>('div', 'blockinstance', temp) swapDOM(oldblock, newblock); eval(data.data.javascript); self.<API key>(newblock); self.<API key>(<API key>('input', 'configurebutton', newblock)); self.rewriteDeleteButton(<API key>('input', 'deletebutton', newblock)); } self.<API key>(); self.showMediaPlayers(); } this.<API key> = function() { // FF3 hangs unless you delay removal of the iframe inside the old configure block callLater(0.0001, function () { forEach(<API key>('div', 'configure'), removeElement); }); } /** * Rewrites the blockinstance delete buttons to be AJAX */ this.<API key> = function() { forEach(<API key>('input', 'deletebutton', self.bottomPane), function(i) { self.rewriteDeleteButton(i); }); } /** * Rewrites one delete button to be AJAX */ this.rewriteDeleteButton = function(button) { connect(button, 'onclick', function(e) { setNodeAttribute(button, 'disabled', 'disabled'); if (confirm(get_string('<API key>'))) { var pd = {'id': $('viewid').value, 'change': 1}; pd[getNodeAttribute(e.src(), 'name')] = 1; sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', pd, 'POST', function(data) { var blockinstanceId = button.name.substr(button.name.lastIndexOf('_') + 1); removeElement('blockinstance_' + blockinstanceId); if ($('blockinstance_' + blockinstanceId + '_configure')) { self.<API key>(); self.showMediaPlayers(); } }, function() { removeNodeAttribute(button, 'disabled'); }); } else { removeNodeAttribute(button, 'disabled'); } e.stop(); }); } /** * Rewrites cancel button to remove a block */ this.rewriteCancelButton = function(button, blockinstanceId) { connect(button, 'onclick', function(e) { var pd = {'id': $('viewid').value, 'change': 1}; pd[getNodeAttribute(e.src(), 'name')] = 1; sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', pd, 'POST', function(data) { removeElement('blockinstance_' + blockinstanceId); if ($('blockinstance_' + blockinstanceId + '_configure')) { self.<API key>(); self.showMediaPlayers(); } }); e.stop(); }); } /** * Rewrites the add column buttons to be AJAX * * If the first parameter is a string/element, only the buttons below that * element will be rewritten */ this.<API key> = function() { var parentNode; if (typeof(arguments[0]) != 'undefined') { parentNode = arguments[0]; } else { parentNode = self.bottomPane; } forEach(<API key>('input', 'addcolumn', parentNode), function(i) { connect(i, 'onclick', function(e) { // Work around for a konqueror bug - konqueror passes onclick // events to disabled buttons if (!i.disabled) { setNodeAttribute(i, 'disabled', 'disabled'); var name = getNodeAttribute(e.src(), 'name'); var id = parseInt(name.substr(name.length - 1, 1)); var pd = {'id': $('viewid').value, 'change': 1} pd['<API key>' + id] = 1; sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', pd, 'POST', function(data) { self.addColumn(id, data); self.<API key>(); }, function() { self.<API key>(); }); } e.stop(); }); }); } /** * Rewrite the remove column buttons to be AJAX * * If the first parameter is a string/element, only the buttons below that * element will be rewritten */ this.<API key> = function() { var parentNode; if (typeof(arguments[0]) != 'undefined') { parentNode = arguments[0]; } else { parentNode = self.bottomPane; } forEach(<API key>('input', 'removecolumn', parentNode), function(i) { connect(i, 'onclick', function(e) { // Work around for a konqueror bug - konqueror passes onclick // events to disabled buttons if (!i.disabled) { setNodeAttribute(i, 'disabled', 'disabled'); var name = getNodeAttribute(e.src(), 'name'); var id = parseInt(name.substr(name.length - 1, 1)); var pd = {'id': $('viewid').value, 'change': 1} pd['<API key>' + id] = 1; sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', pd, 'POST', function(data) { self.removeColumn(id); self.<API key>(); }, function() { self.<API key>(); }); } e.stop(); }); }); } /** * Disables the 'add column' buttons */ this.<API key> = function() { // Get the existing number of columns var numColumns = parseInt(getNodeAttribute(<API key>('div', 'column', self.bottomPane), 'class').match(/columns([0-9]+)/)[1]); var state = (numColumns == 5); forEach(<API key>('input', 'addcolumn', self.bottomPane), function(i) { if (state) { setNodeAttribute(i, 'disabled', 'disabled'); } else { removeNodeAttribute(i, 'disabled'); } }); var state = (numColumns == 1); forEach(<API key>('input', 'removecolumn', self.bottomPane), function(i) { if (state) { setNodeAttribute(i, 'disabled', 'disabled'); } else { removeNodeAttribute(i, 'disabled'); } }); } /** * Makes block instances draggable */ this.<API key> = function() { forEach(<API key>('div', 'blockinstance', self.bottomPane), function(i) { self.<API key>(i); }); } /** * Make a particular blockinstance draggable */ this.<API key> = function(blockinstance) { new Draggable(blockinstance, { 'handle': '<API key>', 'starteffect': function () { self.<API key> = blockinstance; self.origCoordinates = self.<API key>(blockinstance); self.createHotzones(); // Set the positioning of the blockinstance to 'absolute', // so that it is taken out of the document flow (so the // other blocks can collapse into its space if necessary if // it's dragged around). This changes how the width is // calculated, as the width is 'auto' by default, so we // explicitly set it to have the width it needs. var dimensions = elementDimensions(blockinstance); setStyle(blockinstance, { 'position': 'absolute' }); <API key>(blockinstance, dimensions); // Resize the placeholder div // NOTE: negative offset to account for the border. This might be removed <API key>(self.blockPlaceholder, {h: dimensions.h - 2}); setStyle(self.blockPlaceholder, {'width': '100%'}); setOpacity(blockinstance, 0.5); }, 'revert': true, 'reverteffect': function (innerelement, top_offset, left_offset) { self.destroyHotzones(); // This in IE7 can cause major headaches - dragging a block // when it's the only one in the column and releasing it there // will cause the entire bottom pane to move up over the top // pane if (!self.isIE7) { // Removing the block placeholder then reverting the position // of the dragged blockinstance results in a flash where the // height of the page reduces and then expands again. We can // fix this <API key>(self.bottomPane, <API key>(self.bottomPane)); // LEAVE THIS LINE // Without it, firefox doesn't actually set the element // dimensions properly, it seems, resulting in the very flash // we are trying to get rid of <API key>(self.bottomPane); } // We don't need the block placeholder anymore removeElement(self.blockPlaceholder); // Revert the 'absolute' positioning of the blockinstance being moved setStyle(self.<API key>, { 'position': 'relative', 'top': 0, 'left': 0, 'width': 'auto', 'height': 'auto' }); // Revert the explicit size setting for the bottom pane setStyle(self.bottomPane, { 'width': 'auto', 'height': 'auto' }); // No longer is there a 'last hotzone' that was being dragged over self.lastHotzone = null; setOpacity(blockinstance, 1); // Sadly we have to return an effect, because this requires // something cancellable. Would be good to return nothing return new MochiKit.Visual.Move(innerelement, {x: 0, y: 0, duration: 0}); } }); } /** * Makes block types draggable */ this.<API key> = function() { forEach(<API key>('div', 'blocktype', 'blocktype-list'), function(i) { // Overlay a div that is actually the thing that is dragged. This // is done because MochiKit's ghosting actually drags the element, // meaning revert ends up with a horrid flash when the element is // moved back into place makePositioned(i); var clone = DIV({'class': 'blocktype-clone'}); // IE doesn't think that this div has a style object, probably // because it's not in the DOM yet if (!self.isIE7) { setStyle(clone, { 'border': '0px dotted transparent;', 'position': 'absolute' }); } if (self.isIE7 || self.isIE6) { appendChildNodes(clone, i.cloneNode(true)); hideElement(i); } else { setElementPosition(clone, getElementPosition(i, 'top-pane')); setOpacity(clone, 0.5); } <API key>(i, clone); <API key>(clone, <API key>(i)); // Prevents the height of the blocktype list doubling when dragging if (self.isIE7) { i.style.position = 'absolute'; } new Draggable(clone, { 'starteffect': function () { self.movingBlockType = true; self.<API key> = i; self.createHotzones(); // Resize the placeholder div setStyle(self.blockPlaceholder, { 'width' : '100%', 'height': '50px' }); // Make it a ghost. Done when starting the drag because // some browsers have trouble rendering things right on top // of one another if (self.isIE7 || self.isIE6) { showElement(i); setOpacity(clone, 0.5); } else { appendChildNodes(clone, i.cloneNode(true)); } }, 'revert': true, 'reverteffect': function (innerelement, top_offset, left_offset) { if (self.isIE7 || self.isIE6) { // Move the clone back and hide the filler used while // dragging setElementPosition(clone, {x: 0, y: 0}); hideElement(i); setOpacity(clone, 1); } else { // The actual draggable is the clone we were dragging // around, we can put it back and remove the clone now replaceChildNodes(clone); setElementPosition(clone, getElementPosition(i, 'top-pane')); } self.destroyHotzones(); // No longer is there a 'last hotzone' that was being dragged over self.lastHotzone = null; // We don't need the block placeholder anymore, but it // still might be needed in the dropfunction, as the // reverteffect is called before the dropfunction. So we // only hide it here hideElement(self.blockPlaceholder); self.movingBlockType = false; // Sadly we have to return an effect, because this requires // something cancellable. Would be good to return nothing return new MochiKit.Visual.Move(innerelement, {x: 0, y: 0, duration: 0}); } }); }); } /** * changes the intructions so they are for ajax */ this.ajaxInstructions = function() { $('blocksinstruction').innerHTML = get_string('<API key>'); } /** * Wire up the view theme selector */ this.<API key> = function() { if (!self.viewThemeSelect) { return; } var currentTheme = self.viewThemeSelect.selectedIndex; connect(self.viewThemeSelect, 'onchange', function(e) { var choice = self.viewThemeSelect.options[self.viewThemeSelect.selectedIndex]; if (self.viewThemeSelect.selectedIndex != currentTheme && choice.value) { self.viewThemeSelect.form.submit(); } }); } this.createHotzones = function() { // Make a container for all of the hotzone divs self.hotzoneContainer = DIV(); appendChildNodes(self.columnContainer, self.hotzoneContainer); var previousHotzone = null; // Keeps track of whether we have seen the blockinstance that is being // dragged in this column yet var <API key> = false; // We place the hotzones by looping through the blockinstances on the // page and adding the hotzones to over the top of them as appropriate forEach(<API key>('div', 'blockinstance', self.bottomPane), function(i) { var <API key> = elementPosition(i, self.columnContainer); var <API key> = elementDimensions(i); // NOTE: added for the border <API key>.w += 4; // Work out whether the given blockinstance is at the top of the column if (<API key>('div', 'blockinstance', <API key>(i, 'div', 'column-content')) == i) { // Put a hotzone across the top half of the blockinstance var hotzone = self.createHotzone(i, <API key>); setElementPosition(hotzone, {x: <API key>.x, y:0}); <API key>(hotzone, {w: <API key>.w, h: <API key>.h / 2 + <API key>.y}); previousHotzone = hotzone; <API key> = false; } // Work out if there is a blockinstance below the current one var nextBlockinstance = i.nextSibling; var <API key> = null; var <API key> = null; while (nextBlockinstance != null) { if (hasElementClass(nextBlockinstance, 'blockinstance')) { // If there is one, work out its position and dimensions for later <API key> = elementPosition(nextBlockinstance, self.columnContainer); <API key> = elementDimensions(nextBlockinstance); break; } nextBlockinstance = nextBlockinstance.nextSibling; } // Work out the position and size of the previous hotzone, for use // in placing the next hotzone var <API key> = elementPosition(previousHotzone, self.columnContainer); var <API key> = elementDimensions(previousHotzone); // If there is a blockinstance below this one, then we put another // hotzone covering half of the current blockinstance and half on // the one below we found. Otherwise, we just cover the rest of the // column. if (nextBlockinstance) { // The trickiest part about the hotzone implementation. Who // owns the hotzone, and whether the placeholder is inserted // before or after the owner, is important here - getting it // right means when the block switches hotzones, the // placeholder moves to the correct location. // If the blockinstance being moved is not in the same column, // it's relatively simple - just make the owner the current // blockinstance. // If it is in the same column, we make the owner the current // blockinstance, until we hit the blockinstance being moved, // when we switch to using the next block instance. var element; if (self.<API key> == i || <API key>) { element = nextBlockinstance; <API key> = true; } else { element = i; <API key> = false; } var hotzone = self.createHotzone(element, <API key>, true); // We need to place a hotzone over the bottom half of the // current block instance, and the top half of the next setElementPosition(hotzone, {x: <API key>.x, y: <API key>.y + <API key>.h}); <API key>(hotzone, { w: <API key>.w, h: (<API key>.y + (<API key>.h / 2)) - (<API key>.y + (<API key>.h / 2)) }); } else { // We've reached the end of the blockinstances, we place a // hotzone over the end of the column. // FIXME: place it from the bottom half of the last block to the bottom of the page var hotzone = self.createHotzone(i, <API key>, true); var <API key> = elementPosition(self.columnContainer); var <API key> = elementDimensions(self.columnContainer); var footerDimensions = <API key>('footer-wrap', self.bottomPane); var footerPosition = getElementPosition('footer-wrap', self.bottomPane); setElementPosition(hotzone, {x: <API key>.x, y: <API key>.y + <API key>.h}); <API key>(hotzone, { w: <API key>.w, h: (footerPosition.y + footerDimensions.h) - (<API key>.y + <API key>.h) }); } previousHotzone = hotzone; }); forEach(<API key>('div', 'column', 'column-container'), function(i) { if (!<API key>('div', 'blockinstance', i)) { // Column with no blockinstances var columnContent = <API key>('div', 'column-content', i); var hotzone = self.createHotzone(columnContent, appendChildNodes, true); var footerDimensions = <API key>('footer-wrap', self.bottomPane); var footerPosition = getElementPosition('footer-wrap', self.bottomPane); setElementPosition(hotzone, {x: getElementPosition(columnContent, self.columnContainer).x, y: 0}); <API key>(hotzone, { w: <API key>(columnContent).w, h: footerPosition.y + footerDimensions.h }); // The column content may have whitespace in it. This // whitespace causes the box to respect line-height, which // pushes down where the blocks appear when dragged into the // column. Removing all the children nodes fixes this replaceChildNodes(columnContent); previousHotzone = hotzone; } }); } /** * Creates a new hotzone and puts it in the DOM, ready for use * * Hotzones are used for the drag and drop stuff, to detect where the * currently dragged block should land * * @param node The node to use as a reference for putting the placeholder in * @param function The DOM function to use to insert the placeholder relative to the node */ this.createHotzone = function(node, placementFunction) { //var hotzone = DIV({'style': 'outline: 1px solid black; position: absolute;'}); var hotzone = DIV({'style': 'position: absolute;'}); // Whether to place a newly dropped block type after the element on // whose hotzone it was dropped. True always except at the top of // columns. // For some reason, using the (supposedly equal) check // placementFunction != <API key> cause chaos when you // try and drop just after the start of a column (i.e. order 2) and // then at the very start - it gets dropped at order 2 twice. var placeAfter = arguments[2]; placementFunction = partial(placementFunction, node, self.blockPlaceholder); if (self.movingBlockType) { dropFunction = function(draggable, node, placeAfter) { var whereTo = self.<API key>(node); if (placeAfter) { whereTo['order'] += 1; } var pd = { 'id': $('viewid').value, 'change': 1, 'blocktype': <API key>('input', 'blocktype-radio', self.<API key>).value }; if (config.blockeditormaxwidth) { pd['cfheight'] = <API key>().h - 100; } pd['<API key>' + whereTo['column'] + '_order_' + whereTo['order']] = true; sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', pd, 'POST', function(data) { var div = DIV(); div.innerHTML = data.data.display.html; var blockinstance = <API key>('div', 'blockinstance', div); // Make configure button clickable, but disabled as blocks are rendered in configure mode by default var configureButton = <API key>('input', 'configurebutton', blockinstance); if (configureButton) { self.<API key>(configureButton); $('action-dummy').name = '<API key>' + whereTo['column'] + '_order_' + whereTo['order']; } self.rewriteDeleteButton(<API key>('input', 'deletebutton', blockinstance)); self.<API key>(blockinstance); <API key>(self.blockPlaceholder, blockinstance); removeElement(self.blockPlaceholder); if (data.data.configure) { self.addConfigureBlock(blockinstance, data.data.configure, true); } }); }; } else if (placementFunction == appendChildNodes) { dropFunction = partial(appendChildNodes, node); } else { dropFunction = partial(<API key>, self.blockPlaceholder); } self.<API key>(hotzone, node, placementFunction, dropFunction, placeAfter); appendChildNodes(self.hotzoneContainer, hotzone); return hotzone; } /** * Makes a hotzone droppable. In a separate function for scoping purposes */ this.<API key> = function(hotzone, node, placementFunction, dropFunction, placeAfter) { var counter = 5; new Droppable(hotzone, { 'onhover': function() { if (counter++ == 5) { counter = 0; if (self.lastHotzone != hotzone) { self.lastHotzone = hotzone; // Put the placeholder div in place. placementFunction(); showElement(self.blockPlaceholder); } } }, 'ondrop': function(draggable, droppable, e) { e.stop(); // Only pass through the placeAfter parameter when appropriate, // as the dropfunction could be a simple DOM function if (self.movingBlockType) { dropFunction(draggable, node, placeAfter); } else { dropFunction(draggable); } if (!self.movingBlockType) { // Work out where to send the block to var whereTo = self.<API key>(draggable); if (self.origCoordinates.column != whereTo.column || self.origCoordinates.order != whereTo.order) { var pd = {'id': $('viewid').value, 'change': 1}; pd['<API key>' + draggable.id.substr(draggable.id.lastIndexOf('_') + 1) + '_column_' + whereTo['column'] + '_order_' + whereTo['order']] = 1; sendjsonrequest(config['wwwroot'] + 'view/blocks.json.php', pd, 'POST'); } } } }); } /** * Removes hotzones from the document. * * This is trivially implemented as removing the div that contains them all */ this.destroyHotzones = function() { removeElement(self.hotzoneContainer); } /** * Find the co-ordinates of a given block instance * * This returns a {column: x, order: y} hash */ this.<API key> = function(blockinstance) { // Work out where to send the block to var columnContainer = <API key>(blockinstance, 'div', 'column'); var column = columnContainer.id.substr(columnContainer.id.lastIndexOf('_') + 1); var order = 0; forEach(<API key>('div', 'column-content', columnContainer).childNodes, function(i) { if (hasElementClass(i, 'blockinstance')) { order++; } if (i == blockinstance) { throw MochiKit.Iter.StopIteration; } }); return {'column': column, 'order': order}; } /** * Adds CSS rules that should apply for the javascript only version */ this.addCSSRules = function() { var styleNode = createDOM('link', { 'rel' : 'stylesheet', 'type': 'text/css', 'href': config['wwwroot'] + 'theme/views-js.css' }); appendChildNodes(<API key>('head'), styleNode); } // Whether it is a blocktype that is being added, rather than a // blockinstance being moved this.movingBlockType = false; // The object that is currently being moved by drag and drop - either a // block instance or block type this.<API key> = null; // The original (column, order) coordinates of the currently moving // blockinstance this.origCoordinates = null; // The last hotzone that was hovered over this.lastHotzone = null; // The placeholder that shows where the blockinstance will be placed when // it is dropped. Needs a margin the same as the blockinstances this.blockPlaceholder = DIV({'id': 'block-placeholder'}); // The column container - set in self.init this.columnContainer = null; // The bottom pane - set in self.init this.bottomPane = null; // The view theme select element - set in self.init this.viewThemeSelect = null; // Whether the browser is IE7 - needed for some hacks this.isIE7 = document.all && document.documentElement && typeof(document.documentElement.style.maxHeight) != "undefined" && !window.opera; // Whether the browser is IE6 this.isIE6 = !this.isIE7 && document.all && !window.opera; // Whether the brower is iPhone, IPad or IPod if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) { this.isIE6 = true; // work-around for broken drag-and-drop } addLoadEvent(self.init); } viewManager = new ViewManager(); viewManager.addCSSRules(); function blockConfigSuccess(form, data) { if (data.formelementsuccess) { eval(data.formelementsuccess + '(form, data)'); } if (data.blockid) { if (viewManager.isIE6 && data.viewid) { document.location.href = config['wwwroot'] + 'view/blocks.php?id=' + data.viewid; } viewManager.<API key>(data); } } function blockConfigError(form, data) { if (data.formelementerror) { eval(data.formelementerror + '(form, data)'); return; } }
def find_factorial_loop(n): factorial = 1 for i in range(n, 0, -1): # alternatively, for i in range(1, n + 1): factorial *= i return factorial def <API key>(n): if n == 0: return 1 else: return n * <API key>(n - 1) def main(): number = 5 print(find_factorial_loop(number)) print(<API key>(number)) if __name__ == "__main__": main()
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp.Common; using SharpDX; namespace <API key>.Structures { class Monster { public struct MonsterBar { public int BarWidth; public int XOffset; public int YOffsetBegin; public int YOffsetEnd; public MonsterBar(int barWidth, int xoffset, int yOffsetBegin, int yOffsetEnd) { BarWidth = barWidth; XOffset = xoffset; YOffsetBegin = yOffsetBegin; YOffsetEnd = yOffsetEnd; } } public static Dictionary<string, Vector2> MonsterLocations = new Dictionary<string, Vector2>() { {"Neutral.Dragon",SummonersRift.River.Dragon}, {"Neutral.Baron",SummonersRift.River.Baron}, {"Chaos.Red",new Vector2(7016.869f, 10775.55f)}, {"Chaos.Blue",new Vector2(10931.73f, 6990.844f)}, {"Order.Red",new Vector2(7862.244f, 4111.187f)}, {"Order.Blue",new Vector2(3871.489f, 7901.054f)} }; public static Dictionary<string, MonsterBar> <API key> = new Dictionary<string, MonsterBar>() { {"SRU_Red",new MonsterBar(145,3,18,10)}, {"SRU_Blue",new MonsterBar(145,3,18,10)}, {"SRU_Dragon",new MonsterBar(145,3,18,10)}, {"SRU_Baron",new MonsterBar(194,-22,13,16)}, {"SRU_Crab",new MonsterBar(61,45,34,3)}, {"SRU_Krug",new MonsterBar(81,58,18,4)}, {"SRU_Gromp",new MonsterBar(87,62,18,4)}, {"SRU_Murkwolf",new MonsterBar(75,54,19,4)}, {"SRU_Razorbeak",new MonsterBar(75,54,18,4)} }; } }
<?php require_once 'LorisTest.php'; class TestOfTimepointList extends LorisTest { /** * Test that the timepoint_list page is not accessible if * the user is not logged in * * @return null */ function testTPLLoggedOut() { $this->get( $this->url . "/main.php?test_name=timepoint_list&candID=" . $this->CandID ); $this->assertPattern("/Password/", "Could access candidate_list logged out"); } /** * Test the timepoint_list page. This checks that the timepoint_list * page is accessible, and that it contains all the visits for the * candidate specified for testing in the config.xml. * * It also checks that there's at least 1 session for that candidate, * since otherwise it's a useless test. * * @return null */ function testTPLGetPage() { $main_link = "$this->url" . "/main.php?test_name=timepoint_list&candID=" . $this->CandID; $this->login("UnitTester", "4test4"); $this->get($main_link); $this-><API key>(); $this->assertResponse(200, "Could not access timepoint_list as UnitTester"); $this->assertPattern( "/Candidate Profile/", "Page does not appear to have header" ); $this->assertNoPattern("/Password/", "Unexpectedly got login page"); $this->assertNoPattern( "/Visit Label \(Click to Open\)/", "Table appears to be missing" ); $sessions = $this->DB->pselect( "SELECT Visit_label, ID FROM session WHERE CandID=:CaID AND Active='Y'", array('CaID' => $this->CandID) ); $this->assertTrue( count($sessions) > 0, "Candidate does not have any sessions" ); foreach ($sessions as $row) { $vl = $row['Visit_label']; $sid = $row['ID']; $this->assertLink( $vl, true, "Missing link for Visit Label $vl at $main_link" ); } } } ?>
<HTML><BODY>A book called "Continents and Cosmology" stands out.<br> <Button ALIGN=LEFT ICON="QUEST" action="bypass -h npc_%objectId%_Quest">Quest</Button> </body></html>
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "../../src/common/dttypes.h" typedef float elem_type; #define ELEM_SWAP(a,b) { elem_type t=(a);(a)=(b);(b)=t; } static elem_type kth_smallest(elem_type a[], int n, int k) { int i,j,l,m ; elem_type x ; l=0 ; m=n-1 ; while (l<m) { x=a[2*k+1] ; i=l ; j=m ; do { while (a[2*i+1]<x) i++ ; while (x<a[2*j+1]) j if (i<=j) { ELEM_SWAP(a[2*i+1],a[2*j+1]) ; i++ ; j } } while (i<=j) ; if (j<k) l=i ; if (k<i) m=j ; } return a[2*k+1] ; } #define median(a,n) kth_smallest(a,n,(((n)&1)?((n)/2):(((n)/2)-1))) static float* read_pfm(const char *filename, int *wd, int*ht) { FILE *f = fopen(filename, "rb"); if(!f) return 0; fscanf(f, "PF\n%d %d\n%*[^\n]", wd, ht); fgetc(f); // eat only one newline float *p = (float *)malloc(sizeof(float)*3*(*wd)*(*ht)); fread(p, sizeof(float)*3, (*wd)*(*ht), f); for(int k=0;k<3*(*wd)*(*ht);k++) p[k] = fmaxf(0.0f, p[k]); fclose(f); return p; } static float* read_histogram(const char *filename, int *bins) { *bins = 0; FILE *f = fopen(filename, "rb"); if(!f) return 0; while(!feof(f)) { fscanf(f, "%*f %*f %*f %*f %*f %*f %*f %*f %*f %*f\n"); (*bins) ++; } fseek(f, 0, SEEK_SET); // second round, alloc and read float *hist = (float *)malloc(sizeof(float) * 3 * (*bins)); int k=0; while(!feof(f)) { fscanf(f, "%*f %*f %*f %*f %*f %*f %*f %f %f %f\n", hist + 3*k, hist+3*k+1, hist+3*k+2); k++; } fclose(f); return hist; } static void invert_histogram( const float *const hist, float *const inv_hist, const int bins) { // invert non-normalised accumulated hist for(int c=0;c<3;c++) { int last = 0; for(int i=last+1; i<bins; i++) { for(int k=last; k<bins; k++) { if(hist[3*k+c] >= i/(float)bins) { last = k; inv_hist[3*i+c] = k/(float)bins; break; } } } } } #if 0 static void write_pfm(const char *filename, float *buf, int wd, int ht) { FILE *f = fopen(filename, "wb"); if(!f) return; fprintf(f, "PF\n%d %d\n-1.0\n", wd, ht); fwrite(buf, sizeof(float)*3, wd*ht, f); fclose(f); } #endif #define MIN(a,b) ((a>b)?b:a) #define MAX(a,b) ((a>b)?a:b) #define N 300 static inline float clamp(float f, float m, float M) { return MAX(MIN(f, M), m); } int compare_llhh(const void *a, const void *b) { return (int)clamp(((float *)a)[0]*N, 0, N-1) - (int)clamp(((float *)b)[0]*N, 0, N-1); } int main(int argc, char *arg[]) { if(argc < 2) { fprintf(stderr, "usage: %s input.pfm [-c a1 b1]\n", arg[0]); exit(1); } int wd, ht; float *input = read_pfm(arg[1], &wd, &ht); float max = 0.0f; // sanity checks: // for(int k=0;k<3*wd*ht;k++) input[k] = clamp(input[k], 0.0f, 1.0f); // correction requested? if(argc >= 9 && !strcmp(arg[2], "-c")) { const dt_aligned_pixel_t a = { atof(arg[3]), atof(arg[4]), atof(arg[5]) }, b = { atof(arg[6]), atof(arg[7]), atof(arg[8]) }; // const float m[3] = {1, 1, 1}; // 2.0f*sqrt(a[0]*1.0f+b[0])/a[0], // 2.0f*sqrt(a[1]*1.0f+b[1])/a[1], // 2.0f*sqrt(a[2]*1.0f+b[2])/a[2]}; #if 1 // dump curves: for(int k=0;k<N;k++) { for(int c=0;c<3;c++) { // const float y = k/(N-1.0f); // const float x = m[c]*m[c]*a[c]*y*y/4.0f - b[c]/a[c]; float x = k/(N-1.0f)/a[c]; const float d = fmaxf(0.0f, x + 3./8. + (b[c]/a[c])*(b[c]/a[c])); x = 2.0f*sqrtf(d); fprintf(stderr, "%f ", x); } fprintf(stderr, "\n"); } #endif for(int k=0;k<wd*ht;k++) { for(int c=0;c<3;c++) { // input[3*k+c] = 2.0f*sqrtf(a[c]*input[3*k+c]+b[c])/(a[c]*m[c]); input[3*k+c] = input[3*k+c] / a[c]; const float d = fmaxf(0.0f, input[3*k+c] + 3./8. + (b[c]/a[c])*(b[c]/a[c])); input[3*k+c] = 2.0f*sqrtf(d); max = fmaxf(max, input[3*k+c]); } } for(int k=0;k<3*wd*ht;k++) input[k] /= max; } else if(argc >= 4 && !strcmp(arg[2], "-h")) { int bins = 0; float *hist = read_histogram(arg[3], &bins); float *inv_hist = (float *)malloc(sizeof(float) * 3 * bins); invert_histogram(hist, inv_hist, bins); #if 1 // output curves and their inverse: for(int k=0;k<bins;k++) // fprintf(stderr, "%f %f %f %f %f %f %f\n", k/(float)bins, hist[3*k], hist[3*k+1], hist[3*k+2], inv_hist[3*k], inv_hist[3*k+1], inv_hist[3*k+2]); fprintf(stderr, "%f %f %f\n", inv_hist[3*k], inv_hist[3*k+1], inv_hist[3*k+2]); // fprintf(stderr,"scanned %d bins\n", bins); #endif for(int k=0;k<wd*ht;k++) { for(int c=0;c<3;c++) { float f = clamp(input[3*k+c]*bins, 0, bins-2); const int bin = (int)f; f -= bin; input[3*k+c] = (1.0f-f)*inv_hist[3*bin+c] + f*inv_hist[3*(bin+1)+c]; } } } float std[N][3] = {{0.0f}}; float cnt[N][3] = {{0.0f}}; // one level haar decomposition, separable, decimated, lifting scheme for(int j=0;j<ht;j++) { for(int i=0;i<wd-1;i+=2) { float *buf = input + 3*(wd*j + i); for(int c=0;c<3;c++) { buf[c] += buf[3+c]; buf[c] *= .5f; buf[3+c] -= buf[c]; } // buf += 3; } } for(int i=0;i<wd;i++) { for(int j=0;j<ht-1;j+=2) { float *buf = input + 3*(wd*j + i); for(int c=0;c<3;c++) { buf[c] += buf[3*wd+c]; buf[c] *= .5f; buf[3*wd+c] -= buf[c]; } // buf += 3*wd; } } #if 0 // debug: write full wavelet transform: write_pfm("wt.pfm", input, wd, ht); // debug: write LL float *out = (float *)malloc(sizeof(float)*3*wd/2*ht/2); for(int j=0;j<ht-1;j+=2) { for(int i=0;i<wd-1;i+=2) { for(int c=0;c<3;c++) { out[3*((wd/2)*(j/2)+(i/2))+c] = input[3*(wd*j+i)+c]; } } } write_pfm("LL.pfm", out, wd/2, ht/2); free(out); #endif // sort pairs (LL,HH) for each color channel: float *llhh = (float *)malloc(sizeof(float)*wd*ht/2); for(int c=0;c<3;c++) { int k = 0; for(int j=0;j<ht-1;j+=2) { for(int i=0;i<wd-1;i+=2) { llhh[2*k] = input[3*(wd*j+i)+c]; llhh[2*k+1] = fabsf(input[3*(wd*(j+1)+(i+1))+c]); k++; } } qsort(llhh, k, 2*sizeof(float), compare_llhh); // estimate std deviation for every bin we've got: for(int begin=0;begin<k;) { // LL is used to estimate brightness: const int bin = (int)clamp(llhh[2*begin]*N, 0, N-1); int end = begin+1; while((end < k) && ((int)clamp(llhh[2*end]*N, 0, N-1) == bin)) end++; assert(end >= k || bin <= (int)clamp(llhh[2*end]*N, 0, N-1)); // fprintf(stderr, "from %d (%d) -- %d (%d)\n", begin, bin, end, (int)clamp(llhh[2*end]*N, 0, N-1)); // estimate noise by robust statistic (assumes zero mean of HH band): // MAD: median(|Y - med(Y)|) = 0.6745 sigma // if(end - begin > 10) // fprintf(stdout, "%d %f %d\n", bin, median(llhh+2*begin, end-begin)/0.6745, end - begin); std[bin][c] += median(llhh+2*begin, end-begin)/0.6745; cnt[bin][c] = end - begin; begin = end; } } #if 0 // recover noise curve: for(int k=0;k<wd*ht;k++) { for(int c=0;c<3;c++) { const int i = clamp(ref[3*k+c]*N, 0, N-1); cnt[i][c] ++; const float diff = input[3*k+c] - ref[3*k+c]; // assume zero mean: var[i][c] += diff*diff; // - E(X^2) } } #endif #if 0 // normalize for(int i=0;i<N;i++) for(int c=0;c<3;c++) if(cnt[i][c] > 0.0f) std[i][c] /= cnt[i][c]; else std[i][c] = 0.0f; #endif // scale back in case we needed to bin it down: if(max > 0.0f) for(int i=0;i<N;i++) for(int k=0;k<3;k++) std[i][k] *= max; // output variance per brightness level: // fprintf(stdout, "# bin std_r std_g std_b hist_r hist_g hist_b cdf_r cdf_g cdf_b\n"); dt_aligned_pixel_t sum = {0.0f}; for(int i=0;i<N;i++) for(int k=0;k<3;k++) sum[k] += std[i][k]; dt_aligned_pixel_t cdf = {0.0f}; for(int i=0;i<N;i++) { fprintf(stdout, "%f %f %f %f %f %f %f %f %f %f\n", i/(float)N, std[i][0], std[i][1], std[i][2], cnt[i][0], cnt[i][1], cnt[i][2], cdf[0]/sum[0], cdf[1]/sum[1], cdf[2]/sum[2]); // cdf[0], cdf[1], cdf[2]); for(int k=0;k<3;k++) cdf[k] += std[i][k]; } free(llhh); free(input); exit(0); }
package org.ovirt.engine.ui.webadmin.section.main.view.tab.network; import java.util.Arrays; import javax.inject.Inject; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.businessentities.network.NetworkView; import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface; import org.ovirt.engine.core.common.utils.PairQueryable; import org.ovirt.engine.ui.common.idhandler.ElementIdHandler; import org.ovirt.engine.ui.common.uicommon.model.<API key>; import org.ovirt.engine.ui.common.view.ViewRadioGroup; import org.ovirt.engine.ui.common.widget.table.column.<API key>; import org.ovirt.engine.ui.common.widget.table.column.RxTxRateColumn; import org.ovirt.engine.ui.common.widget.table.column.<API key>; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkListModel; import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkVmFilter; import org.ovirt.engine.ui.uicommonweb.models.networks.NetworkVmListModel; import org.ovirt.engine.ui.webadmin.<API key>; import org.ovirt.engine.ui.webadmin.<API key>; import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.network.<API key>; import org.ovirt.engine.ui.webadmin.section.main.view.<API key>; import org.ovirt.engine.ui.webadmin.widget.action.<API key>; import org.ovirt.engine.ui.webadmin.widget.table.column.VmStatusColumn; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.RadioButton; public class SubTabNetworkVmView extends <API key><NetworkView, PairQueryable<VmNetworkInterface, VM>, NetworkListModel, NetworkVmListModel> implements <API key>.ViewDef { interface ViewIdHandler extends ElementIdHandler<SubTabNetworkVmView> { ViewIdHandler idHandler = GWT.create(ViewIdHandler.class); } private final <API key> constants; private final <API key> templates; private final ViewRadioGroup<NetworkVmFilter> viewRadioGroup; @Inject public SubTabNetworkVmView(<API key><PairQueryable<VmNetworkInterface, VM>, NetworkListModel, NetworkVmListModel> modelProvider, <API key> constants, <API key> templates) { super(modelProvider); ViewIdHandler.idHandler.generateAndSetIds(this); this.constants = constants; this.templates = templates; viewRadioGroup = new ViewRadioGroup<NetworkVmFilter>(Arrays.asList(NetworkVmFilter.values())); viewRadioGroup.setSelectedValue(NetworkVmFilter.running); viewRadioGroup.addStyleName("<API key>"); //$NON-NLS-1$ initTable(); initWidget(getTable()); } private void initTableOverhead() { viewRadioGroup.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (((RadioButton) event.getSource()).getValue()) { <API key>(event); } } }); getTable().setTableOverhead(viewRadioGroup); getTable().setTableTopMargin(20); } private void <API key>(ClickEvent event) { getDetailModel().setViewFilterType((viewRadioGroup.getSelectedValue())); boolean running = viewRadioGroup.getSelectedValue() == NetworkVmFilter.running; getTable().ensureColumnPresent(vmStatusColumn, constants.empty(), true, "30px"); //$NON-NLS-1$ getTable().ensureColumnPresent(nameColumn, constants.nameVm(), true, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(clusterColumn, constants.clusterVm(), true, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(ipColumn, constants.ipVm(), true, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(fqdnColumn, constants.fqdn(), true, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(<API key>, constants.vnicStatusNetworkVM(), true, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(vnicNameColumn, constants.vnicNetworkVM(), true, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(rxColumn, templates.sub(constants.rxNetworkVM(), constants.mbps()).asString(), running, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(txColumn, templates.sub(constants.txNetworkVM(), constants.mbps()).asString(), running, "150px"); //$NON-NLS-1$ getTable().ensureColumnPresent(descriptionColumn, constants.descriptionVm(), true, "150px"); //$NON-NLS-1$ } private final VmStatusColumn<PairQueryable<VmNetworkInterface, VM>> vmStatusColumn = new VmStatusColumn<PairQueryable<VmNetworkInterface, VM>>(); private final <API key><PairQueryable<VmNetworkInterface, VM>> nameColumn = new <API key><PairQueryable<VmNetworkInterface, VM>>() { @Override public String getValue(PairQueryable<VmNetworkInterface, VM> object) { return object.getSecond().getName(); } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> clusterColumn = new <API key><PairQueryable<VmNetworkInterface, VM>>() { @Override public String getValue(PairQueryable<VmNetworkInterface, VM> object) { return object.getSecond().getVdsGroupName(); } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> ipColumn = new <API key><PairQueryable<VmNetworkInterface, VM>>() { @Override public String getValue(PairQueryable<VmNetworkInterface, VM> object) { return object.getSecond().getVmIp(); } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> fqdnColumn = new <API key><PairQueryable<VmNetworkInterface, VM>>() { @Override public String getValue(PairQueryable<VmNetworkInterface, VM> object) { setTitle(object.getSecond().getVmFQDN()); return object.getSecond().getVmFQDN(); } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> <API key> = new <API key><PairQueryable<VmNetworkInterface, VM>>(); private final <API key><PairQueryable<VmNetworkInterface, VM>> vnicNameColumn = new <API key><PairQueryable<VmNetworkInterface, VM>>() { @Override public String getValue(PairQueryable<VmNetworkInterface, VM> object) { return object.getFirst().getName(); } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> rxColumn = new RxTxRateColumn<PairQueryable<VmNetworkInterface, VM>>() { @Override protected Double getRate(PairQueryable<VmNetworkInterface, VM> object) { return object.getFirst().getStatistics().getReceiveRate(); } @Override protected Double getSpeed(PairQueryable<VmNetworkInterface, VM> object) { if (object.getFirst().getSpeed() != null) { return object.getFirst().getSpeed().doubleValue(); } else { return null; } } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> txColumn = new RxTxRateColumn<PairQueryable<VmNetworkInterface, VM>>() { @Override protected Double getRate(PairQueryable<VmNetworkInterface, VM> object) { return object.getFirst().getStatistics().getTransmitRate(); } @Override protected Double getSpeed(PairQueryable<VmNetworkInterface, VM> object) { if (object.getFirst().getSpeed() != null) { return object.getFirst().getSpeed().doubleValue(); } else { return null; } } }; private final <API key><PairQueryable<VmNetworkInterface, VM>> descriptionColumn = new <API key><PairQueryable<VmNetworkInterface, VM>>() { @Override public String getValue(PairQueryable<VmNetworkInterface, VM> object) { return object.getSecond().getDescription(); } }; private void initTable() { getTable().<API key>(); initTableOverhead(); <API key>(null); initSorting(); getTable().addActionButton(new <API key><PairQueryable<VmNetworkInterface, VM>>(constants.removeInterface()) { @Override protected UICommand resolveCommand() { return getDetailModel().getRemoveCommand(); } }); } private void initSorting() { vmStatusColumn.makeSortable(); nameColumn.makeSortable(); clusterColumn.makeSortable(); ipColumn.makeSortable(); fqdnColumn.makeSortable(); <API key>.makeSortable(); vnicNameColumn.makeSortable(); rxColumn.makeSortable(); txColumn.makeSortable(); descriptionColumn.makeSortable(); } }
/* bfgs.f -- translated by f2c (version 19991025). */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "bfgs.h" void my_strcpy(char *s1, char *s2) { int i, len=strlen(s2); for (i=0; i<len; i++) s1[i]=s2[i]; } void Yanggradient (int n, const double x[], double f0, double g[],const void*dats, double (*fun)(const double x[],const void*), double space[], const double* lowbound, const double* upbound){ int i,j; double *x0=space, *x1=space+n, eh0, eh01, eh; eh0=eh01=1.e-8; for (i=0;i<n;i++) { for (j=0;j<n;j++) x0[j]=x1[j]=x[j]; eh=pow(eh01*(fabs(x[i])+1), 0.67); x0[i]-=eh; x1[i]+=eh; if (x0[i]<lowbound[i]) {x1[i]+=eh; g[i] = (fun(x1,dats)-f0)/(eh*2.0);} else if (x1[i]>upbound[i]) {x0[i]-=eh; g[i] = (f0-fun(x0,dats))/(eh*2.0);} else g[i] = (fun(x1,dats) - fun(x0,dats))/(eh*2.0); } } void getgradient(int npar, const double invec[], double outvec[],const void*dats, double(*func)(const double [],const void*), const double* lowbound, const double* upbound){ double f0; int i; double *space =(double *)calloc((2*npar+10),sizeof(double)); f0 = func(invec,dats); Yanggradient(npar, invec, f0, outvec,dats, func, space, lowbound, upbound); checkbounds: for (i=0; i<npar; i++) { if (invec[i] <= lowbound[i] && outvec[i] > 0.0) outvec[i] = 0.0; if (invec[i] >=upbound[i] && outvec[i] < 0.0) outvec[i] = 0.0; } free(space); } typedef int logical; //nbd is a vector of integers of dimension numpars. //nbd[i]=0 if there are no bounds for parameter i, // =1 if there are only lower bounds // =2 if there are both lower/upper bounds // =3 if there is only upper bound //or send nbd=NULL is equivalent to nbd=2 for all parameters //noisy=0 => no output, noisy=1 => one line of output, noisy < 99 some output, //noisy>=100 probably too much //dfun is derivative function or send NULL to use numerical derivative //(getgradient function above) double findmax_bfgs(int numpars, double *invec,const void*dats, double (*fun)(const double x[],const void*), void (*dfun)(const double x[], double y[]), double *lowbound, double *upbound, int *nbd, int noisy) { int i, m, isave[44], *iwa; double *grad, *wa, factr, pgtol, dsave[29], like; char task[60], csave[60]; int setulb_(int *n, int *m, double *x, double *l, double *u, int *nbd, double *f, double *g, double *factr, double *pgtol, double *wa, int *iwa, char *task, int *iprint, char *csave, int *lsave, int *isave, double *dsave); // int setulb_(); void my_strcpy(char *s1, char *s2); logical lsave[4]; m=MVAL; factr = FACTR; pgtol = PGTOL; //important to zero initialize arrays below grad =(double *) calloc(numpars,sizeof(double)); wa =(double *) calloc(((2*m+4)*numpars + 12*m*m + 12*m),sizeof(double)); iwa =(int *) calloc(3*numpars,sizeof(int)); my_strcpy(task, "START"); for (i=5; i<60; i++) task[i]=' '; like = (*fun)(invec,dats); if(dfun!=NULL) dfun(invec, grad); else getgradient(numpars,invec,grad,dats,fun,lowbound,upbound); while (1) { setulb_(&numpars, &m, invec, lowbound, upbound, nbd, &like,grad, &factr, &pgtol, wa, iwa, task, &noisy, csave, lsave,isave, dsave); if (task[0]=='F' && task[1]=='G') { printf("\t"); like = fun(invec,dats); if(dfun!=NULL) dfun(invec, grad); else getgradient(numpars,invec,grad,dats,fun,lowbound,upbound); if (noisy > 1) printf("like=%f\n", like); continue; } else if (strncmp(task, "NEW_X", 5)==0) { // if (noisy > 1) printf("\n"); continue; } else break; } if (noisy > 1) printf("\n"); free(wa); free(iwa); free(grad); return -like; } typedef double doublereal; typedef int integer; typedef int ftnlen; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (doublereal)abs(x) #define min(a,b) ((a) <= (b) ? (a) : (b)) #define max(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (doublereal)min(a,b) #define dmax(a,b) (doublereal)max(a,b) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) /* Table of constant values */ doublereal c_b9 = 0.; integer c__1 = 1; // integer c__9 = 9; integer c__11 = 11; // integer c__3 = 3; doublereal c_b275 = .001; doublereal c_b276 = .9; doublereal c_b277 = .1; // integer c__5 = 5; #define FALSE_ (0) #define TRUE_ (1) /* Subroutine */ int setulb_(int *n, int *m, double *x, double *l, double *u, int *nbd, double *f, double *g, double *factr, double *pgtol, double *wa, int *iwa, char *task, int *iprint, char *csave, int *lsave, int *isave, double *dsave) { /* System generated locals */ integer i__1; /* Builtin functions */ // integer s_cmp(); /* Local variables */ integer lsnd, lsgo, lygo, l1, l2, l3, ld, lr, lt; //extern /* Subroutine */ //int mainlb_(); int mainlb_(integer *n, integer *m, doublereal *x, doublereal *l, doublereal *u, integer *nbd, doublereal *f, doublereal *g, doublereal *factr, doublereal *pgtol, doublereal *ws, doublereal *wy, doublereal *sy, doublereal *ss, doublereal *yy, doublereal *wt, doublereal *wn, doublereal *snd, doublereal *z__, doublereal *r__, doublereal *d__, doublereal *t, doublereal *wa, doublereal *sg, doublereal *sgo, doublereal *yg, doublereal *ygo, integer *index, integer *iwhere, integer *indx2, char *task, integer *iprint, char *csave, logical *lsave, integer *isave, doublereal *dsave, ftnlen task_len, ftnlen csave_len); integer lz, lwa, lsg, lyg, lwn, lss, lws, lwt, lsy, lwy, lyy; /* Subroutine setulb */ /* This subroutine partitions the working arrays wa and iwa, and */ /* then uses the limited memory BFGS method to solve the bound */ /* constrained optimization problem by calling mainlb. */ /* (The direct method will be used in the subspace minimization.) */ /* n is an integer variable. */ /* On entry n is the dimension of the problem. */ /* On exit n is unchanged. */ /* m is an integer variable. */ /* On entry m is the maximum number of variable metric corrections */ /* used to define the limited memory matrix. */ /* On exit m is unchanged. */ /* x is a double precision array of dimension n. */ /* On entry x is an approximation to the solution. */ /* On exit x is the current approximation. */ /* l is a double precision array of dimension n. */ /* On entry l is the lower bound on x. */ /* On exit l is unchanged. */ /* u is a double precision array of dimension n. */ /* On entry u is the upper bound on x. */ /* On exit u is unchanged. */ /* nbd is an integer array of dimension n. */ /* On entry nbd represents the type of bounds imposed on the */ /* variables, and must be specified as follows: */ /* nbd(i)=0 if x(i) is unbounded, */ /* 1 if x(i) has only a lower bound, */ /* 2 if x(i) has both lower and upper bounds, and */ /* 3 if x(i) has only an upper bound. */ /* On exit nbd is unchanged. */ /* f is a double precision variable. */ /* On first entry f is unspecified. */ /* On final exit f is the value of the function at x. */ /* g is a double precision array of dimension n. */ /* On first entry g is unspecified. */ /* On final exit g is the value of the gradient at x. */ /* factr is a double precision variable. */ /* On entry factr >= 0 is specified by the user. The iteration */ /* will stop when */ /* (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch */ /* where epsmch is the machine precision, which is automatically */ /* generated by the code. Typical values for factr: 1.d+12 for */ /* low accuracy; 1.d+7 for moderate accuracy; 1.d+1 for extremely */ /* high accuracy. */ /* On exit factr is unchanged. */ /* pgtol is a double precision variable. */ /* On entry pgtol >= 0 is specified by the user. The iteration */ /* will stop when */ /* max{|proj g_i | i = 1, ..., n} <= pgtol */ /* where pg_i is the ith component of the projected gradient. */ /* On exit pgtol is unchanged. */ /* wa is a double precision working array of length */ /* (2mmax + 4)nmax + 12mmax^2 + 12mmax. */ /* iwa is an integer working array of length 3nmax. */ /* task is a working string of characters of length 60 indicating */ /* the current job when entering and quitting this subroutine. */ /* iprint is an integer variable that must be set by the user. */ /* It controls the frequency and type of output generated: */ /* iprint<0 no output is generated; */ /* iprint=0 print only one line at the last iteration; */ /* 0<iprint<99 print also f and |proj g| every iprint iterations; */ /* iprint=99 print details of every iteration except n-vectors; */ /* iprint=100 print also the changes of active set and final x; */ /* iprint>100 print details of every iteration including x and g; */ /* When iprint > 0, the file iterate.dat will be created to */ /* summarize the iteration. */ /* csave is a working string of characters of length 60. */ /* lsave is a logical working array of dimension 4. */ /* On exit with 'task' = NEW_X, the following information is */ /* available: */ /* If lsave(1) = .true. then the initial X has been replaced by */ /* its projection in the feasible set; */ /* If lsave(2) = .true. then the problem is constrained; */ /* If lsave(3) = .true. then each variable has upper and lower */ /* bounds; */ /* isave is an integer working array of dimension 44. */ /* On exit with 'task' = NEW_X, the following information is */ /* available: */ /* isave(22) = the total number of intervals explored in the */ /* search of Cauchy points; */ /* isave(26) = the total number of skipped BFGS updates before */ /* the current iteration; */ /* isave(30) = the number of current iteration; */ /* isave(31) = the total number of BFGS updates prior the current */ /* iteration; */ /* isave(33) = the number of intervals explored in the search of */ /* Cauchy point in the current iteration; */ /* isave(34) = the total number of function and gradient */ /* evaluations; */ /* isave(36) = the number of function value or gradient */ /* evaluations in the current iteration; */ /* if isave(37) = 0 then the subspace argmin is within the box; */ /* if isave(37) = 1 then the subspace argmin is beyond the box; */ /* isave(38) = the number of free variables in the current */ /* iteration; */ /* isave(39) = the number of active constraints in the current */ /* iteration; */ /* n + 1 - isave(40) = the number of variables leaving the set of */ /* active constraints in the current iteration; */ /* isave(41) = the number of variables entering the set of active */ /* constraints in the current iteration. */ /* dsave is a double precision working array of dimension 29. */ /* On exit with 'task' = NEW_X, the following information is */ /* available: */ /* dsave(1) = current 'theta' in the BFGS matrix; */ /* dsave(2) = f(x) in the previous iteration; */ /* dsave(3) = factr*epsmch; */ /* dsave(4) = 2-norm of the line search direction vector; */ /* dsave(5) = the machine precision epsmch generated by the code; */ /* dsave(7) = the accumulated time spent on searching for */ /* Cauchy points; */ /* dsave(8) = the accumulated time spent on */ /* subspace minimization; */ /* dsave(9) = the accumulated time spent on line search; */ /* dsave(11) = the slope of the line search function at */ /* the current point of line search; */ /* dsave(12) = the maximum relative step length imposed in */ /* line search; */ /* dsave(13) = the infinity norm of the projected gradient; */ /* dsave(14) = the relative step length in the line search; */ /* dsave(15) = the slope of the line search function at */ /* the starting point of the line search; */ /* dsave(16) = the square of the 2-norm of the line search */ /* direction vector. */ /* Subprograms called: */ /* L-BFGS-B Library ... mainlb. */ /* References: */ /* [1] R. H. Byrd, P. Lu, J. Nocedal and C. Zhu, ``A limited */ /* memory algorithm for bound constrained optimization'', */ /* SIAM J. Scientific Computing 16 (1995), no. 5, pp. 1190--1208. */ /* [2] C. Zhu, R.H. Byrd, P. Lu, J. Nocedal, ``L-BFGS-B: a */ /* limited memory FORTRAN code for solving bound constrained */ /* optimization problems'', Tech. Report, NAM-11, EECS Department, */ /* Northwestern University, 1994. */ /* (Postscript files of these papers are available via anonymous */ /* ftp to eecs.nwu.edu in the directory pub/lbfgs/lbfgs_bcm.) */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --iwa; --g; --nbd; --u; --l; --x; --wa; --lsave; --isave; --dsave; /* Function Body */ if (strncmp(task, "START", 5) == 0) { isave[1] = *m * *n; /* Computing 2nd power */ i__1 = *m; isave[2] = i__1 * i__1; /* Computing 2nd power */ i__1 = *m; isave[3] = i__1 * i__1 << 2; isave[4] = 1; isave[5] = isave[4] + isave[1]; isave[6] = isave[5] + isave[1]; isave[7] = isave[6] + isave[2]; isave[8] = isave[7] + isave[2]; isave[9] = isave[8] + isave[2]; isave[10] = isave[9] + isave[2]; isave[11] = isave[10] + isave[3]; isave[12] = isave[11] + isave[3]; isave[13] = isave[12] + *n; isave[14] = isave[13] + *n; isave[15] = isave[14] + *n; isave[16] = isave[15] + *n; isave[17] = isave[16] + (*m << 3); isave[18] = isave[17] + *m; isave[19] = isave[18] + *m; isave[20] = isave[19] + *m; } l1 = isave[1]; l2 = isave[2]; l3 = isave[3]; lws = isave[4]; lwy = isave[5]; lsy = isave[6]; lss = isave[7]; lyy = isave[8]; lwt = isave[9]; lwn = isave[10]; lsnd = isave[11]; lz = isave[12]; lr = isave[13]; ld = isave[14]; lt = isave[15]; lwa = isave[16]; lsg = isave[17]; lsgo = isave[18]; lyg = isave[19]; lygo = isave[20]; mainlb_(n, m, &x[1], &l[1], &u[1], &nbd[1], f, &g[1], factr, pgtol, &wa[ lws], &wa[lwy], &wa[lsy], &wa[lss], &wa[lyy], &wa[lwt], &wa[lwn], &wa[lsnd], &wa[lz], &wa[lr], &wa[ld], &wa[lt], &wa[lwa], &wa[lsg], &wa[lsgo], &wa[lyg], &wa[lygo], &iwa[1], &iwa[*n + 1], &iwa[(*n << 1) + 1], task, iprint, csave, &lsave[1], &isave[22], &dsave[1], (ftnlen)60, (ftnlen)60); return 0; } /* setulb_ */ /* Subroutine */ int mainlb_(int *n,int *m,double *x,double *l,double *u,int * nbd,double * f,double * g,double * factr,double * pgtol,double * ws,double * wy, double *sy,double * ss,double * yy,double * wt,double * wn,double * snd,double * z__,double * r__,double * d__,double * t,double * wa,double * sg,double * sgo,double * yg,double * ygo, int * index, int * iwhere, int * indx2,char * task,int * iprint,char * csave,logical *lsave,int *isave, double *dsave, ftnlen task_len,ftnlen csave_len) /* integer *n, *m; doublereal *x, *l, *u; integer *nbd; doublereal *f, *g, *factr, *pgtol, *ws, *wy, *sy, *ss, *yy, *wt, *wn, *snd, * z__, *r__, *d__, *t, *wa, *sg, *sgo, *yg, *ygo; integer *index, *iwhere, *indx2; char *task; integer *iprint; char *csave; logical *lsave; integer *isave; doublereal *dsave; ftnlen task_len; ftnlen csave_len;*/ { /* Format strings */ /* char fmt_1002[] = "(/,\002At iterate\002,i5,4x,\002f= \002,1p,d12\ .5,4x,\002|proj g|= \002,1p,d12.5)"; char fmt_1003[] = "(2(1x,i4),5x,\002-\002,5x,\002-\002,3x,\002\ -\002,5x,\002-\002,5x,\002-\002,8x,\002-\002,3x,1p,2(1x,d10.3))"; char fmt_1001[] = "(//,\002ITERATION \002,i5)"; char fmt_1005[] = "(/,\002 Singular triangular system detected\ ;\002,/,\002 refresh the lbfgs memory and restart the iteration.\002)"; char fmt_1006[] = "(/,\002 Nonpositive definiteness in Cholesky f\ actorization in formk;\002,/,\002 refresh the lbfgs memory and restart the\ iteration.\002)"; char fmt_1008[] = "(/,\002 Bad direction in the line search;\002,\ /,\002 refresh the lbfgs memory and restart the iteration.\002)"; char fmt_1004[] = "(\002 ys=\002,1p,e10.3,\002 -gs=\002,1p,e10.\ 3,\002 BFGS update SKIPPED\002)"; char fmt_1007[] = "(/,\002 Nonpositive definiteness in Cholesky f\ actorization in formt;\002,/,\002 refresh the lbfgs memory and restart the\ iteration.\002)";*/ /* System generated locals */ integer ws_dim1, ws_offset, wy_dim1, wy_offset, sy_dim1, sy_offset, ss_dim1, ss_offset, yy_dim1, yy_offset, wt_dim1, wt_offset, wn_dim1, wn_offset, snd_dim1, snd_offset, i__1; doublereal d__1, d__2; int timer_(double *); /* Builtin functions */ // integer s_cmp(); // /* Subroutine */ int s_copy(); // integer s_wsfe(), do_fio(), e_wsfe(); /* Local variables */ integer head; doublereal fold; integer nact; doublereal ddum; // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer info; doublereal time; integer nfgv, ifun, iter, nint; char word[3]; doublereal time1, time2; integer i__, iback, k; // extern /* Subroutine */ int dscal_(); int dscal_(integer *n, doublereal *da, doublereal *dx, integer *incx); doublereal gdold; integer nfree; logical boxed; integer itail; doublereal theta; // extern /* Subroutine */ int freev_(), dcopy_(); int freev_(integer *n, integer *nfree, integer *index, integer *nenter, integer *ileave, integer *indx2, integer *iwhere, logical *wrk, logical *updatd, logical *cnstnd, integer *iprint, integer *iter); int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); doublereal dnorm; // extern /* Subroutine */ int formk_(); int formk_(integer *n, integer *nsub, integer *ind, integer *nenter, integer *ileave, integer *indx2, integer *iupdat, logical *updatd, doublereal *wn, doublereal *wn1, integer *m, doublereal *ws, doublereal *wy, doublereal *sy, doublereal *theta, integer *col, integer *head, integer *info); integer nskip, iword; // extern /* Subroutine */ int formt_(), subsm_(); int formt_(integer *m, doublereal *wt, doublereal *sy, doublereal *ss, integer *col, doublereal *theta, integer *info); int subsm_(integer *n, integer *m, integer *nsub, integer *ind, doublereal *l, doublereal *u, integer *nbd, doublereal *x, doublereal *d__, doublereal *ws, doublereal *wy, doublereal *theta, integer *col, integer *head, integer *iword, doublereal *wv, doublereal *wn, integer *iprint, integer *info); doublereal xstep, stpmx; // extern /* Subroutine */// int prn1lb_(), prn2lb_();// prn3lb_(); int prn1lb_(integer *n, integer *m, doublereal *l, doublereal *u, doublereal *x, integer *iprint, integer *itfile, doublereal *epsmch); int prn2lb_(integer *n, doublereal *x, doublereal *f, doublereal *g, integer *iprint, integer *itfile, integer *iter, integer *nfgv, integer *nact, doublereal *sbgnrm, integer *nint, char *word, integer *iword, integer *iback, doublereal *stp, doublereal *xstep, ftnlen word_len); int prn3lb_(integer *n, doublereal *x, doublereal *f, char *task, integer *iprint, integer *info, integer *itfile, integer *iter, integer *nfgv, integer *nintol, integer *nskip, integer *nact, doublereal *sbgnrm, doublereal *time, integer *nint, char *word, integer *iback, doublereal *stp, doublereal *xstep, integer *k, doublereal *cachyt, doublereal *sbtime, doublereal *lnscht, ftnlen task_len, ftnlen word_len); doublereal gd, dr, rr; integer ileave; extern /* Subroutine */// int errclb_(); int errclb_(integer *n, integer *m, doublereal *factr, doublereal *l, doublereal *u, integer *nbd, char *task, integer *info, integer *k, ftnlen task_len); integer itfile; doublereal cachyt, epsmch; logical updatd; doublereal sbtime; // extern /* Subroutine */ int active_(); int active_(integer *n, doublereal *l, doublereal *u, integer *nbd, doublereal *x, integer *iwhere, integer *iprint, logical *prjctd, logical *cnstnd, logical *boxed); logical prjctd; integer iupdat; extern doublereal dpmeps_(); logical cnstnd; doublereal sbgnrm; integer nenter; doublereal lnscht; // extern /* Subroutine */ int cauchy_(), cmprlb_(), lnsrlb_(), matupd_(); int matupd_(integer *n, integer *m, doublereal *ws, doublereal *wy, doublereal *sy, doublereal *ss, doublereal *d__, doublereal *r__, integer *itail, integer *iupdat, integer *col, integer *head, doublereal *theta, doublereal *rr, doublereal *dr, doublereal *stp, doublereal *dtd); int lnsrlb_(integer *n, doublereal *l, doublereal *u, integer *nbd, doublereal *x, doublereal *f, doublereal *fold, doublereal *gd, doublereal *gdold, doublereal *g, doublereal *d__, doublereal *r__, doublereal *t, doublereal *z__, doublereal *stp, doublereal *dnorm, doublereal *dtd, doublereal *xstep, doublereal *stpmx, integer *iter, integer *ifun, integer *iback, integer *nfgv, integer *info, char *task, logical *boxed, logical *cnstnd, char *csave, integer *isave, doublereal *dsave, ftnlen task_len, ftnlen csave_len); int cmprlb_(integer *n, integer *m, doublereal *x, doublereal *g, doublereal *ws, doublereal *wy, doublereal *sy, doublereal *wt, doublereal *z__, doublereal *r__, doublereal *wa, integer *index, doublereal *theta, integer *col, integer *head, integer *nfree, logical *cnstnd, integer *info); int cauchy_(integer *n, doublereal *x, doublereal *l, doublereal *u, integer *nbd, doublereal *g, integer *iorder, integer *iwhere, doublereal *t, doublereal *d__, doublereal *xcp, integer *m, doublereal *wy, doublereal *ws, doublereal *sy, doublereal *wt, doublereal *theta, integer *col, integer *head, doublereal *p, doublereal *c__, doublereal *wbp, doublereal *v, integer *nint, doublereal *sg, doublereal *yg, integer *iprint, doublereal *sbgnrm, integer *info); integer nintol; // extern /* Subroutine */ int projgr_(); int projgr_(integer *n, doublereal *l, doublereal *u, integer *nbd, doublereal *x, doublereal *g, doublereal *sbgnrm); doublereal dtd; integer col; doublereal tol; logical wrk; doublereal stp, cpu1, cpu2; /* Fortran I/O blocks */ /* Subroutine mainlb */ /* This subroutine solves bound constrained optimization problems by */ /* using the compact formula of the limited memory BFGS updates. */ /* n is an integer variable. */ /* On entry n is the number of variables. */ /* On exit n is unchanged. */ /* m is an integer variable. */ /* On entry m is the maximum number of variable metric */ /* corrections allowed in the limited memory matrix. */ /* On exit m is unchanged. */ /* x is a double precision array of dimension n. */ /* On entry x is an approximation to the solution. */ /* On exit x is the current approximation. */ /* l is a double precision array of dimension n. */ /* On entry l is the lower bound of x. */ /* On exit l is unchanged. */ /* u is a double precision array of dimension n. */ /* On entry u is the upper bound of x. */ /* On exit u is unchanged. */ /* nbd is an integer array of dimension n. */ /* On entry nbd represents the type of bounds imposed on the */ /* variables, and must be specified as follows: */ /* nbd(i)=0 if x(i) is unbounded, */ /* 1 if x(i) has only a lower bound, */ /* 2 if x(i) has both lower and upper bounds, */ /* 3 if x(i) has only an upper bound. */ /* On exit nbd is unchanged. */ /* f is a double precision variable. */ /* On first entry f is unspecified. */ /* On final exit f is the value of the function at x. */ /* g is a double precision array of dimension n. */ /* On first entry g is unspecified. */ /* On final exit g is the value of the gradient at x. */ /* factr is a double precision variable. */ /* On entry factr >= 0 is specified by the user. The iteration */ /* will stop when */ /* (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch */ /* where epsmch is the machine precision, which is automatically */ /* generated by the code. */ /* On exit factr is unchanged. */ /* pgtol is a double precision variable. */ /* On entry pgtol >= 0 is specified by the user. The iteration */ /* will stop when */ /* max{|proj g_i | i = 1, ..., n} <= pgtol */ /* where pg_i is the ith component of the projected gradient. */ /* On exit pgtol is unchanged. */ /* ws, wy, sy, and wt are double precision working arrays used to */ /* store the following information defining the limited memory */ /* BFGS matrix: */ /* ws, of dimension n x m, stores S, the matrix of s-vectors; */ /* wy, of dimension n x m, stores Y, the matrix of y-vectors; */ /* sy, of dimension m x m, stores S'Y; */ /* ss, of dimension m x m, stores S'S; */ /* yy, of dimension m x m, stores Y'Y; */ /* wt, of dimension m x m, stores the Cholesky factorization */ /* of (theta*S'S+LD^(-1)L'); see eq. */ /* (2.26) in [3]. */ /* wn is a double precision working array of dimension 2m x 2m */ /* used to store the LEL^T factorization of the indefinite matrix */ /* K = [-D -Y'ZZ'Y/theta L_a'-R_z' ] */ /* [L_a -R_z theta*S'AA'S ] */ /* where E = [-I 0] */ /* [ 0 I] */ /* snd is a double precision working array of dimension 2m x 2m */ /* used to store the lower triangular part of */ /* N = [Y' ZZ'Y L_a'+R_z'] */ /* [L_a +R_z S'AA'S ] */ /* z(n),r(n),d(n),t(n),wa(8*m) are double precision working arrays. */ /* z is used at different times to store the Cauchy point and */ /* the Newton point. */ /* sg(m),sgo(m),yg(m),ygo(m) are double precision working arrays. */ /* index is an integer working array of dimension n. */ /* In subroutine freev, index is used to store the free and fixed */ /* variables at the Generalized Cauchy Point (GCP). */ /* iwhere is an integer working array of dimension n used to record */ /* the status of the vector x for GCP computation. */ /* iwhere(i)=0 or -3 if x(i) is free and has bounds, */ /* 1 if x(i) is fixed at l(i), and l(i) .ne. u(i) */ /* 2 if x(i) is fixed at u(i), and u(i) .ne. l(i) */ /* 3 if x(i) is always fixed, i.e., u(i)=x(i)=l(i) */ /* -1 if x(i) is always free, i.e., no bounds on it. */ /* indx2 is an integer working array of dimension n. */ /* Within subroutine cauchy, indx2 corresponds to the array iorder. */ /* In subroutine freev, a list of variables entering and leaving */ /* the free set is stored in indx2, and it is passed on to */ /* subroutine formk with this information. */ /* task is a working string of characters of length 60 indicating */ /* the current job when entering and leaving this subroutine. */ /* iprint is an INTEGER variable that must be set by the user. */ /* It controls the frequency and type of output generated: */ /* iprint<0 no output is generated; */ /* iprint=0 print only one line at the last iteration; */ /* 0<iprint<99 print also f and |proj g| every iprint iterations; */ /* iprint=99 print details of every iteration except n-vectors; */ /* iprint=100 print also the changes of active set and final x; */ /* iprint>100 print details of every iteration including x and g; */ /* When iprint > 0, the file iterate.dat will be created to */ /* summarize the iteration. */ /* csave is a working string of characters of length 60. */ /* lsave is a logical working array of dimension 4. */ /* isave is an integer working array of dimension 23. */ /* dsave is a double precision working array of dimension 29. */ /* Subprograms called */ /* L-BFGS-B Library ... cauchy, subsm, lnsrlb, formk, */ /* errclb, prn1lb, prn2lb, prn3lb, active, projgr, */ /* freev, cmprlb, matupd, formt. */ /* Minpack2 Library ... timer, dpmeps. */ /* Linpack Library ... dcopy, ddot. */ /* References: */ /* [1] R. H. Byrd, P. Lu, J. Nocedal and C. Zhu, ``A limited */ /* memory algorithm for bound constrained optimization'', */ /* SIAM J. Scientific Computing 16 (1995), no. 5, pp. 1190--1208. */ /* [2] C. Zhu, R.H. Byrd, P. Lu, J. Nocedal, ``L-BFGS-B: FORTRAN */ /* Subroutines for Large Scale Bound Constrained Optimization'' */ /* Tech. Report, NAM-11, EECS Department, Northwestern University, */ /* 1994. */ /* [3] R. Byrd, J. Nocedal and R. Schnabel "Representations of */ /* Quasi-Newton Matrices and their use in Limited Memory Methods'', */ /* Mathematical Programming 63 (1994), no. 4, pp. 129-156. */ /* (Postscript files of these papers are available via anonymous */ /* ftp to eecs.nwu.edu in the directory pub/lbfgs/lbfgs_bcm.) */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --indx2; --iwhere; --index; --t; --d__; --r__; --z__; --g; --nbd; --u; --l; --x; --ygo; --yg; --sgo; --sg; --wa; snd_dim1 = 2 * *m; snd_offset = 1 + snd_dim1 * 1; snd -= snd_offset; wn_dim1 = 2 * *m; wn_offset = 1 + wn_dim1 * 1; wn -= wn_offset; wt_dim1 = *m; wt_offset = 1 + wt_dim1 * 1; wt -= wt_offset; yy_dim1 = *m; yy_offset = 1 + yy_dim1 * 1; yy -= yy_offset; ss_dim1 = *m; ss_offset = 1 + ss_dim1 * 1; ss -= ss_offset; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; wy_dim1 = *n; wy_offset = 1 + wy_dim1 * 1; wy -= wy_offset; ws_dim1 = *n; ws_offset = 1 + ws_dim1 * 1; ws -= ws_offset; --lsave; --isave; --dsave; /* Function Body */ if (strncmp(task, "START", 5) == 0) { timer_(&time1); /* Generate the current machine precision. */ epsmch = dpmeps_(); /* Initialize counters and scalars when task='START'. */ /* for the limited memory BFGS matrices: */ col = 0; head = 1; theta = 1.; iupdat = 0; updatd = FALSE_; /* for operation counts: */ iter = 0; nfgv = 0; nint = 0; nintol = 0; nskip = 0; nfree = *n; /* for stopping tolerance: */ tol = *factr * epsmch; /* for measuring running time: */ cachyt = 0.; sbtime = 0.; lnscht = 0.; /* 'word' records the status of subspace solutions. */ my_strcpy(word, " /* 'info' records the termination information. */ info = 0; /* Check the input arguments for errors. */ errclb_(n, m, factr, &l[1], &u[1], &nbd[1], task, &info, &k, (ftnlen) 60); if (strncmp(task, "ERROR", 5)==0) { prn3lb_(n, &x[1], f, task, iprint, &info, &itfile, &iter, &nfgv, & nintol, &nskip, &nact, &sbgnrm, &c_b9, &nint, word, & iback, &stp, &xstep, &k, &cachyt, &sbtime, &lnscht, ( ftnlen)60, (ftnlen)3); return 0; } prn1lb_(n, m, &l[1], &u[1], &x[1], iprint, &itfile, &epsmch); /* Initialize iwhere & project x onto the feasible set. */ active_(n, &l[1], &u[1], &nbd[1], &x[1], &iwhere[1], iprint, &prjctd, &cnstnd, &boxed); /* The end of the initialization. */ } else { /* restore local variables. */ prjctd = lsave[1]; cnstnd = lsave[2]; boxed = lsave[3]; updatd = lsave[4]; nintol = isave[1]; itfile = isave[3]; iback = isave[4]; nskip = isave[5]; head = isave[6]; col = isave[7]; itail = isave[8]; iter = isave[9]; iupdat = isave[10]; nint = isave[12]; nfgv = isave[13]; info = isave[14]; ifun = isave[15]; iword = isave[16]; nfree = isave[17]; nact = isave[18]; ileave = isave[19]; nenter = isave[20]; theta = dsave[1]; fold = dsave[2]; tol = dsave[3]; dnorm = dsave[4]; epsmch = dsave[5]; cpu1 = dsave[6]; cachyt = dsave[7]; sbtime = dsave[8]; lnscht = dsave[9]; time1 = dsave[10]; gd = dsave[11]; stpmx = dsave[12]; sbgnrm = dsave[13]; stp = dsave[14]; gdold = dsave[15]; dtd = dsave[16]; /* After returning from the driver go to the point where execution */ /* is to resume. */ if (strncmp(task, "FG_LN", 5)==0) { goto L666; } if (strncmp(task, "NEW_X", 5)==0) { goto L777; } if (strncmp(task, "FG_ST", 5)==0) { goto L111; } if (strncmp(task, "STOP", 4)==0) { if (strstr(task, "CPU")!=NULL) { /* restore the previous iterate. */ dcopy_(n, &t[1], &c__1, &x[1], &c__1); dcopy_(n, &r__[1], &c__1, &g[1], &c__1); *f = fold; } goto L999; } } /* Compute f0 and g0. */ my_strcpy(task, "FG_START"); /* return to the driver to calculate f and g; reenter at 111. */ goto L1000; L111: nfgv = 1; /* Compute the infinity norm of the (-) projected gradient. */ projgr_(n, &l[1], &u[1], &nbd[1], &x[1], &g[1], &sbgnrm); if (*iprint >= 1) { printf("At iterate %4i f=%f\t|proj g| = %e\n", iter, *f, sbgnrm); } if (sbgnrm <= *pgtol) { /* terminate the algorithm. */ my_strcpy(task, "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL"); // s_copy(task, "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL", ( // ftnlen)60, (ftnlen)48); goto L999; } L222: if (*iprint >= 99) { i__1 = iter + 1; printf("ITERATION %i\n", i__1); } iword = -1; if (! cnstnd && col > 0) { /* skip the search for GCP. */ dcopy_(n, &x[1], &c__1, &z__[1], &c__1); wrk = updatd; nint = 0; goto L333; } /* <API key> */ /* Compute the Generalized Cauchy Point (GCP). */ /* <API key> */ timer_(&cpu1); cauchy_(n, &x[1], &l[1], &u[1], &nbd[1], &g[1], &indx2[1], &iwhere[1], &t[ 1], &d__[1], &z__[1], m, &wy[wy_offset], &ws[ws_offset], &sy[ sy_offset], &wt[wt_offset], &theta, &col, &head, &wa[1], &wa[(*m << 1) + 1], &wa[(*m << 2) + 1], &wa[*m * 6 + 1], &nint, &sg[1], & yg[1], iprint, &sbgnrm, &info); if (info != 0) { /* singular triangular system detected; refresh the lbfgs memory. */ if (*iprint >= 1) { printf("Singular triangular system detected; refresh the lbfgs memory and restart the iteration.\n"); // e_wsfe(); } info = 0; col = 0; head = 1; theta = 1.; iupdat = 0; updatd = FALSE_; timer_(&cpu2); cachyt = cachyt + cpu2 - cpu1; goto L222; } timer_(&cpu2); cachyt = cachyt + cpu2 - cpu1; nintol += nint; /* Count the entering and leaving variables for iter > 0; */ /* find the index set of free and active variables at the GCP. */ freev_(n, &nfree, &index[1], &nenter, &ileave, &indx2[1], &iwhere[1], & wrk, &updatd, &cnstnd, iprint, &iter); nact = *n - nfree; L333: /* If there are no free variables or B=I, then */ /* skip the subspace minimization. */ if (nfree == 0 || col == 0) { goto L555; } /* <API key> */ /* Subspace minimization. */ /* <API key> */ timer_(&cpu1); /* Form the LEL^T factorization of the indefinite */ /* matrix K = [-D -Y'ZZ'Y/theta L_a'-R_z' ] */ /* [L_a -R_z theta*S'AA'S ] */ /* where E = [-I 0] */ /* [ 0 I] */ if (wrk) { formk_(n, &nfree, &index[1], &nenter, &ileave, &indx2[1], &iupdat, & updatd, &wn[wn_offset], &snd[snd_offset], m, &ws[ws_offset], & wy[wy_offset], &sy[sy_offset], &theta, &col, &head, &info); } if (info != 0) { /* nonpositive definiteness in Cholesky factorization; */ /* refresh the lbfgs memory and restart the iteration. */ if (*iprint >= 1) { printf("Nonpositive defiteness in Cholesky factorization; refresh the lbfgs memory ane restart the iteration\n"); // e_wsfe(); } info = 0; col = 0; head = 1; theta = 1.; iupdat = 0; updatd = FALSE_; timer_(&cpu2); sbtime = sbtime + cpu2 - cpu1; goto L222; } /* compute r=-Z'B(xcp-xk)-Z'g (using wa(2m+1)=W'(xcp-x) */ /* from 'cauchy'). */ cmprlb_(n, m, &x[1], &g[1], &ws[ws_offset], &wy[wy_offset], &sy[sy_offset] , &wt[wt_offset], &z__[1], &r__[1], &wa[1], &index[1], &theta, & col, &head, &nfree, &cnstnd, &info); if (info != 0) { goto L444; } /* call the direct method. */ subsm_(n, m, &nfree, &index[1], &l[1], &u[1], &nbd[1], &z__[1], &r__[1], & ws[ws_offset], &wy[wy_offset], &theta, &col, &head, &iword, &wa[1] , &wn[wn_offset], iprint, &info); L444: if (info != 0) { /* singular triangular system detected; */ /* refresh the lbfgs memory and restart the iteration. */ if (*iprint >= 1) { printf("Singular triangular system detected; refresh the lbfgs memory and restart the iteration\n"); // e_wsfe(); } info = 0; col = 0; head = 1; theta = 1.; iupdat = 0; updatd = FALSE_; timer_(&cpu2); sbtime = sbtime + cpu2 - cpu1; goto L222; } timer_(&cpu2); sbtime = sbtime + cpu2 - cpu1; L555: /* <API key> */ /* Line search and optimality tests. */ /* <API key> */ /* Generate the search direction d:=z-x. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = z__[i__] - x[i__]; /* L40: */ } timer_(&cpu1); L666: lnsrlb_(n, &l[1], &u[1], &nbd[1], &x[1], f, &fold, &gd, &gdold, &g[1], & d__[1], &r__[1], &t[1], &z__[1], &stp, &dnorm, &dtd, &xstep, & stpmx, &iter, &ifun, &iback, &nfgv, &info, task, &boxed, &cnstnd, csave, &isave[22], &dsave[17], (ftnlen)60, (ftnlen)60); if (info != 0 || iback >= 20) { /* restore the previous iterate. */ dcopy_(n, &t[1], &c__1, &x[1], &c__1); dcopy_(n, &r__[1], &c__1, &g[1], &c__1); *f = fold; if (col == 0) { /* abnormal termination. */ if (info == 0) { info = -9; /* restore the actual number of f and g evaluations etc. */ --nfgv; --ifun; --iback; } my_strcpy(task, "<API key>"); // s_copy(task, "<API key>", (ftnlen)60, ( // ftnlen)30); ++iter; goto L999; } else { /* refresh the lbfgs memory and restart the iteration. */ if (*iprint >= 1) { printf("refresh the lbfgs memory and restart the iteration\n"); // e_wsfe(); } if (info == 0) { --nfgv; } info = 0; col = 0; head = 1; theta = 1.; iupdat = 0; updatd = FALSE_; my_strcpy(task, "RESTART_FROM_LNSRCH"); // s_copy(task, "RESTART_FROM_LNSRCH", (ftnlen)60, (ftnlen)19); timer_(&cpu2); lnscht = lnscht + cpu2 - cpu1; goto L222; } } else if (strncmp(task, "FG_LN", 5)==0) { /* return to the driver for calculating f and g; reenter at 666. */ goto L1000; } else { /* calculate and print out the quantities related to the new X. */ timer_(&cpu2); lnscht = lnscht + cpu2 - cpu1; ++iter; /* Compute the infinity norm of the projected (-)gradient. */ projgr_(n, &l[1], &u[1], &nbd[1], &x[1], &g[1], &sbgnrm); /* Print iteration information. */ prn2lb_(n, &x[1], f, &g[1], iprint, &itfile, &iter, &nfgv, &nact, & sbgnrm, &nint, word, &iword, &iback, &stp, &xstep, (ftnlen)3); goto L1000; } L777: /* Test for termination. */ if (sbgnrm <= *pgtol) { /* terminate the algorithm. */ my_strcpy(task, "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL"); goto L999; } /* Computing MAX */ d__1 = abs(fold), d__2 = abs(*f), d__1 = max(d__1,d__2); ddum = max(d__1,1.); if (fold - *f <= tol * ddum) { /* terminate the algorithm. */ my_strcpy(task, "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"); if (iback >= 10) { info = -5; } /* i.e., to issue a warning if iback>10 in the line search. */ goto L999; } /* Compute d=newx-oldx, r=newg-oldg, rr=y'y and dr=y's. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { r__[i__] = g[i__] - r__[i__]; /* L42: */ } rr = ddot_(n, &r__[1], &c__1, &r__[1], &c__1); if (stp == 1.) { dr = gd - gdold; ddum = -gdold; } else { dr = (gd - gdold) * stp; dscal_(n, &stp, &d__[1], &c__1); ddum = -gdold * stp; } if (dr <= epsmch * ddum) { /* skip the L-BFGS update. */ ++nskip; updatd = FALSE_; if (*iprint >= 1) { printf("ys=%f, gs=%f, BFGS update SKIPPED\n", dr, ddum); } goto L888; } /* <API key> */ /* Update the L-BFGS matrix. */ /* <API key> */ updatd = TRUE_; ++iupdat; /* Update matrices WS and WY and form the middle matrix in B. */ matupd_(n, m, &ws[ws_offset], &wy[wy_offset], &sy[sy_offset], &ss[ ss_offset], &d__[1], &r__[1], &itail, &iupdat, &col, &head, & theta, &rr, &dr, &stp, &dtd); /* Form the upper half of the pds T = theta*SS + L*D^(-1)*L'; */ /* Store T in the upper triangular of the array wt; */ /* Cholesky factorize T to J*J' with */ /* J' stored in the upper triangular of wt. */ formt_(m, &wt[wt_offset], &sy[sy_offset], &ss[ss_offset], &col, &theta, & info); if (info != 0) { /* nonpositive definiteness in Cholesky factorization; */ /* refresh the lbfgs memory and restart the iteration. */ if (*iprint >= 1) { printf("Nonpositive definiteness in Cholesky factorization; refresh the lbfgs memory and restart the iteration.\n"); // e_wsfe(); } info = 0; col = 0; head = 1; theta = 1.; iupdat = 0; updatd = FALSE_; goto L222; } /* Now the inverse of the middle matrix in B is */ /* [ D^(1/2) O ] [ -D^(1/2) D^(-1/2)*L' ] */ /* [ -L*D^(-1/2) J ] [ 0 J' ] */ L888: goto L222; L999: timer_(&time2); time = time2 - time1; prn3lb_(n, &x[1], f, task, iprint, &info, &itfile, &iter, &nfgv, &nintol, &nskip, &nact, &sbgnrm, &time, &nint, word, &iback, &stp, &xstep, &k, &cachyt, &sbtime, &lnscht, (ftnlen)60, (ftnlen)3); L1000: /* Save local variables. */ lsave[1] = prjctd; lsave[2] = cnstnd; lsave[3] = boxed; lsave[4] = updatd; isave[1] = nintol; isave[3] = itfile; isave[4] = iback; isave[5] = nskip; isave[6] = head; isave[7] = col; isave[8] = itail; isave[9] = iter; isave[10] = iupdat; isave[12] = nint; isave[13] = nfgv; isave[14] = info; isave[15] = ifun; isave[16] = iword; isave[17] = nfree; isave[18] = nact; isave[19] = ileave; isave[20] = nenter; dsave[1] = theta; dsave[2] = fold; dsave[3] = tol; dsave[4] = dnorm; dsave[5] = epsmch; dsave[6] = cpu1; dsave[7] = cachyt; dsave[8] = sbtime; dsave[9] = lnscht; dsave[10] = time1; dsave[11] = gd; dsave[12] = stpmx; dsave[13] = sbgnrm; dsave[14] = stp; dsave[15] = gdold; dsave[16] = dtd; return 0; } /* mainlb_ */ /* Subroutine */ int active_(int *n,double * l,double * u,int * nbd,double* x,int* iwhere,int * iprint,logical* prjctd,logical* cnstnd, logical *boxed) /* integer *n; doublereal *l, *u; integer *nbd; doublereal *x; integer *iwhere, *iprint; logical *prjctd, *cnstnd, *boxed;*/ { /* Format strings */ // char fmt_1001[] = "(/,\002At X0 \002,i9,\002 variables are exactly at the bounds\002)"; /* System generated locals */ integer i__1; /* Builtin functions */ integer s_wsle(), do_lio(), e_wsle(), s_wsfe(), do_fio(), e_wsfe(); /* Local variables */ integer nbdd, i__; /* Fortran I/O blocks */ /* Subroutine active */ /* This subroutine initializes iwhere and projects the initial x to */ /* the feasible set if necessary. */ /* iwhere is an integer array of dimension n. */ /* On entry iwhere is unspecified. */ /* On exit iwhere(i)=-1 if x(i) has no bounds */ /* 3 if l(i)=u(i) */ /* 0 otherwise. */ /* In cauchy, iwhere is given finer gradations. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Initialize nbdd, prjctd, cnstnd and boxed. */ /* Parameter adjustments */ --iwhere; --x; --nbd; --u; --l; /* Function Body */ nbdd = 0; *prjctd = FALSE_; *cnstnd = FALSE_; *boxed = TRUE_; /* Project the initial x to the easible set if necessary. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (nbd[i__] > 0) { if (nbd[i__] <= 2 && x[i__] <= l[i__]) { if (x[i__] < l[i__]) { *prjctd = TRUE_; x[i__] = l[i__]; } ++nbdd; } else if (nbd[i__] >= 2 && x[i__] >= u[i__]) { if (x[i__] > u[i__]) { *prjctd = TRUE_; x[i__] = u[i__]; } ++nbdd; } } /* L10: */ } /* Initialize iwhere and assign values to cnstnd and boxed. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (nbd[i__] != 2) { *boxed = FALSE_; } if (nbd[i__] == 0) { /* this variable is always free */ iwhere[i__] = -1; /* otherwise set x(i)=mid(x(i), u(i), l(i)). */ } else { *cnstnd = TRUE_; if (nbd[i__] == 2 && u[i__] - l[i__] <= 0.) { /* this variable is always fixed */ iwhere[i__] = 3; } else { iwhere[i__] = 0; } } /* L20: */ } if (*iprint >= 0) { if (*prjctd) { printf("The initial X is infeasible. Restart with its projection\n"); } if (! (*cnstnd)) { printf("The problem is unconstrained\n"); } } if (*iprint > 0) { printf("ITERATION %i\n", nbdd); } return 0; } /* active_ */ /* Subroutine */ int bmv_(int *m,double * sy,double * wt,int * col,double * v,double * p,int * info) /* integer *m; doublereal *sy, *wt; integer *col; doublereal *v, *p; integer *info; */ { /* System generated locals */ integer sy_dim1, sy_offset, wt_dim1, wt_offset, i__1, i__2; /* Builtin functions */ // double sqrt(); /* Local variables */ integer i__, k; // extern /* Subroutine */ int dtrsl_(); int dtrsl_(doublereal *t, integer *ldt, integer *n, doublereal *b, integer *job, integer *info); integer i2; doublereal sum; /* Subroutine bmv */ /* This subroutine computes the product of the 2m x 2m middle matrix */ /* in the compact L-BFGS formula of B and a 2m vector v; */ /* it returns the product in p. */ /* m is an integer variable. */ /* On entry m is the maximum number of variable metric corrections */ /* used to define the limited memory matrix. */ /* On exit m is unchanged. */ /* sy is a double precision array of dimension m x m. */ /* On entry sy specifies the matrix S'Y. */ /* On exit sy is unchanged. */ /* wt is a double precision array of dimension m x m. */ /* On entry wt specifies the upper triangular matrix J' which is */ /* the Cholesky factor of (thetaS'S+LD^(-1)L'). */ /* On exit wt is unchanged. */ /* col is an integer variable. */ /* On entry col specifies the number of s-vectors (or y-vectors) */ /* stored in the compact L-BFGS formula. */ /* On exit col is unchanged. */ /* v is a double precision array of dimension 2col. */ /* On entry v specifies vector v. */ /* On exit v is unchanged. */ /* p is a double precision array of dimension 2col. */ /* On entry p is unspecified. */ /* On exit p is the product Mv. */ /* info is an integer variable. */ /* On entry info is unspecified. */ /* On exit info = 0 for normal return, */ /* = nonzero for abnormal return when the system */ /* to be solved by dtrsl is singular. */ /* Subprograms called: */ /* Linpack ... dtrsl. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ wt_dim1 = *m; wt_offset = 1 + wt_dim1 * 1; wt -= wt_offset; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; --p; --v; /* Function Body */ if (*col == 0) { return 0; } /* PART I: solve [ D^(1/2) O ] [ p1 ] = [ v1 ] */ /* [ -L*D^(-1/2) J ] [ p2 ] [ v2 ]. */ /* solve Jp2=v2+LD^(-1)v1. */ p[*col + 1] = v[*col + 1]; i__1 = *col; for (i__ = 2; i__ <= i__1; ++i__) { i2 = *col + i__; sum = 0.; i__2 = i__ - 1; for (k = 1; k <= i__2; ++k) { sum += sy[i__ + k * sy_dim1] * v[k] / sy[k + k * sy_dim1]; /* L10: */ } p[i2] = v[i2] + sum; /* L20: */ } /* Solve the triangular system */ dtrsl_(&wt[wt_offset], m, col, &p[*col + 1], &c__11, info); if (*info != 0) { return 0; } /* solve D^(1/2)p1=v1. */ i__1 = *col; for (i__ = 1; i__ <= i__1; ++i__) { p[i__] = v[i__] / sqrt(sy[i__ + i__ * sy_dim1]); /* L30: */ } /* PART II: solve [ -D^(1/2) D^(-1/2)*L' ] [ p1 ] = [ p1 ] */ /* [ 0 J' ] [ p2 ] [ p2 ]. */ /* solve J^Tp2=p2. */ dtrsl_(&wt[wt_offset], m, col, &p[*col + 1], &c__1, info); if (*info != 0) { return 0; } /* compute p1=-D^(-1/2)(p1-D^(-1/2)L'p2) */ /* =-D^(-1/2)p1+D^(-1)L'p2. */ i__1 = *col; for (i__ = 1; i__ <= i__1; ++i__) { p[i__] = -p[i__] / sqrt(sy[i__ + i__ * sy_dim1]); /* L40: */ } i__1 = *col; for (i__ = 1; i__ <= i__1; ++i__) { sum = 0.; i__2 = *col; for (k = i__ + 1; k <= i__2; ++k) { sum += sy[k + i__ * sy_dim1] * p[*col + k] / sy[i__ + i__ * sy_dim1]; /* L50: */ } p[i__] += sum; /* L60: */ } return 0; } /* bmv_ */ /* Subroutine */ int cauchy_(int *n,double * x,double * l,double * u,int * nbd,double * g,int * iorder,int * iwhere,double * t,double * d__,double * xcp, int *m,double * wy,double * ws,double * sy,double * wt,double * theta,int * col,int * head,double * p,double * c__,double * wbp,double * v,int * nint,double * sg,double * yg, int *iprint,double * sbgnrm,int * info) /* integer *n; doublereal *x, *l, *u; integer *nbd; doublereal *g; integer *iorder, *iwhere; doublereal *t, *d__, *xcp; integer *m; doublereal *wy, *ws, *sy, *wt, *theta; integer *col, *head; doublereal *p, *c__, *wbp, *v; integer *nint; doublereal *sg, *yg; integer *iprint; doublereal *sbgnrm; integer *info;*/ { /* Format strings */ /* System generated locals */ integer wy_dim1, wy_offset, ws_dim1, ws_offset, sy_dim1, sy_offset, wt_dim1, wt_offset, i__1, i__2; doublereal d__1; /* Builtin functions */ integer s_wsle(), do_lio(), e_wsle(), s_wsfe(), e_wsfe(), do_fio(); /* Local variables */ doublereal dibp; // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer iter; doublereal zibp, tsum, dibp2; integer i__, j; logical bnded; // extern /* Subroutine */ int dscal_(); int dscal_(integer *n, doublereal *da, doublereal *dx, integer *incx); doublereal neggi; integer nfree; doublereal bkmin; integer nleft; // extern /* Subroutine */ int dcopy_(), daxpy_(); int daxpy_(integer *n, doublereal *da, doublereal *dx, integer *incx, doublereal *dy, integer *incy); int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); doublereal f1, f2, dt, tj, tl; integer nbreak, ibkmin; doublereal tu; // extern /* Subroutine */ int hpsolb_(); int hpsolb_(integer *n, doublereal *t, integer *iorder, integer *iheap); integer pointr; doublereal tj0; logical xlower, xupper; integer ibp; doublereal dtm; // extern /* Subroutine */ int bmv_(); int bmv_(integer *m, doublereal *sy, doublereal *wt, integer *col, doublereal *v, doublereal *p, integer *info); doublereal wmc, wmp, wmw; integer col2; /* Fortran I/O blocks */ /* Subroutine cauchy */ /* For given x, l, u, g (with sbgnrm > 0), and a limited memory */ /* BFGS matrix B defined in terms of matrices WY, WS, WT, and */ /* scalars head, col, and theta, this subroutine computes the */ /* generalized Cauchy point (GCP), defined as the first local */ /* minimizer of the quadratic */ /* Q(x + s) = g's + 1/2 s'Bs */ /* along the projected gradient direction P(x-tg,l,u). */ /* The routine returns the GCP in xcp. */ /* n is an integer variable. */ /* On entry n is the dimension of the problem. */ /* On exit n is unchanged. */ /* x is a double precision array of dimension n. */ /* On entry x is the starting point for the GCP computation. */ /* On exit x is unchanged. */ /* l is a double precision array of dimension n. */ /* On entry l is the lower bound of x. */ /* On exit l is unchanged. */ /* u is a double precision array of dimension n. */ /* On entry u is the upper bound of x. */ /* On exit u is unchanged. */ /* nbd is an integer array of dimension n. */ /* On entry nbd represents the type of bounds imposed on the */ /* variables, and must be specified as follows: */ /* nbd(i)=0 if x(i) is unbounded, */ /* 1 if x(i) has only a lower bound, */ /* 2 if x(i) has both lower and upper bounds, and */ /* 3 if x(i) has only an upper bound. */ /* On exit nbd is unchanged. */ /* g is a double precision array of dimension n. */ /* On entry g is the gradient of f(x). g must be a nonzero vector. */ /* On exit g is unchanged. */ /* iorder is an integer working array of dimension n. */ /* iorder will be used to store the breakpoints in the piecewise */ /* linear path and free variables encountered. On exit, */ /* iorder(1),...,iorder(nleft) are indices of breakpoints */ /* which have not been encountered; */ /* iorder(nleft+1),...,iorder(nbreak) are indices of */ /* encountered breakpoints; and */ /* iorder(nfree),...,iorder(n) are indices of variables which */ /* have no bound constraits along the search direction. */ /* iwhere is an integer array of dimension n. */ /* On entry iwhere indicates only the permanently fixed (iwhere=3) */ /* or free (iwhere= -1) components of x. */ /* On exit iwhere records the status of the current x variables. */ /* iwhere(i)=-3 if x(i) is free and has bounds, but is not moved */ /* 0 if x(i) is free and has bounds, and is moved */ /* 1 if x(i) is fixed at l(i), and l(i) .ne. u(i) */ /* 2 if x(i) is fixed at u(i), and u(i) .ne. l(i) */ /* 3 if x(i) is always fixed, i.e., u(i)=x(i)=l(i) */ /* -1 if x(i) is always free, i.e., it has no bounds. */ /* t is a double precision working array of dimension n. */ /* t will be used to store the break points. */ /* d is a double precision array of dimension n used to store */ /* the Cauchy direction P(x-tg)-x. */ /* xcp is a double precision array of dimension n used to return the */ /* GCP on exit. */ /* m is an integer variable. */ /* On entry m is the maximum number of variable metric corrections */ /* used to define the limited memory matrix. */ /* On exit m is unchanged. */ /* ws, wy, sy, and wt are double precision arrays. */ /* On entry they store information that defines the */ /* limited memory BFGS matrix: */ /* ws(n,m) stores S, a set of s-vectors; */ /* wy(n,m) stores Y, a set of y-vectors; */ /* sy(m,m) stores S'Y; */ /* wt(m,m) stores the */ /* Cholesky factorization of (theta*S'S+LD^(-1)L'). */ /* On exit these arrays are unchanged. */ /* theta is a double precision variable. */ /* On entry theta is the scaling factor specifying B_0 = theta I. */ /* On exit theta is unchanged. */ /* col is an integer variable. */ /* On entry col is the actual number of variable metric */ /* corrections stored so far. */ /* On exit col is unchanged. */ /* head is an integer variable. */ /* On entry head is the location of the first s-vector (or y-vector) */ /* in S (or Y). */ /* On exit col is unchanged. */ /* p is a double precision working array of dimension 2m. */ /* p will be used to store the vector p = W^(T)d. */ /* c is a double precision working array of dimension 2m. */ /* c will be used to store the vector c = W^(T)(xcp-x). */ /* wbp is a double precision working array of dimension 2m. */ /* wbp will be used to store the row of W corresponding */ /* to a breakpoint. */ /* v is a double precision working array of dimension 2m. */ /* nint is an integer variable. */ /* On exit nint records the number of quadratic segments explored */ /* in searching for the GCP. */ /* sg and yg are double precision arrays of dimension m. */ /* On entry sg and yg store S'g and Y'g correspondingly. */ /* On exit they are unchanged. */ /* iprint is an INTEGER variable that must be set by the user. */ /* It controls the frequency and type of output generated: */ /* iprint<0 no output is generated; */ /* iprint=0 print only one line at the last iteration; */ /* 0<iprint<99 print also f and |proj g| every iprint iterations; */ /* iprint=99 print details of every iteration except n-vectors; */ /* iprint=100 print also the changes of active set and final x; */ /* iprint>100 print details of every iteration including x and g; */ /* When iprint > 0, the file iterate.dat will be created to */ /* summarize the iteration. */ /* sbgnrm is a double precision variable. */ /* On entry sbgnrm is the norm of the projected gradient at x. */ /* On exit sbgnrm is unchanged. */ /* info is an integer variable. */ /* On entry info is 0. */ /* On exit info = 0 for normal return, */ /* = nonzero for abnormal return when the the system */ /* used in routine bmv is singular. */ /* Subprograms called: */ /* L-BFGS-B Library ... hpsolb, bmv. */ /* Linpack ... dscal dcopy, daxpy. */ /* References: */ /* [1] R. H. Byrd, P. Lu, J. Nocedal and C. Zhu, ``A limited */ /* memory algorithm for bound constrained optimization'', */ /* SIAM J. Scientific Computing 16 (1995), no. 5, pp. 1190--1208. */ /* [2] C. Zhu, R.H. Byrd, P. Lu, J. Nocedal, ``L-BFGS-B: FORTRAN */ /* Subroutines for Large Scale Bound Constrained Optimization'' */ /* Tech. Report, NAM-11, EECS Department, Northwestern University, */ /* 1994. */ /* (Postscript files of these papers are available via anonymous */ /* ftp to eecs.nwu.edu in the directory pub/lbfgs/lbfgs_bcm.) */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Check the status of the variables, reset iwhere(i) if necessary; */ /* compute the Cauchy direction d and the breakpoints t; initialize */ /* the derivative f1 and the vector p = W'd (for theta = 1). */ /* Parameter adjustments */ --xcp; --d__; --t; --iwhere; --iorder; --g; --nbd; --u; --l; --x; --yg; --sg; --v; --wbp; --c__; --p; wt_dim1 = *m; wt_offset = 1 + wt_dim1 * 1; wt -= wt_offset; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; ws_dim1 = *n; ws_offset = 1 + ws_dim1 * 1; ws -= ws_offset; wy_dim1 = *n; wy_offset = 1 + wy_dim1 * 1; wy -= wy_offset; /* Function Body */ if (*sbgnrm <= 0.) { if (*iprint >= 0) { printf("Subgnorm = 0. GCP = X.\n"); } dcopy_(n, &x[1], &c__1, &xcp[1], &c__1); return 0; } bnded = TRUE_; nfree = *n + 1; nbreak = 0; ibkmin = 0; bkmin = 0.; col2 = *col << 1; f1 = 0.; if (*iprint >= 99) { printf(" } /* We set p to zero and build it up as we determine d. */ i__1 = col2; for (i__ = 1; i__ <= i__1; ++i__) { p[i__] = 0.; /* L20: */ } /* In the following loop we determine for each variable its bound */ /* status and its breakpoint, and update p accordingly. */ /* Smallest breakpoint is identified. */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { neggi = -g[i__]; if (iwhere[i__] != 3 && iwhere[i__] != -1) { /* if x(i) is not a constant and has bounds, */ /* compute the difference between x(i) and its bounds. */ if (nbd[i__] <= 2) { tl = x[i__] - l[i__]; } if (nbd[i__] >= 2) { tu = u[i__] - x[i__]; } /* If a variable is close enough to a bound */ /* we treat it as at bound. */ xlower = nbd[i__] <= 2 && tl <= 0.; xupper = nbd[i__] >= 2 && tu <= 0.; /* reset iwhere(i). */ iwhere[i__] = 0; if (xlower) { if (neggi <= 0.) { iwhere[i__] = 1; } } else if (xupper) { if (neggi >= 0.) { iwhere[i__] = 2; } } else { if (abs(neggi) <= 0.) { iwhere[i__] = -3; } } } pointr = *head; if (iwhere[i__] != 0 && iwhere[i__] != -1) { d__[i__] = 0.; } else { d__[i__] = neggi; f1 -= neggi * neggi; /* calculate p := p - W'e_i* (g_i). */ i__2 = *col; for (j = 1; j <= i__2; ++j) { p[j] += wy[i__ + pointr * wy_dim1] * neggi; p[*col + j] += ws[i__ + pointr * ws_dim1] * neggi; pointr = pointr % *m + 1; /* L40: */ } if (nbd[i__] <= 2 && nbd[i__] != 0 && neggi < 0.) { /* x(i) + d(i) is bounded; compute t(i). */ ++nbreak; iorder[nbreak] = i__; t[nbreak] = tl / (-neggi); if (nbreak == 1 || t[nbreak] < bkmin) { bkmin = t[nbreak]; ibkmin = nbreak; } } else if (nbd[i__] >= 2 && neggi > 0.) { /* x(i) + d(i) is bounded; compute t(i). */ ++nbreak; iorder[nbreak] = i__; t[nbreak] = tu / neggi; if (nbreak == 1 || t[nbreak] < bkmin) { bkmin = t[nbreak]; ibkmin = nbreak; } } else { /* x(i) + d(i) is not bounded. */ --nfree; iorder[nfree] = i__; if (abs(neggi) > 0.) { bnded = FALSE_; } } } /* L50: */ } /* The indices of the nonzero components of d are now stored */ /* in iorder(1),...,iorder(nbreak) and iorder(nfree),...,iorder(n). */ /* The smallest of the nbreak breakpoints is in t(ibkmin)=bkmin. */ if (*theta != 1.) { /* complete the initialization of p for theta not= one. */ dscal_(col, theta, &p[*col + 1], &c__1); } /* Initialize GCP xcp = x. */ dcopy_(n, &x[1], &c__1, &xcp[1], &c__1); if (nbreak == 0 && nfree == *n + 1) { /* is a zero vector, return with the initial xcp as GCP. */ if (*iprint > 100) { printf("Cauchy X = \n"); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) printf("\t%e", xcp[i__]); printf("\n"); } return 0; } /* Initialize c = W'(xcp - x) = 0. */ i__1 = col2; for (j = 1; j <= i__1; ++j) { c__[j] = 0.; /* L60: */ } /* Initialize derivative f2. */ f2 = -(*theta) * f1; if (*col > 0) { bmv_(m, &sy[sy_offset], &wt[wt_offset], col, &p[1], &v[1], info); if (*info != 0) { return 0; } f2 -= ddot_(&col2, &v[1], &c__1, &p[1], &c__1); } dtm = -f1 / f2; tsum = 0.; *nint = 1; if (*iprint >= 99) { printf("There are %i breakpoints\n", nbreak); } /* If there are no breakpoints, locate the GCP and return. */ if (nbreak == 0) { goto L888; } nleft = nbreak; iter = 1; tj = 0.; L777: /* Find the next smallest breakpoint; */ /* compute dt = t(nleft) - t(nleft + 1). */ tj0 = tj; if (iter == 1) { /* Since we already have the smallest breakpoint we need not do */ /* heapsort yet. Often only one breakpoint is used and the */ /* cost of heapsort is avoided. */ tj = bkmin; ibp = iorder[ibkmin]; } else { if (iter == 2) { /* Replace the already used smallest breakpoint with the */ /* breakpoint numbered nbreak > nlast, before heapsort call. */ if (ibkmin != nbreak) { t[ibkmin] = t[nbreak]; iorder[ibkmin] = iorder[nbreak]; } /* Update heap structure of breakpoints */ /* (if iter=2, initialize heap). */ } i__1 = iter - 2; hpsolb_(&nleft, &t[1], &iorder[1], &i__1); tj = t[nleft]; ibp = iorder[nleft]; } dt = tj - tj0; if (dt != 0. && *iprint >= 100) { printf("Piece %i --f1, f2 at start point %e %e\n", *nint, f1, f2); printf("Distance to the next break point = %e\n", dt); printf("Distance to the stationary point = %e\n", dtm); } /* If a minimizer is within this interval, locate the GCP and return. */ if (dtm < dt) { goto L888; } /* Otherwise fix one variable and */ /* reset the corresponding component of d to zero. */ tsum += dt; --nleft; ++iter; dibp = d__[ibp]; d__[ibp] = 0.; if (dibp > 0.) { zibp = u[ibp] - x[ibp]; xcp[ibp] = u[ibp]; iwhere[ibp] = 2; } else { zibp = l[ibp] - x[ibp]; xcp[ibp] = l[ibp]; iwhere[ibp] = 1; } if (*iprint >= 100) { printf("Variable %i is fixed\n", ibp); } if (nleft == 0 && nbreak == *n) { /* all n variables are fixed, */ /* return with xcp as GCP. */ dtm = dt; goto L999; } /* Update the derivative information. */ ++(*nint); /* Computing 2nd power */ d__1 = dibp; dibp2 = d__1 * d__1; /* Update f1 and f2. */ /* temporarily set f1 and f2 for col=0. */ f1 = f1 + dt * f2 + dibp2 - *theta * dibp * zibp; f2 -= *theta * dibp2; if (*col > 0) { /* update c = c + dt*p. */ daxpy_(&col2, &dt, &p[1], &c__1, &c__[1], &c__1); /* choose wbp, */ /* the row of W corresponding to the breakpoint encountered. */ pointr = *head; i__1 = *col; for (j = 1; j <= i__1; ++j) { wbp[j] = wy[ibp + pointr * wy_dim1]; wbp[*col + j] = *theta * ws[ibp + pointr * ws_dim1]; pointr = pointr % *m + 1; /* L70: */ } /* compute (wbp)Mc, (wbp)Mp, and (wbp)M(wbp)'. */ bmv_(m, &sy[sy_offset], &wt[wt_offset], col, &wbp[1], &v[1], info); if (*info != 0) { return 0; } wmc = ddot_(&col2, &c__[1], &c__1, &v[1], &c__1); wmp = ddot_(&col2, &p[1], &c__1, &v[1], &c__1); wmw = ddot_(&col2, &wbp[1], &c__1, &v[1], &c__1); /* update p = p - dibp*wbp. */ d__1 = -dibp; daxpy_(&col2, &d__1, &wbp[1], &c__1, &p[1], &c__1); /* complete updating f1 and f2 while col > 0. */ f1 += dibp * wmc; f2 = f2 + dibp * 2. * wmp - dibp2 * wmw; } if (nleft > 0) { dtm = -f1 / f2; goto L777; /* to repeat the loop for unsearched intervals. */ } else if (bnded) { f1 = 0.; f2 = 0.; dtm = 0.; } else { dtm = -f1 / f2; } L888: if (*iprint >= 99) { printf("GCP found in this segment\n"); printf("Piece %i --f1, f2 at start point %e %e\n", *nint, f1, f2); printf("Distance to the stationary point = %e\n", dtm); } if (dtm <= 0.) { dtm = 0.; } tsum += dtm; /* Move free variables (i.e., the ones w/o breakpoints) and */ /* the variables whose breakpoints haven't been reached. */ daxpy_(n, &tsum, &d__[1], &c__1, &xcp[1], &c__1); L999: /* Update c = c + dtm*p = W'(x^c - x) */ /* which will be used in computing r = Z'(B(x^c - x) + g). */ if (*col > 0) { daxpy_(&col2, &dtm, &p[1], &c__1, &c__[1], &c__1); } if (*iprint > 100) { printf("Cauchy X =\n"); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) printf("\t%e", xcp[i__]); printf("\n"); } if (*iprint >= 99) { printf(" } return 0; } /* cauchy_ */ /* Subroutine */ int cmprlb_(int *n,int * m,doublereal * x,doublereal * g,doublereal * ws,doublereal * wy,doublereal * sy,doublereal * wt,doublereal * z__,doublereal * r__,doublereal * wa,int * index,doublereal * theta,int * col,int * head,int * nfree,logical * cnstnd, int *info)/* integer *n, *m; doublereal *x, *g, *ws, *wy, *sy, *wt, *z__, *r__, *wa; integer *index; doublereal *theta; integer *col, *head, *nfree; logical *cnstnd; integer *info;*/ { /* System generated locals */ integer ws_dim1, ws_offset, wy_dim1, wy_offset, sy_dim1, sy_offset, wt_dim1, wt_offset, i__1, i__2; /* Local variables */ integer i__, j, k; doublereal a1, a2; integer pointr; // extern /* Subroutine */ int bmv_(); int bmv_(integer *m, doublereal *sy, doublereal *wt, integer *col, doublereal *v, doublereal *p, integer *info); /* Subroutine cmprlb */ /* This subroutine computes r=-Z'B(xcp-xk)-Z'g by using */ /* wa(2m+1)=W'(xcp-x) from subroutine cauchy. */ /* Subprograms called: */ /* L-BFGS-B Library ... bmv. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --index; --r__; --z__; --g; --x; --wa; wt_dim1 = *m; wt_offset = 1 + wt_dim1 * 1; wt -= wt_offset; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; wy_dim1 = *n; wy_offset = 1 + wy_dim1 * 1; wy -= wy_offset; ws_dim1 = *n; ws_offset = 1 + ws_dim1 * 1; ws -= ws_offset; /* Function Body */ if (! (*cnstnd) && *col > 0) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { r__[i__] = -g[i__]; /* L26: */ } } else { i__1 = *nfree; for (i__ = 1; i__ <= i__1; ++i__) { k = index[i__]; r__[i__] = -(*theta) * (z__[k] - x[k]) - g[k]; /* L30: */ } bmv_(m, &sy[sy_offset], &wt[wt_offset], col, &wa[(*m << 1) + 1], &wa[ 1], info); if (*info != 0) { *info = -8; return 0; } pointr = *head; i__1 = *col; for (j = 1; j <= i__1; ++j) { a1 = wa[j]; a2 = *theta * wa[*col + j]; i__2 = *nfree; for (i__ = 1; i__ <= i__2; ++i__) { k = index[i__]; r__[i__] = r__[i__] + wy[k + pointr * wy_dim1] * a1 + ws[k + pointr * ws_dim1] * a2; /* L32: */ } pointr = pointr % *m + 1; /* L34: */ } } return 0; } /* cmprlb_ */ /* Subroutine */ int errclb_(int *n,int * m,double * factr,double * l,double * u,int * nbd,char * task,int* info,int * k,ftnlen task_len)/* integer *n, *m; doublereal *factr, *l, *u; integer *nbd; char *task; integer *info, *k; ftnlen task_len;*/ { /* System generated locals */ integer i__1; /* Builtin functions */ // /* Subroutine */ int s_copy(); /* Local variables */ integer i__; /* Subroutine errclb */ /* This subroutine checks the validity of the input data. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Check the input arguments for errors. */ /* Parameter adjustments */ --nbd; --u; --l; /* Function Body */ if (*n <= 0) { my_strcpy(task, "ERROR: N .LE. 0"); // s_copy(task, "ERROR: N .LE. 0", (ftnlen)60, (ftnlen)15); } if (*m <= 0) { my_strcpy(task, "ERROR: M .LE. 0"); // s_copy(task, "ERROR: M .LE. 0", (ftnlen)60, (ftnlen)15); } if (*factr < 0.) { my_strcpy(task, "ERROR: FACTR .LT. 0"); // s_copy(task, "ERROR: FACTR .LT. 0", (ftnlen)60, (ftnlen)19); } /* Check the validity of the arrays nbd(i), u(i), and l(i). */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (nbd[i__] < 0 || nbd[i__] > 3) { /* return */ my_strcpy(task, "ERROR: INVALID NBD"); // s_copy(task, "ERROR: INVALID NBD", (ftnlen)60, (ftnlen)18); *info = -6; *k = i__; } if (nbd[i__] == 2) { if (l[i__] > u[i__]) { /* return */ my_strcpy(task, "ERROR: NO FEASIBLE SOLUTION"); // s_copy(task, "ERROR: NO FEASIBLE SOLUTION", (ftnlen)60, ( // ftnlen)27); *info = -7; *k = i__; } } /* L10: */ } return 0; } /* errclb_ */ /* Subroutine */ int formk_(int *n,integer * nsub,integer * ind,integer * nenter,integer * ileave,integer * indx2,integer * iupdat, logical *updatd,double * wn,double * wn1,int * m,double * ws,double * wy,double * sy,double * theta,int * col,int * head,int * info)/* integer *n, *nsub, *ind, *nenter, *ileave, *indx2, *iupdat; logical *updatd; doublereal *wn, *wn1; integer *m; doublereal *ws, *wy, *sy, *theta; integer *col, *head, *info;*/ { /* System generated locals */ integer wn_dim1, wn_offset, wn1_dim1, wn1_offset, ws_dim1, ws_offset, wy_dim1, wy_offset, sy_dim1, sy_offset, i__1, i__2, i__3; /* Local variables */ integer dend, pend; // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer upcl; doublereal temp1, temp2, temp3, temp4; integer i__, k; // extern /* Subroutine */ int dpofa_(), dcopy_(), dtrsl_(); int dpofa_(doublereal *a, integer *lda, integer *n, integer *info); int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); int dtrsl_(doublereal *t, integer *ldt, integer *n, doublereal *b, integer *job, integer *info); integer ipntr, jpntr, k1, m2, dbegin, is, js, iy, jy, pbegin, is1, js1, col2; /* Subroutine formk */ /* This subroutine forms the LEL^T factorization of the indefinite */ /* matrix K = [-D -Y'ZZ'Y/theta L_a'-R_z' ] */ /* [L_a -R_z theta*S'AA'S ] */ /* where E = [-I 0] */ /* [ 0 I] */ /* The matrix K can be shown to be equal to the matrix M^[-1]N */ /* occurring in section 5.1 of [1], as well as to the matrix */ /* Mbar^[-1] Nbar in section 5.3. */ /* n is an integer variable. */ /* On entry n is the dimension of the problem. */ /* On exit n is unchanged. */ /* nsub is an integer variable */ /* On entry nsub is the number of subspace variables in free set. */ /* On exit nsub is not changed. */ /* ind is an integer array of dimension nsub. */ /* On entry ind specifies the indices of subspace variables. */ /* On exit ind is unchanged. */ /* nenter is an integer variable. */ /* On entry nenter is the number of variables entering the */ /* free set. */ /* On exit nenter is unchanged. */ /* ileave is an integer variable. */ /* On entry indx2(ileave),...,indx2(n) are the variables leaving */ /* the free set. */ /* On exit ileave is unchanged. */ /* indx2 is an integer array of dimension n. */ /* On entry indx2(1),...,indx2(nenter) are the variables entering */ /* the free set, while indx2(ileave),...,indx2(n) are the */ /* variables leaving the free set. */ /* On exit indx2 is unchanged. */ /* iupdat is an integer variable. */ /* On entry iupdat is the total number of BFGS updates made so far. */ /* On exit iupdat is unchanged. */ /* updatd is a logical variable. */ /* On entry 'updatd' is true if the L-BFGS matrix is updatd. */ /* On exit 'updatd' is unchanged. */ /* wn is a double precision array of dimension 2m x 2m. */ /* On entry wn is unspecified. */ /* On exit the upper triangle of wn stores the LEL^T factorization */ /* of the 2*col x 2*col indefinite matrix */ /* [-D -Y'ZZ'Y/theta L_a'-R_z' ] */ /* [L_a -R_z theta*S'AA'S ] */ /* wn1 is a double precision array of dimension 2m x 2m. */ /* On entry wn1 stores the lower triangular part of */ /* [Y' ZZ'Y L_a'+R_z'] */ /* [L_a+R_z S'AA'S ] */ /* in the previous iteration. */ /* On exit wn1 stores the corresponding updated matrices. */ /* The purpose of wn1 is just to store these inner products */ /* so they can be easily updated and inserted into wn. */ /* m is an integer variable. */ /* On entry m is the maximum number of variable metric corrections */ /* used to define the limited memory matrix. */ /* On exit m is unchanged. */ /* ws, wy, sy, and wtyy are double precision arrays; */ /* theta is a double precision variable; */ /* col is an integer variable; */ /* head is an integer variable. */ /* On entry they store the information defining the */ /* limited memory BFGS matrix: */ /* ws(n,m) stores S, a set of s-vectors; */ /* wy(n,m) stores Y, a set of y-vectors; */ /* sy(m,m) stores S'Y; */ /* wtyy(m,m) stores the Cholesky factorization */ /* of (theta*S'S+LD^(-1)L') */ /* theta is the scaling factor specifying B_0 = theta I; */ /* col is the number of variable metric corrections stored; */ /* head is the location of the 1st s- (or y-) vector in S (or Y). */ /* On exit they are unchanged. */ /* info is an integer variable. */ /* On entry info is unspecified. */ /* On exit info = 0 for normal return; */ /* = -1 when the 1st Cholesky factorization failed; */ /* = -2 when the 2st Cholesky factorization failed. */ /* Subprograms called: */ /* Linpack ... dcopy, dpofa, dtrsl. */ /* References: */ /* [1] R. H. Byrd, P. Lu, J. Nocedal and C. Zhu, ``A limited */ /* memory algorithm for bound constrained optimization'', */ /* SIAM J. Scientific Computing 16 (1995), no. 5, pp. 1190--1208. */ /* [2] C. Zhu, R.H. Byrd, P. Lu, J. Nocedal, ``L-BFGS-B: a */ /* limited memory FORTRAN code for solving bound constrained */ /* optimization problems'', Tech. Report, NAM-11, EECS Department, */ /* Northwestern University, 1994. */ /* (Postscript files of these papers are available via anonymous */ /* ftp to eecs.nwu.edu in the directory pub/lbfgs/lbfgs_bcm.) */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Form the lower triangular part of */ /* WN1 = [Y' ZZ'Y L_a'+R_z'] */ /* [L_a+R_z S'AA'S ] */ /* where L_a is the strictly lower triangular part of S'AA'Y */ /* R_z is the upper triangular part of S'ZZ'Y. */ /* Parameter adjustments */ --indx2; --ind; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; wy_dim1 = *n; wy_offset = 1 + wy_dim1 * 1; wy -= wy_offset; ws_dim1 = *n; ws_offset = 1 + ws_dim1 * 1; ws -= ws_offset; wn1_dim1 = 2 * *m; wn1_offset = 1 + wn1_dim1 * 1; wn1 -= wn1_offset; wn_dim1 = 2 * *m; wn_offset = 1 + wn_dim1 * 1; wn -= wn_offset; /* Function Body */ if (*updatd) { if (*iupdat > *m) { /* shift old part of WN1. */ i__1 = *m - 1; for (jy = 1; jy <= i__1; ++jy) { js = *m + jy; i__2 = *m - jy; dcopy_(&i__2, &wn1[jy + 1 + (jy + 1) * wn1_dim1], &c__1, &wn1[ jy + jy * wn1_dim1], &c__1); i__2 = *m - jy; dcopy_(&i__2, &wn1[js + 1 + (js + 1) * wn1_dim1], &c__1, &wn1[ js + js * wn1_dim1], &c__1); i__2 = *m - 1; dcopy_(&i__2, &wn1[*m + 2 + (jy + 1) * wn1_dim1], &c__1, &wn1[ *m + 1 + jy * wn1_dim1], &c__1); /* L10: */ } } /* put new rows in blocks (1,1), (2,1) and (2,2). */ pbegin = 1; pend = *nsub; dbegin = *nsub + 1; dend = *n; iy = *col; is = *m + *col; ipntr = *head + *col - 1; if (ipntr > *m) { ipntr -= *m; } jpntr = *head; i__1 = *col; for (jy = 1; jy <= i__1; ++jy) { js = *m + jy; temp1 = 0.; temp2 = 0.; temp3 = 0.; /* compute element jy of row 'col' of Y'ZZ'Y */ i__2 = pend; for (k = pbegin; k <= i__2; ++k) { k1 = ind[k]; temp1 += wy[k1 + ipntr * wy_dim1] * wy[k1 + jpntr * wy_dim1]; /* L15: */ } /* compute elements jy of row 'col' of L_a and S'AA'S */ i__2 = dend; for (k = dbegin; k <= i__2; ++k) { k1 = ind[k]; temp2 += ws[k1 + ipntr * ws_dim1] * ws[k1 + jpntr * ws_dim1]; temp3 += ws[k1 + ipntr * ws_dim1] * wy[k1 + jpntr * wy_dim1]; /* L16: */ } wn1[iy + jy * wn1_dim1] = temp1; wn1[is + js * wn1_dim1] = temp2; wn1[is + jy * wn1_dim1] = temp3; jpntr = jpntr % *m + 1; /* L20: */ } /* put new column in block (2,1). */ jy = *col; jpntr = *head + *col - 1; if (jpntr > *m) { jpntr -= *m; } ipntr = *head; i__1 = *col; for (i__ = 1; i__ <= i__1; ++i__) { is = *m + i__; temp3 = 0.; /* compute element i of column 'col' of R_z */ i__2 = pend; for (k = pbegin; k <= i__2; ++k) { k1 = ind[k]; temp3 += ws[k1 + ipntr * ws_dim1] * wy[k1 + jpntr * wy_dim1]; /* L25: */ } ipntr = ipntr % *m + 1; wn1[is + jy * wn1_dim1] = temp3; /* L30: */ } upcl = *col - 1; } else { upcl = *col; } /* modify the old parts in blocks (1,1) and (2,2) due to changes */ /* in the set of free variables. */ ipntr = *head; i__1 = upcl; for (iy = 1; iy <= i__1; ++iy) { is = *m + iy; jpntr = *head; i__2 = iy; for (jy = 1; jy <= i__2; ++jy) { js = *m + jy; temp1 = 0.; temp2 = 0.; temp3 = 0.; temp4 = 0.; i__3 = *nenter; for (k = 1; k <= i__3; ++k) { k1 = indx2[k]; temp1 += wy[k1 + ipntr * wy_dim1] * wy[k1 + jpntr * wy_dim1]; temp2 += ws[k1 + ipntr * ws_dim1] * ws[k1 + jpntr * ws_dim1]; /* L35: */ } i__3 = *n; for (k = *ileave; k <= i__3; ++k) { k1 = indx2[k]; temp3 += wy[k1 + ipntr * wy_dim1] * wy[k1 + jpntr * wy_dim1]; temp4 += ws[k1 + ipntr * ws_dim1] * ws[k1 + jpntr * ws_dim1]; /* L36: */ } wn1[iy + jy * wn1_dim1] = wn1[iy + jy * wn1_dim1] + temp1 - temp3; wn1[is + js * wn1_dim1] = wn1[is + js * wn1_dim1] - temp2 + temp4; jpntr = jpntr % *m + 1; /* L40: */ } ipntr = ipntr % *m + 1; /* L45: */ } /* modify the old parts in block (2,1). */ ipntr = *head; i__1 = *m + upcl; for (is = *m + 1; is <= i__1; ++is) { jpntr = *head; i__2 = upcl; for (jy = 1; jy <= i__2; ++jy) { temp1 = 0.; temp3 = 0.; i__3 = *nenter; for (k = 1; k <= i__3; ++k) { k1 = indx2[k]; temp1 += ws[k1 + ipntr * ws_dim1] * wy[k1 + jpntr * wy_dim1]; /* L50: */ } i__3 = *n; for (k = *ileave; k <= i__3; ++k) { k1 = indx2[k]; temp3 += ws[k1 + ipntr * ws_dim1] * wy[k1 + jpntr * wy_dim1]; /* L51: */ } if (is <= jy + *m) { wn1[is + jy * wn1_dim1] = wn1[is + jy * wn1_dim1] + temp1 - temp3; } else { wn1[is + jy * wn1_dim1] = wn1[is + jy * wn1_dim1] - temp1 + temp3; } jpntr = jpntr % *m + 1; /* L55: */ } ipntr = ipntr % *m + 1; /* L60: */ } /* Form the upper triangle of WN = [D+Y' ZZ'Y/theta -L_a'+R_z' ] */ /* [-L_a +R_z S'AA'S*theta] */ m2 = *m << 1; i__1 = *col; for (iy = 1; iy <= i__1; ++iy) { is = *col + iy; is1 = *m + iy; i__2 = iy; for (jy = 1; jy <= i__2; ++jy) { js = *col + jy; js1 = *m + jy; wn[jy + iy * wn_dim1] = wn1[iy + jy * wn1_dim1] / *theta; wn[js + is * wn_dim1] = wn1[is1 + js1 * wn1_dim1] * *theta; /* L65: */ } i__2 = iy - 1; for (jy = 1; jy <= i__2; ++jy) { wn[jy + is * wn_dim1] = -wn1[is1 + jy * wn1_dim1]; /* L66: */ } i__2 = *col; for (jy = iy; jy <= i__2; ++jy) { wn[jy + is * wn_dim1] = wn1[is1 + jy * wn1_dim1]; /* L67: */ } wn[iy + iy * wn_dim1] += sy[iy + iy * sy_dim1]; /* L70: */ } /* Form the upper triangle of WN= [ LL' L^-1(-L_a'+R_z')] */ /* [(-L_a +R_z)L'^-1 S'AA'S*theta ] */ /* first Cholesky factor (1,1) block of wn to get LL' */ /* with L' stored in the upper triangle of wn. */ dpofa_(&wn[wn_offset], &m2, col, info); if (*info != 0) { *info = -1; return 0; } /* then form L^-1(-L_a'+R_z') in the (1,2) block. */ col2 = *col << 1; i__1 = col2; for (js = *col + 1; js <= i__1; ++js) { dtrsl_(&wn[wn_offset], &m2, col, &wn[js * wn_dim1 + 1], &c__11, info); /* L71: */ } /* Form S'AA'S*theta + (L^-1(-L_a'+R_z'))'L^-1(-L_a'+R_z') in the */ /* upper triangle of (2,2) block of wn. */ i__1 = col2; for (is = *col + 1; is <= i__1; ++is) { i__2 = col2; for (js = is; js <= i__2; ++js) { wn[is + js * wn_dim1] += ddot_(col, &wn[is * wn_dim1 + 1], &c__1, &wn[js * wn_dim1 + 1], &c__1); /* L74: */ } /* L72: */ } /* Cholesky factorization of (2,2) block of wn. */ dpofa_(&wn[*col + 1 + (*col + 1) * wn_dim1], &m2, col, info); if (*info != 0) { *info = -2; return 0; } return 0; } /* formk_ */ /* Subroutine */ int formt_(int *m, double *wt,double * sy,double * ss,int * col,double * theta,int * info)/* integer *m; doublereal *wt, *sy, *ss; integer *col; doublereal *theta; integer *info;*/ { /* System generated locals */ integer wt_dim1, wt_offset, sy_dim1, sy_offset, ss_dim1, ss_offset, i__1, i__2, i__3; /* Local variables */ doublereal ddum; integer i__, j, k; // extern /* Subroutine */ int dpofa_(); int dpofa_(doublereal *a, integer *lda, integer *n, integer *info); integer k1; /* Subroutine formt */ /* This subroutine forms the upper half of the pos. def. and symm. */ /* T = theta*SS + L*D^(-1)*L', stores T in the upper triangle */ /* of the array wt, and performs the Cholesky factorization of T */ /* to produce J*J', with J' stored in the upper triangle of wt. */ /* Subprograms called: */ /* Linpack ... dpofa. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Form the upper half of T = theta*SS + L*D^(-1)*L', */ /* store T in the upper triangle of the array wt. */ /* Parameter adjustments */ ss_dim1 = *m; ss_offset = 1 + ss_dim1 * 1; ss -= ss_offset; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; wt_dim1 = *m; wt_offset = 1 + wt_dim1 * 1; wt -= wt_offset; /* Function Body */ i__1 = *col; for (j = 1; j <= i__1; ++j) { wt[j * wt_dim1 + 1] = *theta * ss[j * ss_dim1 + 1]; /* L52: */ } i__1 = *col; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = *col; for (j = i__; j <= i__2; ++j) { k1 = min(i__,j) - 1; ddum = 0.; i__3 = k1; for (k = 1; k <= i__3; ++k) { ddum += sy[i__ + k * sy_dim1] * sy[j + k * sy_dim1] / sy[k + k * sy_dim1]; /* L53: */ } wt[i__ + j * wt_dim1] = ddum + *theta * ss[i__ + j * ss_dim1]; /* L54: */ } /* L55: */ } /* Cholesky factorize T to J*J' with */ /* J' stored in the upper triangle of wt. */ dpofa_(&wt[wt_offset], m, col, info); if (*info != 0) { *info = -3; } return 0; } /* formt_ */ /* Subroutine */ int freev_(int *n,int * nfree,int * index,int * nenter,int * ileave,int * indx2,int * iwhere, logical *wrk,logical * updatd,logical * cnstnd,int * iprint,int * iter)/* integer *n, *nfree, *index, *nenter, *ileave, *indx2, *iwhere; logical *wrk, *updatd, *cnstnd; integer *iprint, *iter;*/ { /* System generated locals */ integer i__1; /* Builtin functions */ integer s_wsle(), do_lio(), e_wsle(); /* Local variables */ integer iact, i__, k; /* Fortran I/O blocks */ /* Subroutine freev */ /* This subroutine counts the entering and leaving variables when */ /* iter > 0, and finds the index set of free and active variables */ /* at the GCP. */ /* cnstnd is a logical variable indicating whether bounds are present */ /* index is an integer array of dimension n */ /* for i=1,...,nfree, index(i) are the indices of free variables */ /* for i=nfree+1,...,n, index(i) are the indices of bound variables */ /* On entry after the first iteration, index gives */ /* the free variables at the previous iteration. */ /* On exit it gives the free variables based on the determination */ /* in cauchy using the array iwhere. */ /* indx2 is an integer array of dimension n */ /* On entry indx2 is unspecified. */ /* On exit with iter>0, indx2 indicates which variables */ /* have changed status since the previous iteration. */ /* For i= 1,...,nenter, indx2(i) have changed from bound to free. */ /* For i= ileave+1,...,n, indx2(i) have changed from free to bound. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --iwhere; --indx2; --index; /* Function Body */ *nenter = 0; *ileave = *n + 1; if (*iter > 0 && *cnstnd) { /* count the entering and leaving variables. */ i__1 = *nfree; for (i__ = 1; i__ <= i__1; ++i__) { k = index[i__]; if (iwhere[k] > 0) { --(*ileave); indx2[*ileave] = k; if (*iprint >= 100) { printf("Variable %i leaves the set of free variables\n", k); } } /* L20: */ } i__1 = *n; for (i__ = *nfree + 1; i__ <= i__1; ++i__) { k = index[i__]; if (iwhere[k] <= 0) { ++(*nenter); indx2[*nenter] = k; if (*iprint >= 100) { printf("Variable %i enters the set of free variables\n",k); } } /* L22: */ } if (*iprint >= 99) { i__1 = *n + 1 - *ileave; printf("%i variables leave; %i variables enter\n", i__1, *nenter); } } *wrk = *ileave < *n + 1 || *nenter > 0 || *updatd; /* Find the index set of free and active variables at the GCP. */ *nfree = 0; iact = *n + 1; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { if (iwhere[i__] <= 0) { ++(*nfree); index[*nfree] = i__; } else { --iact; index[iact] = i__; } /* L24: */ } if (*iprint >= 99) { i__1 = *iter + 1; printf(" %i variables are free at GCP %i\n", *nfree, i__1); } return 0; } /* freev_ */ /* Subroutine */ int hpsolb_(int *n,double * t,int * iorder,int * iheap)/* integer *n; doublereal *t; integer *iorder, *iheap;*/ { /* System generated locals */ integer i__1; /* Local variables */ doublereal ddum; integer i__, j, k, indxin, indxou; doublereal out; /* Subroutine hpsolb */ /* This subroutine sorts out the least element of t, and puts the */ /* remaining elements of t in a heap. */ /* n is an integer variable. */ /* On entry n is the dimension of the arrays t and iorder. */ /* On exit n is unchanged. */ /* t is a double precision array of dimension n. */ /* On entry t stores the elements to be sorted, */ /* On exit t(n) stores the least elements of t, and t(1) to t(n-1) */ /* stores the remaining elements in the form of a heap. */ /* iorder is an integer array of dimension n. */ /* On entry iorder(i) is the index of t(i). */ /* On exit iorder(i) is still the index of t(i), but iorder may be */ /* permuted in accordance with t. */ /* iheap is an integer variable specifying the task. */ /* On entry iheap should be set as follows: */ /* iheap .eq. 0 if t(1) to t(n) is not in the form of a heap, */ /* iheap .ne. 0 if otherwise. */ /* On exit iheap is unchanged. */ /* References: */ /* Algorithm 232 of CACM (J. W. J. Williams): HEAPSORT. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --iorder; --t; /* Function Body */ if (*iheap == 0) { /* Rearrange the elements t(1) to t(n) to form a heap. */ i__1 = *n; for (k = 2; k <= i__1; ++k) { ddum = t[k]; indxin = iorder[k]; /* Add ddum to the heap. */ i__ = k; L10: if (i__ > 1) { j = i__ / 2; if (ddum < t[j]) { t[i__] = t[j]; iorder[i__] = iorder[j]; i__ = j; goto L10; } } t[i__] = ddum; iorder[i__] = indxin; /* L20: */ } } /* Assign to 'out' the value of t(1), the least member of the heap, */ /* and rearrange the remaining members to form a heap as */ /* elements 1 to n-1 of t. */ if (*n > 1) { i__ = 1; out = t[1]; indxou = iorder[1]; ddum = t[*n]; indxin = iorder[*n]; /* Restore the heap */ L30: j = i__ + i__; if (j <= *n - 1) { if (t[j + 1] < t[j]) { ++j; } if (t[j] < ddum) { t[i__] = t[j]; iorder[i__] = iorder[j]; i__ = j; goto L30; } } t[i__] = ddum; iorder[i__] = indxin; /* Put the least member in t(n). */ t[*n] = out; iorder[*n] = indxou; } return 0; } /* hpsolb_ */ /* Subroutine */ int lnsrlb_(int *n,double * l,double * u,int * nbd,double * x,double * f,double * fold,double * gd,double * gdold,double * g,double * d__,double * r__, double *t,double * z__,double * stp,double * dnorm,double * dtd,double * xstep,double * stpmx,int * iter,int * ifun,int * iback,int * nfgv,int * info, char *task,logical * boxed,logical * cnstnd,char * csave,int * isave,double * dsave,ftnlen task_len,ftnlen csave_len)/* integer *n; doublereal *l, *u; integer *nbd; doublereal *x, *f, *fold, *gd, *gdold, *g, *d__, *r__, *t, *z__, *stp, *dnorm, *dtd, *xstep, *stpmx; integer *iter, *ifun, *iback, *nfgv, *info; char *task; logical *boxed, *cnstnd; char *csave; integer *isave; doublereal *dsave; ftnlen task_len; ftnlen csave_len;*/ { /* System generated locals */ integer i__1; doublereal d__1; /* Builtin functions */ // integer s_cmp(); // double sqrt(); // /* Subroutine */ int s_copy(); /* Local variables */ // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer i__; // extern /* Subroutine */ int dcopy_(); int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); doublereal a1, a2; // extern /* Subroutine */ int dcsrch_(); int dcsrch_(doublereal *f, doublereal *g, doublereal *stp, doublereal *ftol, doublereal *gtol, doublereal *xtol, doublereal *stpmin, doublereal *stpmax, char *task, integer *isave, doublereal *dsave, ftnlen task_len); /* Subroutine lnsrlb */ /* This subroutine calls subroutine dcsrch from the Minpack2 library */ /* to perform the line search. Subroutine dscrch is safeguarded so */ /* that all trial points lie within the feasible region. */ /* Subprograms called: */ /* Minpack2 Library ... dcsrch. */ /* Linpack ... dtrsl, ddot. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --z__; --t; --r__; --d__; --g; --x; --nbd; --u; --l; --isave; --dsave; /* Function Body */ if (strncmp(task, "FG_LN", 5)==0) { goto L556; } *dtd = ddot_(n, &d__[1], &c__1, &d__[1], &c__1); *dnorm = sqrt(*dtd); /* Determine the maximum step length. */ *stpmx = 1e10; if (*cnstnd) { if (*iter == 0) { *stpmx = 1.; } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { a1 = d__[i__]; if (nbd[i__] != 0) { if (a1 < 0. && nbd[i__] <= 2) { a2 = l[i__] - x[i__]; if (a2 >= 0.) { *stpmx = 0.; } else if (a1 * *stpmx < a2) { *stpmx = a2 / a1; } } else if (a1 > 0. && nbd[i__] >= 2) { a2 = u[i__] - x[i__]; if (a2 <= 0.) { *stpmx = 0.; } else if (a1 * *stpmx > a2) { *stpmx = a2 / a1; } } } /* L43: */ } } } if (*iter == 0 && ! (*boxed)) { /* Computing MIN */ d__1 = 1. / *dnorm; *stp = min(d__1,*stpmx); } else { *stp = 1.; } dcopy_(n, &x[1], &c__1, &t[1], &c__1); dcopy_(n, &g[1], &c__1, &r__[1], &c__1); *fold = *f; *ifun = 0; *iback = 0; my_strcpy(csave, "START"); // s_copy(csave, "START", (ftnlen)60, (ftnlen)5); L556: *gd = ddot_(n, &g[1], &c__1, &d__[1], &c__1); if (*ifun == 0) { *gdold = *gd; if (*gd >= 0.) { /* the directional derivative >=0. */ /* Line search is impossible. */ *info = -4; return 0; } } dcsrch_(f, gd, stp, &c_b275, &c_b276, &c_b277, &c_b9, stpmx, csave, & isave[1], &dsave[1], (ftnlen)60); *xstep = *stp * *dnorm; if (strncmp(csave, "CONV", 4) != 0 && strncmp(csave, "WARN", 4)!=0) { my_strcpy(task, "FG_LNSRCH"); ++(*ifun); ++(*nfgv); *iback = *ifun - 1; if (*stp == 1.) { dcopy_(n, &z__[1], &c__1, &x[1], &c__1); } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { x[i__] = *stp * d__[i__] + t[i__]; /* L41: */ } } } else { my_strcpy(task, "NEW_X"); } return 0; } /* lnsrlb_ */ /* Subroutine */ int matupd_(int *n,int * m,double * ws,double * wy,double * sy,double * ss,double * d__,double * r__,int * itail,int * iupdat, int *col,int * head,double * theta,double *rr,double * dr,double * stp,double * dtd)/* integer *n, *m; doublereal *ws, *wy, *sy, *ss, *d__, *r__; integer *itail, *iupdat, *col, *head; doublereal *theta, *rr, *dr, *stp, *dtd;*/ { /* System generated locals */ integer ws_dim1, ws_offset, wy_dim1, wy_offset, sy_dim1, sy_offset, ss_dim1, ss_offset, i__1, i__2; /* Local variables */ // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer j; // extern /* Subroutine */ int dcopy_(); int dcopy_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer pointr; /* Subroutine matupd */ /* This subroutine updates matrices WS and WY, and forms the */ /* middle matrix in B. */ /* Subprograms called: */ /* Linpack ... dcopy, ddot. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Set pointers for matrices WS and WY. */ /* Parameter adjustments */ --r__; --d__; ss_dim1 = *m; ss_offset = 1 + ss_dim1 * 1; ss -= ss_offset; sy_dim1 = *m; sy_offset = 1 + sy_dim1 * 1; sy -= sy_offset; wy_dim1 = *n; wy_offset = 1 + wy_dim1 * 1; wy -= wy_offset; ws_dim1 = *n; ws_offset = 1 + ws_dim1 * 1; ws -= ws_offset; /* Function Body */ if (*iupdat <= *m) { *col = *iupdat; *itail = (*head + *iupdat - 2) % *m + 1; } else { *itail = *itail % *m + 1; *head = *head % *m + 1; } /* Update matrices WS and WY. */ dcopy_(n, &d__[1], &c__1, &ws[*itail * ws_dim1 + 1], &c__1); dcopy_(n, &r__[1], &c__1, &wy[*itail * wy_dim1 + 1], &c__1); /* Set theta=yy/ys. */ *theta = *rr / *dr; /* Form the middle matrix in B. */ /* update the upper triangle of SS, */ /* and the lower triangle of SY: */ if (*iupdat > *m) { /* move old information */ i__1 = *col - 1; for (j = 1; j <= i__1; ++j) { dcopy_(&j, &ss[(j + 1) * ss_dim1 + 2], &c__1, &ss[j * ss_dim1 + 1] , &c__1); i__2 = *col - j; dcopy_(&i__2, &sy[j + 1 + (j + 1) * sy_dim1], &c__1, &sy[j + j * sy_dim1], &c__1); /* L50: */ } } /* add new information: the last row of SY */ /* and the last column of SS: */ pointr = *head; i__1 = *col - 1; for (j = 1; j <= i__1; ++j) { sy[*col + j * sy_dim1] = ddot_(n, &d__[1], &c__1, &wy[pointr * wy_dim1 + 1], &c__1); ss[j + *col * ss_dim1] = ddot_(n, &ws[pointr * ws_dim1 + 1], &c__1, & d__[1], &c__1); pointr = pointr % *m + 1; /* L51: */ } if (*stp == 1.) { ss[*col + *col * ss_dim1] = *dtd; } else { ss[*col + *col * ss_dim1] = *stp * *stp * *dtd; } sy[*col + *col * sy_dim1] = *dr; return 0; } /* matupd_ */ /* Subroutine */ int prn1lb_(int *n,int * m,double * l,double * u,double * x,int * iprint,int * itfile,double * epsmch)/* integer *n, *m; doublereal *l, *u, *x; integer *iprint, *itfile; doublereal *epsmch;*/ { /* Format strings */ /* char fmt_7001[] = "(\002RUNNING THE L-BFGS-B CODE\002,/,/,\002 \ * * *\002,/,/,\002Machine precision =\002,1p,d10.3)"; char fmt_2001[] = "(\002RUNNING THE L-BFGS-B CODE\002,/,/,\002it \ = iteration number\002,/,\002nf = number of function evaluations\002,/,\ \002nint = number of segments explored during the Cauchy search\002,/,\002n\ act = number of active bounds at the generalized Cauchy point\002,/,\002sub\ = manner in which the subspace minimization terminated:\002,/,\002 \ con = converged, bnd = a bound was reached\002,/,\002itls = number of iter\ ations performed in the line search\002,/,\002stepl = step length used\002,/,\ \002tstep = norm of the displacement (total step)\002,/,\002projg = norm of \ the projected gradient\002,/,\002f = function value\002,/,/,\002 \ * * *\002,/,/,\002Machine precision =\002,1p,d10.3)"; char fmt_9001[] = "(/,3x,\002it\002,3x,\002nf\002,2x,\002nint\002\ ,2x,\002nact\002,2x,\002sub\002,2x,\002itls\002,2x,\002stepl\002,4x,\002tstep\ \002,5x,\002projg\002,8x,\002f\002)"; char fmt_1004[] = "(/,a4,1p,6(1x,d11.4),/,(4x,1p,6(1x,d11.4)))";*/ /* System generated locals */ // integer i__1; /* Builtin functions */ integer s_wsfe(), do_fio(), e_wsfe(), s_wsle(), do_lio(), e_wsle(); /* Local variables */ // integer i__; /* Fortran I/O blocks */ /* Subroutine prn1lb */ /* This subroutine prints the input data, initial point, upper and */ /* lower bounds of each variable, machine precision, as well as */ /* the headings of the output. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --x; --u; --l; /* Function Body */ if (*iprint >= 0) { printf("RUNNING THE L-BFGS-B CODE\n\n\t* * *\n\nMachine precision=%e\n", *epsmch); printf("N = %i M = %i\n", *n, *m); } return 0; } /* prn1lb_ */ /* Subroutine */ int prn2lb_(int *n,double * x,double * f,double * g,int * iprint,int * itfile,int * iter,int * nfgv,int * nact, double *sbgnrm,int* nint, char *word,int * iword, int *iback,double * stp,double * xstep,ftnlen word_len)/* integer *n; doublereal *x, *f, *g; integer *iprint, *itfile, *iter, *nfgv, *nact; doublereal *sbgnrm; integer *nint; char *word; integer *iword, *iback; doublereal *stp, *xstep; ftnlen word_len;*/ { /* Format strings */ /* char fmt_2001[] = "(/,\002At iterate\002,i5,4x,\002f= \002,1p,d12\ .5,4x,\002|proj g|= \002,1p,d12.5)"; char fmt_1004[] = "(/,a4,1p,6(1x,d11.4),/,(4x,1p,6(1x,d11.4)))"; char fmt_3001[] = "(2(1x,i4),2(1x,i5),2x,a3,1x,i4,1p,2(2x,d7.1),1\ p,2(1x,d10.3))";*/ /* System generated locals */ integer i__1; /* Builtin functions */ // /* Subroutine */ int s_copy(); integer s_wsle(), do_lio(), e_wsle(), s_wsfe(), do_fio(), e_wsfe(); /* Local variables */ integer imod, i__; /* Fortran I/O blocks */ /* Subroutine prn2lb */ /* This subroutine prints out new information after a successful */ /* line search. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* 'word' records the status of subspace solutions. */ /* Parameter adjustments */ --g; --x; /* Function Body */ if (*iword == 0) { /* the subspace minimization converged. */ my_strcpy(word, "con"); // s_copy(word, "con", (ftnlen)3, (ftnlen)3); } else if (*iword == 1) { /* the subspace minimization stopped at a bound. */ my_strcpy(word, "bnd"); // s_copy(word, "bnd", (ftnlen)3, (ftnlen)3); } else if (*iword == 5) { /* the truncated Newton step has been used. */ my_strcpy(word, "TNT"); // s_copy(word, "TNT", (ftnlen)3, (ftnlen)3); } else { my_strcpy(word, " } if (*iprint >= 99) { printf("LINE SEARCH %i times; norm of step = %e\n", *iback, *xstep); printf("At iterate %i f=%e |proj g| = %e\n", *iter, *f, *sbgnrm); if (*iprint > 100) { printf("\nX="); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) printf("\t%e", x[i__]); printf("\n"); printf("\nG="); i__1 = *n; for (i__1 = 1; i__ <= i__1; ++i__) printf("\t%e", g[i__]); printf("\n"); } } else if (*iprint > 0) { imod = *iter % *iprint; if (imod == 0) { } } if (*iprint >= 1) { } return 0; } /* prn2lb_ */ /* Subroutine */ int prn3lb_(int *n,double * x,double * f,char * task,int * iprint,integer * info,integer * itfile,integer * iter,integer * nfgv, integer *nintol,integer * nskip,integer * nact,doublereal * sbgnrm,doublereal * time,int * nint,char * word, int *iback,double * stp,double * xstep,int * k, double *cachyt, double *sbtime, double *lnscht, ftnlen task_len,ftnlen word_len)/* integer *n; doublereal *x, *f; char *task; integer *iprint, *info, *itfile, *iter, *nfgv, *nintol, *nskip, *nact; doublereal *sbgnrm, *time; integer *nint; char *word; integer *iback; doublereal *stp, *xstep; integer *k; doublereal *cachyt, *sbtime, *lnscht; ftnlen task_len; ftnlen word_len;*/ { /* Format strings */ /* char fmt_3003[] = "(/,\002 * * *\002,/,/,\002Tit = to\ tal number of iterations\002,/,\002Tnf = total number of function evaluati\ ons\002,/,\002Tnint = total number of segments explored during\002,\002 Cauc\ hy searches\002,/,\002Skip = number of BFGS updates skipped\002,/,\002Nact \ = number of active bounds at final generalized\002,\002 Cauchy point\002,/\ ,\002Projg = norm of the final projected gradient\002,/,\002F = final fu\ nction value\002,/,/,\002 * * *\002)"; char fmt_3004[] = "(/,3x,\002N\002,3x,\002Tit\002,2x,\002Tnf\002,\ 2x,\002Tnint\002,2x,\002Skip\002,2x,\002Nact\002,5x,\002Projg\002,8x,\002\ F\002)"; char fmt_3005[] = "(i5,2(1x,i4),(1x,i6),(2x,i4),(1x,i5),1p,2(2x,d\ 10.3))"; char fmt_1004[] = "(/,a4,1p,6(1x,d11.4),/,(4x,1p,6(1x,d11.4)))"; char fmt_3009[] = "(/,a60)"; char fmt_9011[] = "(/,\002 Matrix in 1st Cholesky factorization i\ n formk is not Pos. Def.\002)"; char fmt_9012[] = "(/,\002 Matrix in 2st Cholesky factorization i\ n formk is not Pos. Def.\002)"; char fmt_9013[] = "(/,\002 Matrix in the Cholesky factorization i\ n formt is not Pos. Def.\002)"; char fmt_9014[] = "(/,\002 Derivative >= 0, backtracking line sea\ rch impossible.\002,/,\002 Previous x, f and g restored.\002,/,\002 Possib\ le causes: 1 error in function or gradient evaluation;\002,/,\002 \ 2 rounding errors dominate computation.\002)"; char fmt_9015[] = "(/,\002 Warning: more than 10 function and gr\ adient\002,/,\002 evaluations in the last line search. Termination\002,/\ ,\002 may possibly be caused by a bad search direction.\002)"; char fmt_9018[] = "(/,\002 The triangular system is singular.\002)" ; char fmt_9019[] = "(/,\002 Line search cannot locate an adequate \ point after 20 function\002,/,\002 and gradient evaluations. Previous x, f\ and g restored.\002,/,\002 Possible causes: 1 error in function or gradient\ evaluation;\002,/,\002 2 rounding error dominate computati\ on.\002)"; char fmt_3007[] = "(/,\002 Cauchy time\002,1p,e10.\ 3,\002 seconds.\002,/\002 Subspace minimization time\002,1p,e10.3,\002 secon\ ds.\002,/\002 Line search time\002,1p,e10.3,\002 seconds.\002)"; char fmt_3008[] = "(/,\002 Total User time\002,1p,e10.3,\002 seco\ nds.\002,/)"; char fmt_3002[] = "(2(1x,i4),2(1x,i5),2x,a3,1x,i4,1p,2(2x,d7.1),6\ x,\002-\002,10x,\002-\002)";*/ /* System generated locals */ integer i__1; /* Builtin functions */ // integer s_cmp(), s_wsfe(), e_wsfe(), do_fio(), s_wsle(), do_lio(), e_wsle(); /* Local variables */ integer i__; /* Fortran I/O blocks */ /* Subroutine prn3lb */ /* This subroutine prints out information when either a built-in */ /* convergence test is satisfied or when an error message is */ /* generated. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --x; /* Function Body */ if (strncmp(task, "ERROR", 5) == 0) { goto L999; } if (*iprint >= 0) { printf("\n\t* * *\n\nTit = total number of iterations\nTnf = total number of function evaluations\nTnint = total number of segments explored during Cauchy searches\nSkip = number of BFGS updates skipped\nNact = number of active bounds at final generalized Cuachy point\nProjg = norm of the final projected gradient\nF = final function value\n\n\t* * *\n"); printf("N\tTit\tTnf\tTnint\tSkip\tNact\tProjg\tF\n"); printf("%i\t%i\t%i\t%i\t%i\t%i\t%e\t%e\n", *n, *iter, *nfgv, *nintol, *nskip, *nact, *sbgnrm, *f); if (*iprint >= 100) { printf("X = "); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) printf("%e", x[i__]); printf("\n"); } if (*iprint >= 1) { printf(" F = %f\n", *f); } } L999: if (*iprint >= 0) { printf("%s\n", task); if (*info != 0) { if (*info == -1) { printf("Matrix in 1st Cholesky factorization in formk is not Pos. Def.\n"); } if (*info == -2) { printf(" Matrix in 2st Cholesky factorization in formk is not Pos. Def.\n"); } if (*info == -3) { printf("Matrix in the Cholesky factorization in formt is not Pos. Def.\n"); } if (*info == -4) { printf("Derivative >= 0, backtracking line search impossible.\n, Previous x, f and g restored.\nPossible causes: 1 error in function or gradient evaluation;\n2 rounding errors dominate computation.\n"); } if (*info == -5) { printf("Warning: more than 10 function and gradient evaluations in the last line search. Termination may possibly be caused by a bad search direction.\n"); } if (*info == -6) { printf(" Input nbd(%i) is invalid\n", *k); } if (*info == -7) { printf(" l(%i) > u(%i). No feasible solutions.\n", *k, *k); } if (*info == -8) { printf("The triangular system is singular.\n"); } if (*info == -9) { printf("Line search cannot locate an adequate point after 20 function and gradient evaluations. Previous x, f and g restored. Possible causes: 1 error in function or gradient evaluation; 2 rounding error dominate computation.\n"); } } if (*iprint >= 1) { printf("Cauchy time %.0f seconds.\nSubspace minimization time %.0f seconds.\nLine search time %.0f seconds.\n", *cachyt, *sbtime, *lnscht); } printf("Total User time %.0f seconds.\n", *time); } /* L3006: */ return 0; } /* prn3lb_ */ /* Subroutine */ int projgr_(int *n,double * l,double * u,int * nbd,double * x,double * g,double * sbgnrm)/* integer *n; doublereal *l, *u; integer *nbd; doublereal *x, *g, *sbgnrm;*/ { /* System generated locals */ integer i__1; doublereal d__1, d__2; /* Local variables */ integer i__; doublereal gi; /* Subroutine projgr */ /* This subroutine computes the infinity norm of the projected */ /* gradient. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --g; --x; --nbd; --u; --l; /* Function Body */ *sbgnrm = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { gi = g[i__]; if (nbd[i__] != 0) { if (gi < 0.) { if (nbd[i__] >= 2) { /* Computing MAX */ d__1 = x[i__] - u[i__]; gi = max(d__1,gi); } } else { if (nbd[i__] <= 2) { /* Computing MIN */ d__1 = x[i__] - l[i__]; gi = min(d__1,gi); } } } /* Computing MAX */ d__1 = *sbgnrm, d__2 = abs(gi); *sbgnrm = max(d__1,d__2); /* L15: */ } return 0; } /* projgr_ */ /* Subroutine */ int subsm_(int *n,int * m,int * nsub,int * ind,double * l,double * u,int * nbd,double * x,double * d__,double * ws,double * wy,double * theta, int *col,int * head,int * iword,double * wv,double * wn,int * iprint,int * info)/* integer *n, *m, *nsub, *ind; doublereal *l, *u; integer *nbd; doublereal *x, *d__, *ws, *wy, *theta; integer *col, *head, *iword; doublereal *wv, *wn; integer *iprint, *info;*/ { /* Format strings */ /* System generated locals */ integer ws_dim1, ws_offset, wy_dim1, wy_offset, wn_dim1, wn_offset, i__1, i__2; /* Builtin functions */ integer s_wsfe(), e_wsfe(), do_fio(), s_wsle(), do_lio(), e_wsle(); /* Local variables */ doublereal temp1, temp2; integer i__, j, k; doublereal alpha; // extern /* Subroutine */ int dtrsl_(); int dtrsl_(doublereal *t, integer *ldt, integer *n, doublereal *b, integer *job, integer *info); integer m2; doublereal dk; integer js, jy, pointr, ibd, col2; /* Fortran I/O blocks */ /* Subroutine subsm */ /* Given xcp, l, u, r, an index set that specifies */ /* the active set at xcp, and an l-BFGS matrix B */ /* (in terms of WY, WS, SY, WT, head, col, and theta), */ /* this subroutine computes an approximate solution */ /* of the subspace problem */ /* (P) min Q(x) = r'(x-xcp) + 1/2 (x-xcp)' B (x-xcp) */ /* subject to l<=x<=u */ /* x_i=xcp_i for all i in A(xcp) */ /* along the subspace unconstrained Newton direction */ /* d = -(Z'BZ)^(-1) r. */ /* The formula for the Newton direction, given the L-BFGS matrix */ /* and the Sherman-Morrison formula, is */ /* d = (1/theta)r + (1/theta*2) Z'WK^(-1)W'Z r. */ /* where */ /* K = [-D -Y'ZZ'Y/theta L_a'-R_z' ] */ /* [L_a -R_z theta*S'AA'S ] */ /* Note that this procedure for computing d differs */ /* from that described in [1]. One can show that the matrix K is */ /* equal to the matrix M^[-1]N in that paper. */ /* n is an integer variable. */ /* On entry n is the dimension of the problem. */ /* On exit n is unchanged. */ /* m is an integer variable. */ /* On entry m is the maximum number of variable metric corrections */ /* used to define the limited memory matrix. */ /* On exit m is unchanged. */ /* nsub is an integer variable. */ /* On entry nsub is the number of free variables. */ /* On exit nsub is unchanged. */ /* ind is an integer array of dimension nsub. */ /* On entry ind specifies the coordinate indices of free variables. */ /* On exit ind is unchanged. */ /* l is a double precision array of dimension n. */ /* On entry l is the lower bound of x. */ /* On exit l is unchanged. */ /* u is a double precision array of dimension n. */ /* On entry u is the upper bound of x. */ /* On exit u is unchanged. */ /* nbd is a integer array of dimension n. */ /* On entry nbd represents the type of bounds imposed on the */ /* variables, and must be specified as follows: */ /* nbd(i)=0 if x(i) is unbounded, */ /* 1 if x(i) has only a lower bound, */ /* 2 if x(i) has both lower and upper bounds, and */ /* 3 if x(i) has only an upper bound. */ /* On exit nbd is unchanged. */ /* x is a double precision array of dimension n. */ /* On entry x specifies the Cauchy point xcp. */ /* On exit x(i) is the minimizer of Q over the subspace of */ /* free variables. */ /* d is a double precision array of dimension n. */ /* On entry d is the reduced gradient of Q at xcp. */ /* On exit d is the Newton direction of Q. */ /* ws and wy are double precision arrays; */ /* theta is a double precision variable; */ /* col is an integer variable; */ /* head is an integer variable. */ /* On entry they store the information defining the */ /* limited memory BFGS matrix: */ /* ws(n,m) stores S, a set of s-vectors; */ /* wy(n,m) stores Y, a set of y-vectors; */ /* theta is the scaling factor specifying B_0 = theta I; */ /* col is the number of variable metric corrections stored; */ /* head is the location of the 1st s- (or y-) vector in S (or Y). */ /* On exit they are unchanged. */ /* iword is an integer variable. */ /* On entry iword is unspecified. */ /* On exit iword specifies the status of the subspace solution. */ /* iword = 0 if the solution is in the box, */ /* 1 if some bound is encountered. */ /* wv is a double precision working array of dimension 2m. */ /* wn is a double precision array of dimension 2m x 2m. */ /* On entry the upper triangle of wn stores the LEL^T factorization */ /* of the indefinite matrix */ /* K = [-D -Y'ZZ'Y/theta L_a'-R_z' ] */ /* [L_a -R_z theta*S'AA'S ] */ /* where E = [-I 0] */ /* [ 0 I] */ /* On exit wn is unchanged. */ /* iprint is an INTEGER variable that must be set by the user. */ /* It controls the frequency and type of output generated: */ /* iprint<0 no output is generated; */ /* iprint=0 print only one line at the last iteration; */ /* 0<iprint<99 print also f and |proj g| every iprint iterations; */ /* iprint=99 print details of every iteration except n-vectors; */ /* iprint=100 print also the changes of active set and final x; */ /* iprint>100 print details of every iteration including x and g; */ /* When iprint > 0, the file iterate.dat will be created to */ /* summarize the iteration. */ /* info is an integer variable. */ /* On entry info is unspecified. */ /* On exit info = 0 for normal return, */ /* = nonzero for abnormal return */ /* when the matrix K is ill-conditioned. */ /* Subprograms called: */ /* Linpack dtrsl. */ /* References: */ /* [1] R. H. Byrd, P. Lu, J. Nocedal and C. Zhu, ``A limited */ /* memory algorithm for bound constrained optimization'', */ /* SIAM J. Scientific Computing 16 (1995), no. 5, pp. 1190--1208. */ /* NEOS, November 1994. (Latest revision June 1996.) */ /* Optimization Technology Center. */ /* Argonne National Laboratory and Northwestern University. */ /* Written by */ /* Ciyou Zhu */ /* in collaboration with R.H. Byrd, P. Lu-Chen and J. Nocedal. */ /* Parameter adjustments */ --d__; --x; --nbd; --u; --l; wn_dim1 = 2 * *m; wn_offset = 1 + wn_dim1 * 1; wn -= wn_offset; --wv; wy_dim1 = *n; wy_offset = 1 + wy_dim1 * 1; wy -= wy_offset; ws_dim1 = *n; ws_offset = 1 + ws_dim1 * 1; ws -= ws_offset; --ind; /* Function Body */ if (*nsub <= 0) { return 0; } if (*iprint >= 99) { printf(" } /* Compute wv = W'Zd. */ pointr = *head; i__1 = *col; for (i__ = 1; i__ <= i__1; ++i__) { temp1 = 0.; temp2 = 0.; i__2 = *nsub; for (j = 1; j <= i__2; ++j) { k = ind[j]; temp1 += wy[k + pointr * wy_dim1] * d__[j]; temp2 += ws[k + pointr * ws_dim1] * d__[j]; /* L10: */ } wv[i__] = temp1; wv[*col + i__] = *theta * temp2; pointr = pointr % *m + 1; /* L20: */ } /* Compute wv:=K^(-1)wv. */ m2 = *m << 1; col2 = *col << 1; dtrsl_(&wn[wn_offset], &m2, &col2, &wv[1], &c__11, info); if (*info != 0) { return 0; } i__1 = *col; for (i__ = 1; i__ <= i__1; ++i__) { wv[i__] = -wv[i__]; /* L25: */ } dtrsl_(&wn[wn_offset], &m2, &col2, &wv[1], &c__1, info); if (*info != 0) { return 0; } /* Compute d = (1/theta)d + (1/theta**2)Z'W wv. */ pointr = *head; i__1 = *col; for (jy = 1; jy <= i__1; ++jy) { js = *col + jy; i__2 = *nsub; for (i__ = 1; i__ <= i__2; ++i__) { k = ind[i__]; d__[i__] = d__[i__] + wy[k + pointr * wy_dim1] * wv[jy] / *theta + ws[k + pointr * ws_dim1] * wv[js]; /* L30: */ } pointr = pointr % *m + 1; /* L40: */ } i__1 = *nsub; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] /= *theta; /* L50: */ } /* Backtrack to the feasible region. */ alpha = 1.; temp1 = alpha; i__1 = *nsub; for (i__ = 1; i__ <= i__1; ++i__) { k = ind[i__]; dk = d__[i__]; if (nbd[k] != 0) { if (dk < 0. && nbd[k] <= 2) { temp2 = l[k] - x[k]; if (temp2 >= 0.) { temp1 = 0.; } else if (dk * alpha < temp2) { temp1 = temp2 / dk; } } else if (dk > 0. && nbd[k] >= 2) { temp2 = u[k] - x[k]; if (temp2 <= 0.) { temp1 = 0.; } else if (dk * alpha > temp2) { temp1 = temp2 / dk; } } if (temp1 < alpha) { alpha = temp1; ibd = i__; } } /* L60: */ } if (alpha < 1.) { dk = d__[ibd]; k = ind[ibd]; if (dk > 0.) { x[k] = u[k]; d__[ibd] = 0.; } else if (dk < 0.) { x[k] = l[k]; d__[ibd] = 0.; } } i__1 = *nsub; for (i__ = 1; i__ <= i__1; ++i__) { k = ind[i__]; x[k] += alpha * d__[i__]; /* L70: */ } if (*iprint >= 99) { if (alpha < 1.) { printf("ALPHA = %e backtrack to the BOX\n", alpha); } else { printf("SM solution inside the box\n"); } if (*iprint > 100) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) printf("\t%e", x[i__]); printf("\n"); } } if (alpha < 1.) { *iword = 1; } else { *iword = 0; } if (*iprint >= 99) { printf(" } return 0; } /* subsm_ */ /* Subroutine */ int dcsrch_(doublereal *f,doublereal * g,doublereal * stp,doublereal * ftol,doublereal * gtol, doublereal *xtol,doublereal * stpmin, doublereal *stpmax, char *task,int * isave,double * dsave,ftnlen task_len)/* doublereal *f, *g, *stp, *ftol, *gtol, *xtol, *stpmin, *stpmax; char *task; integer *isave; doublereal *dsave; ftnlen task_len;*/ { /* System generated locals */ doublereal d__1; /* Builtin functions */ // integer s_cmp(); // /* Subroutine */ int s_copy(); /* Local variables */ integer stage; doublereal finit, ginit, width, ftest, gtest, stmin, stmax, width1, fm, gm, fx, fy, gx, gy; logical brackt; // extern /* Subroutine */ int dcstep_(); int dcstep_(doublereal *stx, doublereal *fx, doublereal *dx, doublereal *sty, doublereal *fy, doublereal *dy, doublereal *stp, doublereal *fp, doublereal *dp, logical *brackt, doublereal *stpmin, doublereal *stpmax); doublereal fxm, fym, gxm, gym, stx, sty; /* Subroutine dcsrch */ /* This subroutine finds a step that satisfies a sufficient */ /* decrease condition and a curvature condition. */ /* Each call of the subroutine updates an interval with */ /* endpoints stx and sty. The interval is initially chosen */ /* so that it contains a minimizer of the modified function */ /* psi(stp) = f(stp) - f(0) - ftol*stp*f'(0). */ /* If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the */ /* interval is chosen so that it contains a minimizer of f. */ /* The algorithm is designed to find a step that satisfies */ /* the sufficient decrease condition */ /* f(stp) <= f(0) + ftol*stp*f'(0), */ /* and the curvature condition */ /* abs(f'(stp)) <= gtol*abs(f'(0)). */ /* If ftol is less than gtol and if, for example, the function */ /* is bounded below, then there is always a step which satisfies */ /* both conditions. */ /* If no step can be found that satisfies both conditions, then */ /* the algorithm stops with a warning. In this case stp only */ /* satisfies the sufficient decrease condition. */ /* A typical invocation of dcsrch has the following outline: */ /* task = 'START' */ /* 10 continue */ /* call dcsrch( ... ) */ /* if (task .eq. 'FG') then */ /* Evaluate the function and the gradient at stp */ /* goto 10 */ /* end if */ /* NOTE: The user must no alter work arrays between calls. */ /* The subroutine statement is */ /* subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax, */ /* task,isave,dsave) */ /* where */ /* f is a double precision variable. */ /* On initial entry f is the value of the function at 0. */ /* On subsequent entries f is the value of the */ /* function at stp. */ /* On exit f is the value of the function at stp. */ /* g is a double precision variable. */ /* On initial entry g is the derivative of the function at 0. */ /* On subsequent entries g is the derivative of the */ /* function at stp. */ /* On exit g is the derivative of the function at stp. */ /* stp is a double precision variable. */ /* On entry stp is the current estimate of a satisfactory */ /* step. On initial entry, a positive initial estimate */ /* must be provided. */ /* On exit stp is the current estimate of a satisfactory step */ /* if task = 'FG'. If task = 'CONV' then stp satisfies */ /* the sufficient decrease and curvature condition. */ /* ftol is a double precision variable. */ /* On entry ftol specifies a nonnegative tolerance for the */ /* sufficient decrease condition. */ /* On exit ftol is unchanged. */ /* gtol is a double precision variable. */ /* On entry gtol specifies a nonnegative tolerance for the */ /* curvature condition. */ /* On exit gtol is unchanged. */ /* xtol is a double precision variable. */ /* On entry xtol specifies a nonnegative relative tolerance */ /* for an acceptable step. The subroutine exits with a */ /* warning if the relative difference between sty and stx */ /* is less than xtol. */ /* On exit xtol is unchanged. */ /* stpmin is a double precision variable. */ /* On entry stpmin is a nonnegative lower bound for the step. */ /* On exit stpmin is unchanged. */ /* stpmax is a double precision variable. */ /* On entry stpmax is a nonnegative upper bound for the step. */ /* On exit stpmax is unchanged. */ /* task is a character variable of length at least 60. */ /* On initial entry task must be set to 'START'. */ /* On exit task indicates the required action: */ /* If task(1:2) = 'FG' then evaluate the function and */ /* derivative at stp and call dcsrch again. */ /* If task(1:4) = 'CONV' then the search is successful. */ /* If task(1:4) = 'WARN' then the subroutine is not able */ /* to satisfy the convergence conditions. The exit value of */ /* stp contains the best point found during the search. */ /* If task(1:5) = 'ERROR' then there is an error in the */ /* input arguments. */ /* On exit with convergence, a warning or an error, the */ /* variable task contains additional information. */ /* isave is an integer work array of dimension 2. */ /* dsave is a double precision work array of dimension 13. */ /* Subprograms called */ /* MINPACK-2 ... dcstep */ /* MINPACK-1 Project. June 1983. */ /* Argonne National Laboratory. */ /* Jorge J. More' and David J. Thuente. */ /* MINPACK-2 Project. October 1993. */ /* Argonne National Laboratory and University of Minnesota. */ /* Brett M. Averick, Richard G. Carter, and Jorge J. More'. */ /* Initialization block. */ /* Parameter adjustments */ --dsave; --isave; /* Function Body */ if (strncmp(task, "START", 5) == 0) { /* Check the input arguments for errors. */ if (*stp < *stpmin) { my_strcpy(task, "ERROR: STP .LT. STPMIN"); } if (*stp > *stpmax) { my_strcpy(task, "ERROR: STP .GT. STPMAX"); } if (*g >= 0.) { my_strcpy(task, "ERROR: INITIAL G .GE. ZERO"); } if (*ftol < 0.) { my_strcpy(task, "ERROR: FTOL .LT. ZERO"); } if (*gtol < 0.) { my_strcpy(task, "ERROR: GTOL .LT. ZERO"); } if (*xtol < 0.) { my_strcpy(task, "ERROR: XTOL .LT. ZERO"); } if (*stpmin < 0.) { my_strcpy(task, "ERROR: STPMIN .LT. ZERO"); } if (*stpmax < *stpmin) { my_strcpy(task, "ERROR: STPMAX .LT. STPMIN"); } /* Exit if there are errors on input. */ if (strncmp(task, "ERROR", 5) == 0) { return 0; } /* Initialize local variables. */ brackt = FALSE_; stage = 1; finit = *f; ginit = *g; gtest = *ftol * ginit; width = *stpmax - *stpmin; width1 = width / .5; /* The variables stx, fx, gx contain the values of the step, */ /* function, and derivative at the best step. */ /* The variables sty, fy, gy contain the value of the step, */ /* function, and derivative at sty. */ /* The variables stp, f, g contain the values of the step, */ /* function, and derivative at stp. */ stx = 0.; fx = finit; gx = ginit; sty = 0.; fy = finit; gy = ginit; stmin = 0.; stmax = *stp + *stp * 4.; task[0]='F'; task[1]='G'; goto L1000; } else { /* Restore local variables. */ if (isave[1] == 1) { brackt = TRUE_; } else { brackt = FALSE_; } stage = isave[2]; ginit = dsave[1]; gtest = dsave[2]; gx = dsave[3]; gy = dsave[4]; finit = dsave[5]; fx = dsave[6]; fy = dsave[7]; stx = dsave[8]; sty = dsave[9]; stmin = dsave[10]; stmax = dsave[11]; width = dsave[12]; width1 = dsave[13]; } /* If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the */ /* algorithm enters the second stage. */ ftest = finit + *stp * gtest; if (stage == 1 && *f <= ftest && *g >= 0.) { stage = 2; } /* Test for warnings. */ if (brackt && (*stp <= stmin || *stp >= stmax)) { my_strcpy(task, "WARNING: ROUNDING ERRORS PREVENT PROGRESS"); } if (brackt && stmax - stmin <= *xtol * stmax) { my_strcpy(task, "WARNING: XTOL TEST SATISFIED"); } if (*stp == *stpmax && *f <= ftest && *g <= gtest) { my_strcpy(task, "WARNING: STP = STPMAX"); } if (*stp == *stpmin && (*f > ftest || *g >= gtest)) { my_strcpy(task, "WARNING: STP = STPMIN"); } /* Test for convergence. */ if (*f <= ftest && abs(*g) <= *gtol * (-ginit)) { my_strcpy(task, "CONVERGENCE"); } /* Test for termination. */ if (strncmp(task, "WARN", 4) == 0 || strncmp(task, "CONV", 4)==0) { goto L1000; } /* A modified function is used to predict the step during the */ /* first stage if a lower function value has been obtained but */ /* the decrease is not sufficient. */ if (stage == 1 && *f <= fx && *f > ftest) { /* Define the modified function and derivative values. */ fm = *f - *stp * gtest; fxm = fx - stx * gtest; fym = fy - sty * gtest; gm = *g - gtest; gxm = gx - gtest; gym = gy - gtest; /* Call dcstep to update stx, sty, and to compute the new step. */ dcstep_(&stx, &fxm, &gxm, &sty, &fym, &gym, stp, &fm, &gm, &brackt, & stmin, &stmax); /* Reset the function and derivative values for f. */ fx = fxm + stx * gtest; fy = fym + sty * gtest; gx = gxm + gtest; gy = gym + gtest; } else { /* Call dcstep to update stx, sty, and to compute the new step. */ dcstep_(&stx, &fx, &gx, &sty, &fy, &gy, stp, f, g, &brackt, &stmin, & stmax); } /* Decide if a bisection step is needed. */ if (brackt) { if ((d__1 = sty - stx, abs(d__1)) >= width1 * .66) { *stp = stx + (sty - stx) * .5; } width1 = width; width = (d__1 = sty - stx, abs(d__1)); } /* Set the minimum and maximum steps allowed for stp. */ if (brackt) { stmin = min(stx,sty); stmax = max(stx,sty); } else { stmin = *stp + (*stp - stx) * 1.1; stmax = *stp + (*stp - stx) * 4.; } /* Force the step to be within the bounds stpmax and stpmin. */ *stp = max(*stp,*stpmin); *stp = min(*stp,*stpmax); /* If further progress is not possible, let stp be the best */ /* point obtained during the search. */ if ((brackt && (*stp <= stmin || *stp >= stmax)) || (brackt && stmax - stmin <= *xtol * stmax)) { *stp = stx; } /* Obtain another function and derivative. */ task[0]='F'; task[1]='G'; L1000: /* Save local variables. */ if (brackt) { isave[1] = 1; } else { isave[1] = 0; } isave[2] = stage; dsave[1] = ginit; dsave[2] = gtest; dsave[3] = gx; dsave[4] = gy; dsave[5] = finit; dsave[6] = fx; dsave[7] = fy; dsave[8] = stx; dsave[9] = sty; dsave[10] = stmin; dsave[11] = stmax; dsave[12] = width; dsave[13] = width1; return 0; } /* dcsrch_ */ /* Subroutine */ int dcstep_(doublereal *stx,doublereal * fx,doublereal * dx,doublereal * sty,doublereal * fy,doublereal * dy,doublereal * stp,doublereal * fp,doublereal * dp,logical * brackt,double *stpmin,double * stpmax)/* doublereal *stx, *fx, *dx, *sty, *fy, *dy, *stp, *fp, *dp; logical *brackt; doublereal *stpmin, *stpmax;*/ { /* System generated locals */ doublereal d__1, d__2, d__3; /* Builtin functions */ // double sqrt(); /* Local variables */ doublereal sgnd, stpc, stpf, stpq, p, q, gamma, r__, s, theta; /* Subroutine dcstep */ /* This subroutine computes a safeguarded step for a search */ /* procedure and updates an interval that contains a step that */ /* satisfies a sufficient decrease and a curvature condition. */ /* The parameter stx contains the step with the least function */ /* value. If brackt is set to .true. then a minimizer has */ /* been bracketed in an interval with endpoints stx and sty. */ /* The parameter stp contains the current step. */ /* The subroutine assumes that if brackt is set to .true. then */ /* min(stx,sty) < stp < max(stx,sty), */ /* and that the derivative at stx is negative in the direction */ /* of the step. */ /* The subroutine statement is */ /* subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt, */ /* stpmin,stpmax) */ /* where */ /* stx is a double precision variable. */ /* On entry stx is the best step obtained so far and is an */ /* endpoint of the interval that contains the minimizer. */ /* On exit stx is the updated best step. */ /* fx is a double precision variable. */ /* On entry fx is the function at stx. */ /* On exit fx is the function at stx. */ /* dx is a double precision variable. */ /* On entry dx is the derivative of the function at */ /* stx. The derivative must be negative in the direction of */ /* the step, that is, dx and stp - stx must have opposite */ /* signs. */ /* On exit dx is the derivative of the function at stx. */ /* sty is a double precision variable. */ /* On entry sty is the second endpoint of the interval that */ /* contains the minimizer. */ /* On exit sty is the updated endpoint of the interval that */ /* contains the minimizer. */ /* fy is a double precision variable. */ /* On entry fy is the function at sty. */ /* On exit fy is the function at sty. */ /* dy is a double precision variable. */ /* On entry dy is the derivative of the function at sty. */ /* On exit dy is the derivative of the function at the exit sty. */ /* stp is a double precision variable. */ /* On entry stp is the current step. If brackt is set to .true. */ /* then on input stp must be between stx and sty. */ /* On exit stp is a new trial step. */ /* fp is a double precision variable. */ /* On entry fp is the function at stp */ /* On exit fp is unchanged. */ /* dp is a double precision variable. */ /* On entry dp is the the derivative of the function at stp. */ /* On exit dp is unchanged. */ /* brackt is an logical variable. */ /* On entry brackt specifies if a minimizer has been bracketed. */ /* Initially brackt must be set to .false. */ /* On exit brackt specifies if a minimizer has been bracketed. */ /* When a minimizer is bracketed brackt is set to .true. */ /* stpmin is a double precision variable. */ /* On entry stpmin is a lower bound for the step. */ /* On exit stpmin is unchanged. */ /* stpmax is a double precision variable. */ /* On entry stpmax is an upper bound for the step. */ /* On exit stpmax is unchanged. */ /* MINPACK-1 Project. June 1983 */ /* Argonne National Laboratory. */ /* Jorge J. More' and David J. Thuente. */ /* MINPACK-2 Project. October 1993. */ /* Argonne National Laboratory and University of Minnesota. */ /* Brett M. Averick and Jorge J. More'. */ sgnd = *dp * (*dx / abs(*dx)); /* First case: A higher function value. The minimum is bracketed. */ /* If the cubic step is closer to stx than the quadratic step, the */ /* cubic step is taken, otherwise the average of the cubic and */ /* quadratic steps is taken. */ if (*fp > *fx) { theta = (*fx - *fp) * 3. / (*stp - *stx) + *dx + *dp; /* Computing MAX */ d__1 = abs(theta), d__2 = abs(*dx), d__1 = max(d__1,d__2), d__2 = abs( *dp); s = max(d__1,d__2); /* Computing 2nd power */ d__1 = theta / s; gamma = s * sqrt(d__1 * d__1 - *dx / s * (*dp / s)); if (*stp < *stx) { gamma = -gamma; } p = gamma - *dx + theta; q = gamma - *dx + gamma + *dp; r__ = p / q; stpc = *stx + r__ * (*stp - *stx); stpq = *stx + *dx / ((*fx - *fp) / (*stp - *stx) + *dx) / 2. * (*stp - *stx); if ((d__1 = stpc - *stx, abs(d__1)) < (d__2 = stpq - *stx, abs(d__2))) { stpf = stpc; } else { stpf = stpc + (stpq - stpc) / 2.; } *brackt = TRUE_; /* Second case: A lower function value and derivatives of opposite */ /* sign. The minimum is bracketed. If the cubic step is farther from */ /* stp than the secant step, the cubic step is taken, otherwise the */ /* secant step is taken. */ } else if (sgnd < 0.) { theta = (*fx - *fp) * 3. / (*stp - *stx) + *dx + *dp; /* Computing MAX */ d__1 = abs(theta), d__2 = abs(*dx), d__1 = max(d__1,d__2), d__2 = abs( *dp); s = max(d__1,d__2); /* Computing 2nd power */ d__1 = theta / s; gamma = s * sqrt(d__1 * d__1 - *dx / s * (*dp / s)); if (*stp > *stx) { gamma = -gamma; } p = gamma - *dp + theta; q = gamma - *dp + gamma + *dx; r__ = p / q; stpc = *stp + r__ * (*stx - *stp); stpq = *stp + *dp / (*dp - *dx) * (*stx - *stp); if ((d__1 = stpc - *stp, abs(d__1)) > (d__2 = stpq - *stp, abs(d__2))) { stpf = stpc; } else { stpf = stpq; } *brackt = TRUE_; /* Third case: A lower function value, derivatives of the same sign, */ /* and the magnitude of the derivative decreases. */ } else if (abs(*dp) < abs(*dx)) { /* The cubic step is computed only if the cubic tends to infinity */ /* in the direction of the step or if the minimum of the cubic */ /* is beyond stp. Otherwise the cubic step is defined to be the */ /* secant step. */ theta = (*fx - *fp) * 3. / (*stp - *stx) + *dx + *dp; /* Computing MAX */ d__1 = abs(theta), d__2 = abs(*dx), d__1 = max(d__1,d__2), d__2 = abs( *dp); s = max(d__1,d__2); /* The case gamma = 0 only arises if the cubic does not tend */ /* to infinity in the direction of the step. */ /* Computing MAX */ /* Computing 2nd power */ d__3 = theta / s; d__1 = 0., d__2 = d__3 * d__3 - *dx / s * (*dp / s); gamma = s * sqrt((max(d__1,d__2))); if (*stp > *stx) { gamma = -gamma; } p = gamma - *dp + theta; q = gamma + (*dx - *dp) + gamma; r__ = p / q; if (r__ < 0. && gamma != 0.) { stpc = *stp + r__ * (*stx - *stp); } else if (*stp > *stx) { stpc = *stpmax; } else { stpc = *stpmin; } stpq = *stp + *dp / (*dp - *dx) * (*stx - *stp); if (*brackt) { /* A minimizer has been bracketed. If the cubic step is */ /* closer to stp than the secant step, the cubic step is */ /* taken, otherwise the secant step is taken. */ if ((d__1 = stpc - *stp, abs(d__1)) < (d__2 = stpq - *stp, abs( d__2))) { stpf = stpc; } else { stpf = stpq; } if (*stp > *stx) { /* Computing MIN */ d__1 = *stp + (*sty - *stp) * .66; stpf = min(d__1,stpf); } else { /* Computing MAX */ d__1 = *stp + (*sty - *stp) * .66; stpf = max(d__1,stpf); } } else { /* A minimizer has not been bracketed. If the cubic step is */ /* farther from stp than the secant step, the cubic step is */ /* taken, otherwise the secant step is taken. */ if ((d__1 = stpc - *stp, abs(d__1)) > (d__2 = stpq - *stp, abs( d__2))) { stpf = stpc; } else { stpf = stpq; } stpf = min(*stpmax,stpf); stpf = max(*stpmin,stpf); } /* Fourth case: A lower function value, derivatives of the same sign, */ /* and the magnitude of the derivative does not decrease. If the */ /* minimum is not bracketed, the step is either stpmin or stpmax, */ /* otherwise the cubic step is taken. */ } else { if (*brackt) { theta = (*fp - *fy) * 3. / (*sty - *stp) + *dy + *dp; /* Computing MAX */ d__1 = abs(theta), d__2 = abs(*dy), d__1 = max(d__1,d__2), d__2 = abs(*dp); s = max(d__1,d__2); /* Computing 2nd power */ d__1 = theta / s; gamma = s * sqrt(d__1 * d__1 - *dy / s * (*dp / s)); if (*stp > *sty) { gamma = -gamma; } p = gamma - *dp + theta; q = gamma - *dp + gamma + *dy; r__ = p / q; stpc = *stp + r__ * (*sty - *stp); stpf = stpc; } else if (*stp > *stx) { stpf = *stpmax; } else { stpf = *stpmin; } } /* Update the interval which contains a minimizer. */ if (*fp > *fx) { *sty = *stp; *fy = *fp; *dy = *dp; } else { if (sgnd < 0.) { *sty = *stx; *fy = *fx; *dy = *dx; } *stx = *stp; *fx = *fp; *dx = *dp; } /* Compute the new step. */ *stp = stpf; return 0; } /* dcstep_ */ typedef double real; /* Subroutine */ int timer_(double *ttime) //doublereal *ttime; { // real temp; extern doublereal etime_(); // real tarray[2]; time_t currtime; /* Subroutine timer */ /* This subroutine is used to determine user time. In a typical */ /* application, the user time for a code segment requires calls */ /* to subroutine timer to determine the initial and final time. */ /* The subroutine statement is */ /* subroutine timer(ttime) */ /* where */ /* ttime is an output variable which specifies the user time. */ /* Argonne National Laboratory and University of Minnesota. */ /* MINPACK-2 Project. */ /* Modified October 1990 by Brett M. Averick. */ /* The first element of the array tarray specifies user time */ // temp = time_(tarray); // *ttime = (doublereal) tarray[0]; time(&currtime); *ttime = (double)currtime; return 0; } /* timer_ */ doublereal dnrm2_(int *n, double *x,int* incx)/* integer *n; doublereal *x; integer *incx;*/ { /* System generated locals */ integer i__1, i__2; doublereal ret_val, d__1, d__2, d__3; /* Builtin functions */ // double sqrt(); /* Local variables */ integer i__; doublereal scale; /* Function dnrm2 */ /* Given a vector x of length n, this function calculates the */ /* Euclidean norm of x with stride incx. */ /* The function statement is */ /* double precision function dnrm2(n,x,incx) */ /* where */ /* n is a positive integer input variable. */ /* x is an input array of length n. */ /* incx is a positive integer variable that specifies the */ /* stride of the vector. */ /* Subprograms called */ /* FORTRAN-supplied ... abs, max, sqrt */ /* MINPACK-2 Project. February 1991. */ /* Argonne National Laboratory. */ /* Brett M. Averick. */ /* Parameter adjustments */ --x; /* Function Body */ ret_val = 0.; scale = 0.; i__1 = *n; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { /* Computing MAX */ d__2 = scale, d__3 = (d__1 = x[i__], abs(d__1)); scale = max(d__2,d__3); /* L10: */ } if (scale == 0.) { return ret_val; } i__2 = *n; i__1 = *incx; for (i__ = 1; i__1 < 0 ? i__ >= i__2 : i__ <= i__2; i__ += i__1) { /* Computing 2nd power */ d__1 = x[i__] / scale; ret_val += d__1 * d__1; /* L20: */ } ret_val = scale * sqrt(ret_val); return ret_val; } /* dnrm2_ */ doublereal dpmeps_() { /* Initialized data */ doublereal zero = 0.; doublereal one = 1.; doublereal two = 2.; /* System generated locals */ integer i__1; doublereal ret_val; /* Local variables */ doublereal beta; integer irnd; doublereal temp, temp1, a, b; integer i__; doublereal betah; integer ibeta, negep; doublereal tempa; integer itemp, it; doublereal betain; /* Subroutine dpeps */ /* This subroutine computes the machine precision parameter */ /* dpmeps as the smallest floating point number such that */ /* 1 + dpmeps differs from 1. */ /* This subroutine is based on the subroutine machar described in */ /* W. J. Cody, */ /* MACHAR: A subroutine to dynamically determine machine parameters, */ /* ACM Transactions on Mathematical Software, 14, 1988, pages 303-311. */ /* The subroutine statement is: */ /* subroutine dpeps(dpmeps) */ /* where */ /* dpmeps is a double precision variable. */ /* On entry dpmeps need not be specified. */ /* On exit dpmeps is the machine precision. */ /* MINPACK-2 Project. February 1991. */ /* Argonne National Laboratory and University of Minnesota. */ /* Brett M. Averick. */ /* determine ibeta, beta ala malcolm. */ a = one; b = one; L10: a += a; temp = a + one; temp1 = temp - a; if (temp1 - one == zero) { goto L10; } L20: b += b; temp = a + b; itemp = (integer) (temp - a); if (itemp == 0) { goto L20; } ibeta = itemp; beta = (doublereal) ibeta; /* determine it, irnd. */ it = 0; b = one; L30: ++it; b *= beta; temp = b + one; temp1 = temp - b; if (temp1 - one == zero) { goto L30; } irnd = 0; betah = beta / two; temp = a + betah; if (temp - a != zero) { irnd = 1; } tempa = a + beta; temp = tempa + betah; if (irnd == 0 && temp - tempa != zero) { irnd = 2; } /* determine dpmeps. */ negep = it + 3; betain = one / beta; a = one; i__1 = negep; for (i__ = 1; i__ <= i__1; ++i__) { a *= betain; /* L40: */ } L50: temp = one + a; if (temp - one != zero) { goto L60; } a *= beta; goto L50; L60: ret_val = a; if (ibeta == 2 || irnd == 0) { goto L70; } a = a * (one + a) / two; temp = one + a; if (temp - one != zero) { ret_val = a; } L70: return ret_val; } /* dpmeps_ */ /* Subroutine */ int daxpy_(int *n,double * da,double * dx,int * incx,double * dy,int * incy)/* integer *n; doublereal *da, *dx; integer *incx; doublereal *dy; integer *incy;*/ { /* System generated locals */ integer i__1; /* Local variables */ integer i__, m, ix, iy, mp1; /* constant times a vector plus a vector. */ /* uses unrolled loops for increments equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ if (*n <= 0) { return 0; } if (*da == 0.) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments */ /* not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dy[iy] += *da * dx[ix]; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ /* clean-up loop */ L20: m = *n % 4; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dy[i__] += *da * dx[i__]; /* L30: */ } if (*n < 4) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 4) { dy[i__] += *da * dx[i__]; dy[i__ + 1] += *da * dx[i__ + 1]; dy[i__ + 2] += *da * dx[i__ + 2]; dy[i__ + 3] += *da * dx[i__ + 3]; /* L50: */ } return 0; } /* daxpy_ */ /* Subroutine */ int dcopy_(int *n,double * dx,int * incx,double * dy,int * incy)/* integer *n; doublereal *dx; integer *incx; doublereal *dy; integer *incy;*/ { /* System generated locals */ integer i__1; /* Local variables */ integer i__, m, ix, iy, mp1; /* copies a vector, x, to a vector, y. */ /* uses unrolled loops for increments equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments */ /* not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dy[iy] = dx[ix]; ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 */ /* clean-up loop */ L20: m = *n % 7; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dy[i__] = dx[i__]; /* L30: */ } if (*n < 7) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 7) { dy[i__] = dx[i__]; dy[i__ + 1] = dx[i__ + 1]; dy[i__ + 2] = dx[i__ + 2]; dy[i__ + 3] = dx[i__ + 3]; dy[i__ + 4] = dx[i__ + 4]; dy[i__ + 5] = dx[i__ + 5]; dy[i__ + 6] = dx[i__ + 6]; /* L50: */ } return 0; } /* dcopy_ */ doublereal ddot_(int *n,double * dx,int * incx,double * dy,int * incy)/* integer *n; doublereal *dx; integer *incx; doublereal *dy; integer *incy;*/ { /* System generated locals */ integer i__1; doublereal ret_val; /* Local variables */ integer i__, m; doublereal dtemp; integer ix, iy, mp1; /* forms the dot product of two vectors. */ /* uses unrolled loops for increments equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* Parameter adjustments */ --dy; --dx; /* Function Body */ ret_val = 0.; dtemp = 0.; if (*n <= 0) { return ret_val; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments */ /* not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { dtemp += dx[ix] * dy[iy]; ix += *incx; iy += *incy; /* L10: */ } ret_val = dtemp; return ret_val; /* code for both increments equal to 1 */ /* clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__1 = m; for (i__ = 1; i__ <= i__1; ++i__) { dtemp += dx[i__] * dy[i__]; /* L30: */ } if (*n < 5) { goto L60; } L40: mp1 = m + 1; i__1 = *n; for (i__ = mp1; i__ <= i__1; i__ += 5) { dtemp = dtemp + dx[i__] * dy[i__] + dx[i__ + 1] * dy[i__ + 1] + dx[ i__ + 2] * dy[i__ + 2] + dx[i__ + 3] * dy[i__ + 3] + dx[i__ + 4] * dy[i__ + 4]; /* L50: */ } L60: ret_val = dtemp; return ret_val; } /* ddot_ */ /* Subroutine */ int dpofa_(double *a,int * lda,int * n, int *info)/* doublereal *a; integer *lda, *n, *info;*/ { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3; /* Builtin functions */ // double sqrt(); /* Local variables */ // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer j, k; doublereal s, t; integer jm1; /* dpofa factors a double precision symmetric positive definite */ /* matrix. */ /* dpofa is usually called by dpoco, but it can be called */ /* directly with a saving in time if rcond is not needed. */ /* (time for dpoco) = (1 + 18/n)*(time for dpofa) . */ /* on entry */ /* a double precision(lda, n) */ /* the symmetric matrix to be factored. only the */ /* diagonal and upper triangle are used. */ /* lda integer */ /* the leading dimension of the array a . */ /* n integer */ /* the order of the matrix a . */ /* on return */ /* a an upper triangular matrix r so that a = trans(r)*r */ /* where trans(r) is the transpose. */ /* the strict lower triangle is unaltered. */ /* if info .ne. 0 , the factorization is not complete. */ /* info integer */ /* = 0 for normal return. */ /* = k signals an error condition. the leading minor */ /* of order k is not positive definite. */ /* linpack. this version dated 08/14/78 . */ /* cleve moler, university of new mexico, argonne national lab. */ /* subroutines and functions */ /* blas ddot */ /* fortran sqrt */ /* internal variables */ /* begin block with ...exits to 40 */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; /* Function Body */ i__1 = *n; for (j = 1; j <= i__1; ++j) { *info = j; s = 0.; jm1 = j - 1; if (jm1 < 1) { goto L20; } i__2 = jm1; for (k = 1; k <= i__2; ++k) { i__3 = k - 1; t = a[k + j * a_dim1] - ddot_(&i__3, &a[k * a_dim1 + 1], &c__1, & a[j * a_dim1 + 1], &c__1); t /= a[k + k * a_dim1]; a[k + j * a_dim1] = t; s += t * t; /* L10: */ } L20: s = a[j + j * a_dim1] - s; /* ......exit */ if (s <= 0.) { goto L40; } a[j + j * a_dim1] = sqrt(s); /* L30: */ } *info = 0; L40: return 0; } /* dpofa_ */ /* Subroutine */ int dscal_(int *n, double *da,double * dx,int * incx)/* integer *n; doublereal *da, *dx; integer *incx;*/ { /* System generated locals */ integer i__1, i__2; /* Local variables */ integer i__, m, nincx, mp1; /* scales a vector by a constant. */ /* uses unrolled loops for increment equal to one. */ /* jack dongarra, linpack, 3/11/78. */ /* modified 3/93 to return if incx .le. 0. */ /* Parameter adjustments */ --dx; /* Function Body */ if (*n <= 0 || *incx <= 0) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i__ = 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { dx[i__] = *da * dx[i__]; /* L10: */ } return 0; /* code for increment equal to 1 */ /* clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__2 = m; for (i__ = 1; i__ <= i__2; ++i__) { dx[i__] = *da * dx[i__]; /* L30: */ } if (*n < 5) { return 0; } L40: mp1 = m + 1; i__2 = *n; for (i__ = mp1; i__ <= i__2; i__ += 5) { dx[i__] = *da * dx[i__]; dx[i__ + 1] = *da * dx[i__ + 1]; dx[i__ + 2] = *da * dx[i__ + 2]; dx[i__ + 3] = *da * dx[i__ + 3]; dx[i__ + 4] = *da * dx[i__ + 4]; /* L50: */ } return 0; } /* dscal_ */ /* Subroutine */ int dtrsl_(double *t,int * ldt,int * n,double * b,int * job,int* info)/* doublereal *t; integer *ldt, *n; doublereal *b; integer *job, *info;*/ { /* System generated locals */ integer t_dim1, t_offset, i__1, i__2; /* Local variables */ integer case__; // extern doublereal ddot_(); doublereal ddot_(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy); doublereal temp; integer j; // extern /* Subroutine */ int daxpy_(); int daxpy_(integer *n, doublereal *da, doublereal *dx, integer *incx, doublereal *dy, integer *incy); integer jj; /* dtrsl solves systems of the form */ /* t * x = b */ /* trans(t) * x = b */ /* where t is a triangular matrix of order n. here trans(t) */ /* denotes the transpose of the matrix t. */ /* on entry */ /* t double precision(ldt,n) */ /* t contains the matrix of the system. the zero */ /* elements of the matrix are not referenced, and */ /* the corresponding elements of the array can be */ /* used to store other information. */ /* ldt integer */ /* ldt is the leading dimension of the array t. */ /* n integer */ /* n is the order of the system. */ /* b double precision(n). */ /* b contains the right hand side of the system. */ /* job integer */ /* job specifies what kind of system is to be solved. */ /* if job is */ /* 00 solve t*x=b, t lower triangular, */ /* 01 solve t*x=b, t upper triangular, */ /* 10 solve trans(t)*x=b, t lower triangular, */ /* 11 solve trans(t)*x=b, t upper triangular. */ /* on return */ /* b b contains the solution, if info .eq. 0. */ /* otherwise b is unaltered. */ /* info integer */ /* info contains zero if the system is nonsingular. */ /* otherwise info contains the index of */ /* the first zero diagonal element of t. */ /* linpack. this version dated 08/14/78 . */ /* g. w. stewart, university of maryland, argonne national lab. */ /* subroutines and functions */ /* blas daxpy,ddot */ /* fortran mod */ /* internal variables */ /* begin block permitting ...exits to 150 */ /* check for zero diagonal elements. */ /* Parameter adjustments */ t_dim1 = *ldt; t_offset = 1 + t_dim1 * 1; t -= t_offset; --b; /* Function Body */ i__1 = *n; for (*info = 1; *info <= i__1; ++(*info)) { /* ......exit */ if (t[*info + *info * t_dim1] == 0.) { goto L150; } /* L10: */ } *info = 0; /* determine the task and go to it. */ case__ = 1; if (*job % 10 != 0) { case__ = 2; } if (*job % 100 / 10 != 0) { case__ += 2; } switch ((int)case__) { case 1: goto L20; case 2: goto L50; case 3: goto L80; case 4: goto L110; } /* solve t*x=b for t lower triangular */ L20: b[1] /= t[t_dim1 + 1]; if (*n < 2) { goto L40; } i__1 = *n; for (j = 2; j <= i__1; ++j) { temp = -b[j - 1]; i__2 = *n - j + 1; daxpy_(&i__2, &temp, &t[j + (j - 1) * t_dim1], &c__1, &b[j], &c__1); b[j] /= t[j + j * t_dim1]; /* L30: */ } L40: goto L140; /* solve t*x=b for t upper triangular. */ L50: b[*n] /= t[*n + *n * t_dim1]; if (*n < 2) { goto L70; } i__1 = *n; for (jj = 2; jj <= i__1; ++jj) { j = *n - jj + 1; temp = -b[j + 1]; daxpy_(&j, &temp, &t[(j + 1) * t_dim1 + 1], &c__1, &b[1], &c__1); b[j] /= t[j + j * t_dim1]; /* L60: */ } L70: goto L140; /* solve trans(t)*x=b for t lower triangular. */ L80: b[*n] /= t[*n + *n * t_dim1]; if (*n < 2) { goto L100; } i__1 = *n; for (jj = 2; jj <= i__1; ++jj) { j = *n - jj + 1; i__2 = jj - 1; b[j] -= ddot_(&i__2, &t[j + 1 + j * t_dim1], &c__1, &b[j + 1], &c__1); b[j] /= t[j + j * t_dim1]; /* L90: */ } L100: goto L140; /* solve trans(t)*x=b for t upper triangular. */ L110: b[1] /= t[t_dim1 + 1]; if (*n < 2) { goto L130; } i__1 = *n; for (j = 2; j <= i__1; ++j) { i__2 = j - 1; b[j] -= ddot_(&i__2, &t[j * t_dim1 + 1], &c__1, &b[1], &c__1); b[j] /= t[j + j * t_dim1]; /* L120: */ } L130: L140: L150: return 0; } /* dtrsl_ */
# -*- coding: utf-8 -*- import random import re import threading import time from module.plugins.internal.Plugin import Plugin, Skip from module.plugins.internal.misc import Periodical, compare_time, decode, isiterable, lock, parse_size class Account(Plugin): __name__ = "Account" __type__ = "account" __version__ = "0.75" __status__ = "stable" __description__ = """Base account plugin""" __license__ = "GPLv3" __authors__ = [("Walter Purcaro", "vuolter@gmail.com")] LOGIN_TIMEOUT = 30 * 60 #: Relogin account every 30 minutes TUNE_TIMEOUT = True #: Automatically tune relogin interval def __init__(self, manager, accounts): self._init(manager.core) self.manager = manager self.lock = threading.RLock() self.accounts = accounts #@TODO: Recheck in 0.4.10 self.user = None self.timeout = self.LOGIN_TIMEOUT #: Callback of periodical job task, used by HookManager self.periodical = Periodical(self, self.periodical_task) self.cb = self.periodical.cb #@TODO: Recheck in 0.4.10 self.init() @property def logged(self): """ Checks if user is still logged in """ if not self.user: return False self.sync() if self.info['login']['timestamp'] + self.timeout < time.time(): self.log_debug("Reached login timeout for user `%s`" % self.user) return False else: return True @property def premium(self): return bool(self.get_data('premium')) def _log(self, level, plugintype, pluginname, messages): log = getattr(self.pyload.log, level) msg = u" | ".join(decode(a).strip() for a in messages if a) #: Hide any password try: msg = msg.replace(self.info['login']['password'], "**********") except Exception: pass log("%(plugintype)s %(pluginname)s: %(msg)s" % {'plugintype': plugintype.upper(), 'pluginname': pluginname, 'msg' : msg}) def setup(self): """ Setup for enviroment and other things, called before logging (possibly more than one time) """ pass def periodical_task(self): raise NotImplementedError def signin(self, user, password, data): """ Login into account, the cookies will be saved so user can be recognized """ pass def login(self): if not self.req: self.log_info(_("Login user `%s`...") % self.user) else: self.log_info(_("Relogin user `%s`...") % self.user) self.clean() self.req = self.pyload.requestFactory.getRequest(self.classname, self.user) self.sync() self.setup() timestamp = time.time() try: self.signin(self.user, self.info['login']['password'], self.info['data']) except Skip, e: self.log_warning(_("Skipped login user `%s`") % self.user, e) self.info['login']['valid'] = True new_timeout = timestamp - self.info['login']['timestamp'] if self.TUNE_TIMEOUT and new_timeout > self.timeout: self.timeout = new_timeout except Exception, e: self.log_error(_("Could not login user `%s`") % self.user, e) self.info['login']['valid'] = False else: self.info['login']['valid'] = True finally: self.info['login']['timestamp'] = timestamp #: Set timestamp for login self.syncback() return bool(self.info['login']['valid']) #@TODO: Recheck in 0.4.10 def syncback(self): """ Wrapper to directly sync self.info -> self.accounts[self.user] """ return self.sync(reverse=True) #@TODO: Recheck in 0.4.10 def sync(self, reverse=False): """ Sync self.accounts[self.user] -> self.info or self.info -> self.accounts[self.user] (if reverse is True) """ if not self.user: return u = self.accounts[self.user] if reverse: u.update(self.info['data']) u.update(self.info['login']) else: d = {'login': {}, 'data': {}} for k, v in u.items(): if k in ('password', 'timestamp', 'valid'): d['login'][k] = v else: d['data'][k] = v self.info.update(d) def relogin(self): return self.login() def reset(self): self.sync() clear = lambda x: {} if isinstance(x, dict) else [] if isiterable(x) else None self.info['data'] = dict((k, clear(v)) for k, v in self.info['data'].items()) self.info['data']['options'] = {'limitdl': ['0']} self.syncback() def get_info(self, refresh=True): """ Retrieve account infos for an user, do **not** overwrite this method! just use it to retrieve infos in hoster plugins. see `grab_info` :param user: username :param relogin: reloads cached account information :return: dictionary with information """ if not self.logged: if self.relogin(): refresh = True else: refresh = False self.reset() if refresh and self.info['login']['valid']: self.log_info(_("Grabbing account info for user `%s`...") % self.user) self.info = self._grab_info() self.syncback() self.log_debug("Account info for user `%s`: %s" % (self.user, self.info)) return self.info def get_login(self, key=None, default=None): d = self.get_info()['login'] return d.get(key, default) if key else d def get_data(self, key=None, default=None): d = self.get_info()['data'] return d.get(key, default) if key else d def _grab_info(self): try: data = self.grab_info(self.user, self.info['login']['password'], self.info['data']) if data and isinstance(data, dict): self.info['data'].update(data) except Exception, e: self.log_warning(_("Error loading info for user `%s`") % self.user, e) finally: return self.info def grab_info(self, user, password, data): """ This should be overwritten in account plugin and retrieving account information for user :param user: :param req: `Request` instance :return: """ pass @lock def init_accounts(self): accounts = dict(self.accounts) self.accounts.clear() for user, info in accounts.items(): self.add(user, info['password'], info['options']) @lock def getAccountData(self, user, force=False): if force: self.accounts[user]['plugin'].get_info() return self.accounts[user] @lock def getAllAccounts(self, force=False): if force: self.init_accounts() #@TODO: Recheck in 0.4.10 return [self.getAccountData(user, force) for user in self.accounts] #@TODO: Remove in 0.4.10 @lock def scheduleRefresh(self, user, force=False): pass @lock def add(self, user, password=None, options={}): self.log_info(_("Adding user `%s`...") % user) if user in self.accounts: self.log_error(_("Error adding user `%s`") % user, _("User already exists")) return False d = {'login' : user, 'maxtraffic' : None, 'options' : options or {'limitdl': ['0']}, 'password' : password or "", 'plugin' : self.__class__(self.manager, self.accounts), 'premium' : None, 'timestamp' : 0, 'trafficleft': None, 'type' : self.__name__, 'valid' : None, 'validuntil' : None} u = self.accounts[user] = d result = u['plugin'].choose(user) u['plugin'].get_info() return result @lock def updateAccounts(self, user, password=None, options={}): """ Updates account and return true if anything changed """ if user in self.accounts: self.log_info(_("Updating account info for user `%s`...") % user) u = self.accounts[user] if password: u['password'] = password if options: u['options'].update(options) u['plugin'].relogin() else: self.add(user, password, options) @lock def removeAccount(self, user): self.log_info(_("Removing user `%s`...") % user) self.accounts.pop(user, None) if user is self.user: self.choose() @lock def select(self): free_accounts = {} premium_accounts = {} for user in self.accounts: info = self.accounts[user]['plugin'].get_info() data = info['data'] if not info['login']['valid']: continue if data['options'].get('time'): time_data = "" try: time_data = data['options']['time'][0] start, end = time_data.split("-") if not compare_time(start.split(":"), end.split(":")): continue except Exception: self.log_warning(_("Invalid time format `%s` for account `%s`, use 1:22-3:44") % (user, time_data)) if data['trafficleft'] == 0: self.log_warning(_("Not using account `%s` because the account has no traffic left") % user) continue if time.time() > data['validuntil'] > 0: self.log_warning(_("Not using account `%s` because the account has expired") % user) continue if data['premium']: premium_accounts[user] = info else: free_accounts[user] = info account_list = (premium_accounts or free_accounts).items() if not account_list: return None, None validuntil_list = [(user, info) for user, info in account_list \ if info['data']['validuntil']] if not validuntil_list: return random.choice(account_list) #@TODO: Random account?! Rewrite in 0.4.10 return sorted(validuntil_list, key=lambda a: a[1]['data']['validuntil'], reverse=True)[0] @lock def choose(self, user=None): """ Choose a valid account """ if not user: user = self.select()[0] elif user not in self.accounts: self.log_error(_("Error choosing user `%s`") % user, _("User not exists")) return False if self.req and user is self.user: return True self.user = user self.info.clear() self.clean() if user is None: return False else: if not self.logged: self.relogin() else: self.req = self.pyload.requestFactory.getRequest(self.classname, self.user) return True def parse_traffic(self, size, unit=None): #@NOTE: Returns kilobytes only in 0.4.9 self.log_debug("Size: %s" % size, "Unit: %s" % (unit or "N/D")) return parse_size(size, unit or "byte") / 1024 #@TODO: Remove `/ 1024` in 0.4.10 def fail_login(self, msg=_("Login handshake has failed")): return self.fail(msg) def skip_login(self, msg=_("Already signed in")): return self.skip(msg)
package net.gravitydevelopment.anticheat.config.providers; import net.gravitydevelopment.anticheat.util.Group; import java.util.List; public interface Groups { /** * Get all groups. * * @return List of groups. */ public List<Group> getGroups(); /** * Get the highest level value assigned to a group. * Used as a maximum cap to rising hack levels. * * @return Highest group level. */ public int getHighestLevel(); }
#pragma once #include "common.h" extern bool <API key>; void <API key>(); void <API key>();
<!-- start: BREADCRUMB --> <div class="breadcrumb-wrapper"> <h4 class="mainTitle no-margin" translate="dashboard.WELCOME" translate-values="{ appName: app.name }">WELCOME TO CLIP-TWO</h4> <span class="mainDescription">overview &amp; stats </span> <div ncy-breadcrumb class="pull-right"></div> </div> <!-- end: BREADCRUMB --> <!-- start: FIRST SECTION --> <div class="container-fluid container-fullw padding-bottom-10"> <div class="row"> <div class="col-sm-12"> <div class="row"> <div class="col-md-12 col-lg-3"> <div class="row"> <div class="col-md-4 col-lg-12"> <table class="table table-stylish"> <tbody> <tr> <td class="center text-extra-large"><i class="fa fa-desktop"></i></td> <td><span class="text-dark block">Desktop</span></td> <td class="center">49,090</td> <td class="center"><i class="fa fa-caret-down text-red"></i></td> </tr> <tr> <td class="center text-extra-large"><i class="fa fa-tablet"></i></td> <td>Tablet</td> <td class="center">23,130</td> <td class="center"><i class="fa fa-caret-up text-green"></i></td> </tr> <tr> <td class="center text-extra-large"><i class="fa fa-mobile"></i></td> <td>Mobile</td> <td class="center">138,570</td> <td class="center"><i class="fa fa-caret-up text-green"></i></td> </tr> </tbody> </table> </div> <div class="col-md-4 col-lg-12"> <div class="panel panel-white no-radius no-border"> <ct-paneltool class="panel-tools" tool-refresh="load1"></ct-paneltool> <div class="panel-body no-padding"> <div class="row"> <div class="col-xs-12"> <div class="padding-15"> <h5 class="text-dark">Acquisition</h5> <p> <span class="label label-success margin-right-10">100%</span><span class="text-bold text-extra-small">All Sessions</span> </p> <p> <span class="text-small"> (17,869 of 17,869)</span> </p> </div> </div> <div class="col-xs-12"> <!-- /// controller: 'AcquisitionCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="AcquisitionCtrl"> <canvas class="chart chart-bar height-65" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </div> </div> </div> </div> </div> </div> <div class="col-md-4 col-lg-12"> <div class="panel panel-white no-radius no-border"> <ct-paneltool class="panel-tools" tool-refresh="load1"></ct-paneltool> <div class="panel-body no-padding"> <div class="row"> <div class="col-xs-12"> <div class="padding-15"> <h5 class="text-dark">Conversions</h5> <p> <i class="fa fa-circle text-azure margin-right-5"></i><span class="text-bold text-extra-small">Ecommerce Conversion Rate</span> </p> <p> <span class="text-small"> 1,20%</span> </p> </div> </div> <div class="col-xs-12"> <!-- /// controller: 'ConversionsCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="ConversionsCtrl" class="margin-negative-5"> <canvas class="chart chart-line height-75" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </div> </div> </div> </div> </div> </div> </div> </div> <div class="col-md-7 col-lg-5"> <div class="panel panel-white no-radius no-border" id="visits"> <div class="panel-heading padding-right-70"> <h2 class="inline-block"> Top 3 Products </h2> <ct-paneltool class="panel-tools" tool-refresh="load1" tool-expand="tool-expand"></ct-paneltool> </div> <div class="panel-wrapper"> <div class="panel-body"> <div class="block"> <div class="pull-left"> <h3 class="inline-block text-red text-bold"> 207K </h3> <span class="inline-block text-extra-small text-green">+8.24 %</span> </div> <div class="text-right"> <button class="btn btn-xs btn-grey"> Hourly </button> <button class="btn btn-xs btn-grey"> Day </button> <button class="btn btn-xs btn-grey"> Week </button> <button class="btn btn-xs btn-grey active"> Month </button> </div> </div> <!-- /// controller: 'ProductsCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="ProductsCtrl"> <canvas class="chart chart-line height-300" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </div> <div class="row padding-top-25"> <div class="col-xs-4 text-center"> <div class="margin-bottom-10"> <letter-icon data="Alpha" color="#947499" size="sm" class="margin-right-10"></letter-icon><span class="text-extra-large text-bold">+5,04 %</span> </div> Alpha </div> <div class="col-xs-4 text-center"> <div class="margin-bottom-10"> <letter-icon data="Omega" color="#7F8C8D" size="sm" class="margin-right-10"></letter-icon><span class="text-extra-large text-bold">+2,21 %</span> </div> Omega </div> <div class="col-xs-4 text-center"> <div class="margin-bottom-10"> <letter-icon data="Kappa" color="#5A8770" size="sm" class="margin-right-10"></letter-icon><span class="text-extra-large text-bold">+0,68 %</span> </div> Kappa </div> </div> </div> </div> <div class="panel-footer no-border"> <p class="no-margin"> <a href="#"><i class="fa <API key> text-green"></i></a> <span class="text-light margin-left-10">Show more details </span> </p> </div> </div> </div> <div class="col-md-5 col-lg-4"> <div class="panel panel-white no-radius no-border"> <div class="panel-heading border-light"> <h4 class="panel-title"> Users </h4> <ct-paneltool class="panel-tools" tool-refresh="load1" tool-expand="tool-expand"></ct-paneltool> </div> <div class="panel-body"> <div class="row"> <div class="col-sm-12"> <div class="panel-scroll height-200" perfect-scrollbar wheel-propagation="false" suppress-scroll-x="true"> <table class="table no-margin"> <tbody> <tr> <td class="center"><img alt="image" class="img-circle" src="assets/images/avatar-1-small.jpg"></td> <td><span class="text-small block text-light">UI Designer</span> <a href=" Peter Clark </a></td> <td><span class="label partition-purple">Administrator</span></td> </tr> <tr> <td class="center"><img alt="image" class="img-circle" src="assets/images/avatar-2-small.jpg"></td> <td><span class="text-small block text-light">Content Designer</span> <a href=" Nicole Bell </a></td> <td><span class="label partition-green">Editor</span></td> </tr> <tr> <td class="center"><img alt="image" class="img-circle" src="assets/images/avatar-3-small.jpg"></td> <td><span class="text-small block text-light">Visual Designer</span> <a href=" Steven Thompson </a></td> <td><span class="label partition-blue">Author</span></td> </tr> <tr> <td class="center"><img alt="image" class="img-circle" src="assets/images/avatar-5-small.jpg"></td> <td><span class="text-small block text-light">Senior Designer</span> <a href=" Kenneth Ross </a></td> <td><span class="label partition-orange">Contributor</span></td> </tr> <tr> <td class="center"><img alt="image" class="img-circle" src="assets/images/avatar-4-small.jpg"></td> <td><span class="text-small block text-light">Web Editor</span> <a href=" Ella Patterson </a></td> <td><span class="label partition-green">Editor</span></td> </tr> </tbody> </table> </div> </div> </div> <div class="row margin-top-15"> <div class="col-xs-4 text-center"> <div class="rate"> <i class="fa fa-caret-up text-green margin-right-5"></i><span class="value">26</span><span class="percentage">%</span> </div> <small class="text-muted">Blog Post</small> </div> <div class="col-xs-4 text-center"> <div class="rate"> <i class="fa fa-caret-up text-green margin-right-5"></i><span class="value">62</span><span class="percentage">%</span> </div> <small class="text-muted">Forum Post</small> </div> <div class="col-xs-4 text-center"> <div class="rate"> <i class="fa fa-caret-down text-red margin-right-5"></i><span class="value">12</span><span class="percentage">%</span> </div> <small class="text-muted">Forum Reply</small> </div> </div> <div class="panel-scroll height-200 margin-top-25" perfect-scrollbar wheel-propagation="false" suppress-scroll-x="true"> <div class="media padding-left-10 padding-right-10"> <a href="#" class="pull-left"> <img alt="image" class="img-circle" src="assets/images/avatar-2.jpg"> </a> <div class="media-body "> <small class="pull-right text-light">5 mins ago</small> <strong>Nicole Bell</strong> posted on your <strong>timeline</strong>. <br> <small class="text-light">125 Likes - 12 Comments - 25 Shares</small> <div class="well padding-15 margin-top-15"> In placerat feugiat odio a ullamcorper. Aliquam vel justo vel nisl sollicitudin bibendum. Donec a vehicula risus, a pellentesque metus. </div> <div class="pull-right"> <a class="btn btn-xs btn-default"><i class="fa fa-thumbs-up"></i> Like </a> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <!-- end: FIRST SECTION --> <!-- start: SECOND SECTION --> <div class="container-fluid container-fullw padding-bottom-10"> <div class="row"> <div class="col-lg-7"> <div class="row"> <div class="col-sm-6"> <div class="panel panel-green no-border no-radius"> <ct-paneltool class="panel-tools" tool-refresh="load1"></ct-paneltool> <div class="panel-body no-padding"> <div class="space10 padding-15"> <h5 class="text-bold text-extra-small <API key> text-uppercase no-margin">Revenue YTD <i class="fa <API key>"></i></h5> <h2 class="text-white margin-top-15 margin-bottom-10">$159M</h2> <span class="label background-light text-dark margin-top-10 margin-right-5">+6.24M</span><span class="text-extra-small">+4.08%</span> </div> <!-- /// controller: 'LineCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="LineCtrl"> <canvas class="chart chart-line height-80" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </div> </div> </div> </div> <div class="col-sm-6"> <div class="panel panel-azure no-border no-radius"> <div class="panel-body no-padding"> <div class="space10 padding-15"> <h5 class="text-bold text-extra-small <API key> text-uppercase no-margin">Expenses YTD <i class="fa <API key>"></i></h5> <h2 class="text-white margin-top-15 margin-bottom-10">$30.6M</h2> <span class="label background-light text-dark margin-top-10 margin-right-5">+15.3K</span><span class="text-extra-small">+0.05%</span> </div> <!-- /// controller: 'BarCtrl2' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="BarCtrl2"> <canvas class="chart chart-bar height-80" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </div> </div> </div> </div> <div class="col-sm-6"> <div class="panel panel-purple no-radius no-border"> <div class="panel-body no-padding"> <div class="space10 padding-15"> <h5 class="text-bold text-extra-small <API key> text-uppercase no-margin">Real-Time <i class="fa <API key>"></i></h5> <div class="block text-center"> <!-- /// controller: 'RandomCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="RandomCtrl"> <h2 class="text-white text-bold margin-top-5 margin-bottom-5">{{randomUsers}}</h2> <span class="<API key> margin-bottom-5 block">active users on site</span> </div> <div class="height-80 margin-bottom-10"> <!-- /// controller: 'KnobCtrl3' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div class="inline-block margin-right-25" ng-controller="KnobCtrl3"> <ui-knob value="value" options="options"></ui-knob><span class="text-white block">CPU used</span> </div> <!-- /// controller: 'KnobCtrl4' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div class="inline-block" ng-controller="KnobCtrl4"> <ui-knob value="value" options="options"></ui-knob><span class="text-white block">RAM used</span> </div> </div> </div> </div> </div> </div> </div> <div class="col-sm-6"> <div class="panel panel-pink no-border no-radius"> <ct-paneltool class="panel-tools" tool-refresh="load1"></ct-paneltool> <div class="panel-body no-padding"> <div class="space10 padding-15"> <h5 class="text-bold text-extra-small <API key> text-uppercase no-margin">Total Products <i class="fa <API key>"></i></h5> <h2 class="text-white margin-top-15 margin-bottom-10">5,635</h2> <span class="label background-light text-dark margin-top-10 margin-right-5">89%</span><span class="text-extra-small">with active listings</span> </div> <div class="min-height-80"> <div class="padding-top-20"> <uib-progressbar value="89" class="progress-xs no-radius background-dark no-margin" type="white"></uib-progressbar> </div> </div> </div> </div> </div> </div> </div> <div class="col-lg-5"> <div class="row"> <div class="col-xs-12"> <div class="panel panel-white no-radius no-border"> <div class="panel-body"> <div class="<API key> padding-15 text-center margin-bottom-25"> <h4 class="no-margin">Monthly Statistics</h4> <span class="text-light">based on the major browsers</span> </div> <v-accordion class="vAccordion--default"> <!-- add expanded attribute to open first section --> <v-pane expanded> <v-pane-header> This Month </v-pane-header> <v-pane-content> <table class="table margin-bottom-5"> <tbody> <tr> <td>Google Chrome</td> <td class="center">4909</td> <td><i class="fa fa-caret-down text-red"></i></td> </tr> <tr> <td>Mozilla Firefox</td> <td class="center">3857</td> <td><i class="fa fa-caret-up text-green"></i></td> </tr> <tr> <td>Safari</td> <td class="center">1789</td> <td><i class="fa fa-caret-up text-green"></i></td> </tr> <tr> <td>Internet Explorer</td> <td class="center">612</td> <td><i class="fa fa-caret-down text-red"></i></td> </tr> </tbody> </table> </v-pane-content> </v-pane> <v-pane> <v-pane-header> Last Month </v-pane-header> <v-pane-content> <table class="table margin-bottom-5"> <tbody> <tr> <td>Google Chrome</td> <td class="center">5228</td> <td><i class="fa fa-caret-up text-green"></i></td> </tr> <tr> <td>Mozilla Firefox</td> <td class="center">2853</td> <td><i class="fa fa-caret-up text-green"></i></td> </tr> <tr> <td>Safari</td> <td class="center">1948</td> <td><i class="fa fa-caret-up text-green"></i></td> </tr> <tr> <td>Internet Explorer</td> <td class="center">456</td> <td><i class="fa fa-caret-down text-red"></i></td> </tr> </tbody> </table> </v-pane-content> </v-pane> </v-accordion> </div> <div class="panel-footer border-light"> <p class="no-margin"> <a href="#"><i class="fa <API key> text-green"></i></a> <span class="text-light margin-left-10">Show more details </span> </p> </div> </div> </div> </div> </div> </div> </div> <!-- end: SECOND SECTION --> <!-- start: THIRD SECTION --> <div class="container-fluid container-fullw padding-bottom-10"> <div class="row"> <div class="col-md-12 col-lg-9"> <div class="panel panel-white no-radius" id="panelsocial"> <div class="panel-heading border-light"> <h4 class="panel-title">Social Marketing</h4> <ct-paneltool class="panel-tools" tool-collapse="tool-collapse" tool-dismiss="tool-dismiss"></ct-paneltool> </div> <div uib-collapse="panelsocial" ng-init="panelsocial=false" class="panel-wrapper"> <div class="panel-body no-padding"> <div class="row"> <div class="col-sm-6"> <div class="padding-10 block text-center"> <p> <span class="text-bold">Social Traffic</span><span class="text-light"> (7 days)</span> </p> <!-- /// controller: 'SocialCtrl3' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="SocialCtrl3"> <div class="text-center"> <span class="mini-pie-100"> <canvas class="chart chart-doughnut" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </span> </div> </div> <h4><i class="fa fa-sort-up small text-green margin-right-5"></i><span class="text-bold text-dark margin-right-10">Facebook</span><span class="text-grey">(43.98%)</span></h4> </div> </div> <div class="col-sm-6"> <div class="padding-10 block text-center"> <p> <span class="text-bold">Marketing Channels</span><span class="text-light"> (7 days)</span> </p> <!-- /// controller: 'SocialCtrl4' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="SocialCtrl4"> <div class="text-center"> <span class="mini-pie-100"> <canvas class="chart chart-doughnut" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas></span> </div> </div> <h4><i class="fa fa-sort-up small text-green margin-right-5"></i><span class="text-bold text-dark margin-right-10">Display Ads</span><span class="text-grey">(72.11%)</span></h4> </div> </div> </div> <div class="clearfix padding-5 space5"> <div class="col-xs-4 text-center no-padding"> <div class="border-right border-dark"> <a class="text-dark" href=" <i class="fa fa-heart-o text-red"></i> 250 </a> </div> </div> <div class="col-xs-4 text-center no-padding"> <div class="border-right border-dark"> <a class="text-dark" href=" <i class="fa fa-bookmark-o text-green"></i> 20 </a> </div> </div> <div class="col-xs-4 text-center no-padding"> <a class="text-dark" href="#"><i class="fa fa-comment-o text-azure"></i> 544</a> </div> </div> <uib-tabset class="tabbable no-padding no-margin"> <uib-tab heading="This Month" class="padding-top-5 padding-left-5"> <table class="table no-margin"> <thead> <tr> <th class="width-50 hidden-xs hidden-sm"></th> <th>Campaign</th> <th>Clicks</th> <th class="hidden-xs hidden-sm">Impr. <a href="" uib-popover="Impressions help you understand how often your ad is being seen. They're also used to calculate clickthrough rate (CTR), which is helpful in determining the effectiveness of your ads." popover-placement="top" popover-title=""><i class="fa fa-question-circle <API key> margin-left-5"></i></a></th> <th class="hidden-xs hidden-sm">CTR <a href="" uib-popover="Click-through rate (CTR) is the ratio of users who click on a specific link to the number of total users who view a page, email, or advertisement." popover-placement="top" popover-title=""><i class="fa fa-question-circle <API key> margin-left-5"></i></a></th> <th class="hidden-xs hidden-sm">Cost <a href="" uib-popover="Cost is the sum of your cost-per-click (CPC) spend and cost-per-thousand impressions (CPM) spend during this period." popover-placement="top" popover-title=""><i class="fa fa-question-circle <API key> margin-left-5"></i></a></th> <th>Actions</th> </tr> </thead> <tbody> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox1" value="1"> <label for="checkbox1"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-facebook" class="pull-left margin-right-10" box="round" color="#6F83B6" color-hover="#4862A3"></letter-icon> <span class="block">Facebook</span> <span class="text-small text-light">6 active campaigns</span> </a></td> <td>1,596</td> <td class="hidden-xs hidden-sm">9,990</td> <td class="hidden-xs hidden-sm">15.98%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 1,164.22</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox2" value="1"> <label for="checkbox2"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-twitter" class="pull-left margin-right-10" box="round" color="#79BEF1" color-hover="#55ACEE"></letter-icon> <span class="block">Twitter</span> <span class="text-small text-light">6 active campaigns</span> </a></td> <td>574</td> <td class="hidden-xs hidden-sm">6,931</td> <td class="hidden-xs hidden-sm">8.28%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 397.73</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox3" value="1"> <label for="checkbox3"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-youtube-play" class="pull-left margin-right-10" box="round" color="#ED5952" color-hover="#E62117"></letter-icon> <span class="block">YouTube</span> <span class="text-small text-light">6 active campaigns</span> </a></td> <td>277</td> <td class="hidden-xs hidden-sm">484</td> <td class="hidden-xs hidden-sm">57.23%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 136.09</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox4" value="1"> <label for="checkbox4"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-spotify" class="pull-left margin-right-10" box="round" color="#8BC33E" color-hover="#7CB549"></letter-icon> <span class="block">Spotify</span> <span class="text-small text-light">6 active campaigns</span> </a></td> <td>215</td> <td class="hidden-xs hidden-sm">584</td> <td class="hidden-xs hidden-sm">36.82%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 138.22</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> </tbody> </table> </uib-tab> <uib-tab heading="Last Month" class="padding-top-5"> <table class="table no-margin"> <thead> <tr> <th class="width-50 hidden-xs hidden-sm"></th> <th>Campaign</th> <th>Clicks</th> <th class="hidden-xs hidden-sm">Impr. <a href="" uib-popover="Impressions help you understand how often your ad is being seen. They're also used to calculate clickthrough rate (CTR), which is helpful in determining the effectiveness of your ads." popover-placement="top" popover-title=""><i class="fa fa-question-circle <API key> margin-left-5"></i></a></th> <th class="hidden-xs hidden-sm">CTR <a href="" uib-popover="Click-through rate (CTR) is the ratio of users who click on a specific link to the number of total users who view a page, email, or advertisement." popover-placement="top" popover-title=""><i class="fa fa-question-circle <API key> margin-left-5"></i></a></th> <th class="hidden-xs hidden-sm">Cost <a href="" uib-popover="Cost is the sum of your cost-per-click (CPC) spend and cost-per-thousand impressions (CPM) spend during this period." popover-placement="top" popover-title=""><i class="fa fa-question-circle <API key> margin-left-5"></i></a></th> <th>Actions</th> </tr> </thead> <tbody> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox2" value="1"> <label for="checkbox2"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-twitter" class="pull-left margin-right-10" box="round" color="#79BEF1" color-hover="#55ACEE"></letter-icon> <span class="block">Twitter</span> <span class="text-small text-light">9 active campaigns</span> </a></td> <td>1292</td> <td class="hidden-xs hidden-sm">2,657</td> <td class="hidden-xs hidden-sm">7.18%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 2499.76</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox1" value="1"> <label for="checkbox1"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-facebook" class="pull-left margin-right-10" box="round" color="#6F83B6" color-hover="#4862A3"></letter-icon> <span class="block">Facebook</span> <span class="text-small text-light">5 active campaigns</span> </a></td> <td>1,097</td> <td class="hidden-xs hidden-sm">8,896</td> <td class="hidden-xs hidden-sm">15.21%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 964.21</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox3" value="1"> <label for="checkbox3"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-youtube-play" class="pull-left margin-right-10" box="round" color="#ED5952" color-hover="#E62117"></letter-icon> <span class="block">YouTube</span> <span class="text-small text-light">6 active campaigns</span> </a></td> <td>256</td> <td class="hidden-xs hidden-sm">498</td> <td class="hidden-xs hidden-sm">58.11%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 144.32</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> <tr> <td class="hidden-xs hidden-sm"> <div class="checkbox clip-check check-primary"> <input type="checkbox" id="checkbox4" value="1"> <label for="checkbox4"> </label> </div></td> <td> <a href=""> <letter-icon data-icon="fa fa-spotify" class="pull-left margin-right-10" box="round" color="#8BC33E" color-hover="#7CB549"></letter-icon> <span class="block">Spotify</span> <span class="text-small text-light">6 active campaigns</span> </a></td> <td>210</td> <td class="hidden-xs hidden-sm">579</td> <td class="hidden-xs hidden-sm">37.01%</td> <td class="hidden-xs hidden-sm"><span class="text-bold">$ 140.12</span></td> <td> <div uib-dropdown> <a href class="dropdown-toggle btn btn-transparent" uib-dropdown-toggle><i class="fa fa-caret-down"></i> </a> <ul class="dropdown-menu pull-right animated fadeInRight"> <li> <a href=" Edit campaigns </a> </li> <li> <a href=" Disable all campaigns </a> </li> <li class="divider"></li> <li> <a href=" Settings </a> </li> </ul> </div></td> </tr> </tbody> </table> </uib-tab> </uib-tabset> </div> <div class="panel-footer no-border padding-top-0"> <p class="no-margin"> <a href="#"><i class="fa <API key> text-green"></i></a> <span class="text-light margin-left-10">Show more details </span> </p> </div> </div> </div> </div> <div class="col-md-12 col-lg-3"> <div class="panel panel-white no-radius"> <div class="panel-heading border-bottom"> <h4 class="panel-title">Campaign Options</h4> <ct-paneltool class="panel-tools" tool-dismiss="tool-dismiss" tool-expand="tool-expand"></ct-paneltool> </div> <div class="panel-body"> <!-- /// controller: 'BudgetCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="BudgetCtrl"> <p> <span class="text-bold">Daily Budget</span><span class="text-light"> (USD)</span> </p> <input ng-model="dailyValue" type="text" slider options="dailyOptions" /> <p class="padding-top-20"> <span class="text-bold">Total Budget</span><span class="text-light"> (USD)</span> </p> <input ng-model="totalValue" type="text" slider options="totalOptions" /> <p class="padding-top-20"> <span class="text-bold">Locations</span> </p> <div class="padding-left-10"> <p class="text-small"> Targeted locations: <ul> <li class="text-bold"> Canada </li> <li class="text-bold"> United States </li> </ul> </p> <p class="text-extra-small"> <a href="#" class="text-bold"> Edit </a> <a href="#" class="margin-left-25 text-bold"> View location info <i class="fa fa-angle-right"></i> </a> </p> </div> <div class="padding-top-30 padding-bottom-30"> <p class="text-bold"> Estimated Daily Reach </p> <hr class="margin-top-15 margin-bottom-15" /> <p class="text-bold text-small"> 5,300 - 14,000 people </p> <uib-progressbar class="progress-sm no-radius no-margin background-dark" value="25" type="warning"></uib-progressbar> <p class="no-margin"> <span class="text-extra-small text-light pull-left">0</span> <span class="text-extra-small text-light pull-right">of 18,000,000</span> </p> </div> <div class="padding-top-20"> <p class="text-bold text-small"> Ad Set Duration: 31 days </p> </div> </div> </div> <div class="panel-footer no-border"> <p class="no-margin"> <a href="#"><i class="fa <API key> text-green"></i></a> <span class="text-light margin-left-10">Show more details </span> </p> </div> </div> </div> </div> </div> <!-- end: THIRD SECTION --> <!-- start: FOURTH SECTION --> <div class="container-fluid container-fullw padding-bottom-10"> <div class="row"> <div class="col-md-6 col-lg-4"> <div class="panel panel-white no-radius"> <div class="panel-heading border-bottom"> <h4 class="panel-title">Demographics</h4> </div> <div class="panel-body"> <h5 class="text-bold">Gender</h5> <p class="text-light text-small"> Based on the share of users whose gender we were able to determinate through social profile analysis. </p> <div class="row"> <div class="col-xs-6 no-padding border-right"> <div class="padding-10 text-center"> <i class="fa fa-female text-pink large-letters"></i> <span class="text-extra-large block margin-top-15">46%</span> </div> </div> <div class="col-xs-6 no-padding border-right"> <div class="padding-10 text-center"> <i class="fa fa-male text-azure large-letters"></i> <span class="text-extra-large block margin-top-15">54%</span> </div> </div> </div> <div class="padding-top-15"> <h5 class="text-bold">Age</h5> <p class="text-light text-small"> Based on the share of users whose age we were able to determinate through social profile analysis. </p> <uib-progressbar value="25" class="no-radius progress-sm background-dark" type="info"> 18-29 </uib-progressbar> <uib-progressbar value="37" class="no-radius progress-sm background-dark" type="info"> 30-49 </uib-progressbar> <uib-progressbar value="22" class="no-radius progress-sm background-dark" type="info"> 50-64 </uib-progressbar> <uib-progressbar value="15" class="no-radius progress-sm background-dark" type="info"> 65+ </uib-progressbar> </div> </div> <div class="panel-footer"> <div class="clearfix padding-5 padding-top-10 padding-bottom-10 space5"> <div class="col-xs-6 text-center no-padding"> <div class="border-right border-dark"> <span class="text-bold block text-extra-large">34,468</span> <span class="text-light text-extra-small">Male Fans</span> </div> </div> <div class="col-xs-6 text-center no-padding"> <div> <span class="text-bold block text-extra-large">28,657</span> <span class="text-light text-extra-small">Female Fans</span> </div> </div> </div> </div> </div> </div> <div class="col-md-6 col-lg-4"> <div class="panel panel-white no-radius"> <div class="panel-heading border-bottom"> <h4 class="panel-title">Specialization</h4> </div> <div class="panel-body"> <ul class="timeline-xs margin-top-20 margin-bottom-20"> <li class="timeline-item success"> <div class="margin-left-15"> <div class="text-muted text-small"> 2 minutes ago </div> <p> <a class="text-info" href> Steven </a> has completed his account. </p> </div> </li> <li class="timeline-item"> <div class="margin-left-15"> <div class="text-muted text-small"> 12:30 </div> <p> Staff Meeting </p> </div> </li> <li class="timeline-item danger"> <div class="margin-left-15"> <div class="text-muted text-small"> 11:11 </div> <p> Completed new layout. </p> </div> </li> <li class="timeline-item info"> <div class="margin-left-15"> <div class="text-muted text-small"> Thu, 12 Jun </div> <p> Contacted <a class="text-info" href> Microsoft </a> for license upgrades. </p> </div> </li> <li class="timeline-item"> <div class="margin-left-15"> <div class="text-muted text-small"> Tue, 10 Jun </div> <p> Started development new site </p> </div> </li> <li class="timeline-item"> <div class="margin-left-15"> <div class="text-muted text-small"> Sun, 11 Apr </div> <p> Lunch with <a class="text-info" href> Nicole </a> . </p> </div> </li> <li class="timeline-item warning"> <div class="margin-left-15"> <div class="text-muted text-small"> Wed, 25 Mar </div> <p> server Maintenance. </p> </div> </li> <li class="timeline-item warning"> <div class="margin-left-15"> <div class="text-muted text-small"> Wed, 25 Mar </div> <p> server Maintenance. </p> </div> </li> </ul> </div> <div class="panel-footer"> <div class="clearfix padding-5 padding-top-10 padding-bottom-10 space5"> <div class="col-xs-4 text-center no-padding"> <div class="border-right border-dark"> <span class="text-bold block text-extra-large">90%</span> <span class="text-light">Satisfied</span> </div> </div> <div class="col-xs-4 text-center no-padding"> <div class="border-right border-dark"> <span class="text-bold block text-extra-large">2%</span> <span class="text-light">Unsatisfied</span> </div> </div> <div class="col-xs-4 text-center no-padding"> <span class="text-bold block text-extra-large">8%</span> <span class="text-light">NA</span> </div> </div> </div> </div> </div> <div class="col-md-12 col-lg-4"> <div class="panel panel-white no-radius"> <div class="panel-heading border-bottom"> <h4 class="panel-title">Sales Performance</h4> </div> <div class="panel-body padding-20"> <div class="margin-bottom-20"> <p class="text-black"> Key strengths of sales force </p> <h3><i class="fa fa-sort-up small text-red margin-right-5"></i><span class="text-bold text-dark margin-right-10">10.6m</span><span class="text-grey">(53%)</span></h3> <p> <span class="text-light margin-right-5">Source:</span><span>CT Sales Skills Audit</span> </p> </div> <h4 class="text-center text-bold text-light">Sales skills audit</h4> <div class="text-center"> <!-- /// controller: 'PerformanceCtrl1' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div class="inline-block" ng-controller="PerformanceCtrl1"> <ui-knob value="value" options="options"></ui-knob><span class="text-white block">CPU used</span> </div> </div> <div class="margin-top-25"> <!-- /// controller: 'SalesCtrl' - localtion: assets/js/controllers/dashboardCtrl.js /// --> <div ng-controller="SalesCtrl"> <canvas class="chart chart-bar height-185" chart-data="data" chart-options="options" chart-labels="labels" chart-series="series" chart-colours="colors"></canvas> </div> </div> </div> </div> </div> </div> </div> <!-- end: FOURTH SECTION --> <!-- start: FIFTH SECTION --> <div class="container-fluid container-fullw"> <div class="row"> <div class="col-xs-12 col-md-8"> <div class="panel panel-white no-radius no-margin"> <div class="panel-heading border-light padding-30"> <div class="row"> <div class="col-lg-4 col-xs-5"> <span class="input-icon"> <input type="text" placeholder="Search posts..." id="form-field-14" class="form-control radius-10"> <i class="ti-search"></i> </span> </div> <div class="col-lg-8 col-xs-7 text-right"> <div class="btn-group margin-top-5" uib-dropdown ng-init="selected='Newest'"> <button id="split-button" type="button" class="btn btn-azure btn-sm"> Sort by: <span class="text-bold">{{selected}}</span> </button> <button type="button" class="btn btn-azure btn-sm" uib-dropdown-toggle> <span class="caret"></span> <span class="sr-only">Split button!</span> </button> <ul uib-dropdown-menu role="menu" aria-labelledby="split-button"> <li role="menuitem"> <a href="#" ng-click="selected='Newest'"> Newest </a> </li> <li role="menuitem"> <a href="#" ng-click="selected='Oldest'"> Oldest </a> </li> <li role="menuitem"> <a href="#" ng-click="selected='Approved'"> Approved </a> </li> <li role="menuitem"> <a href="#" ng-click="selected='In Review'"> In Review </a> </li> <li class="divider"></li> <li role="menuitem"> <a href="#" ng-click="selected='Declined'"> Declined </a> </li> </ul> </div> </div> </div> </div> <div class="panel-body padding-top-0"> <table class="table no-margin"> <tbody> <tr> <td class="max-width-100"> <div class="icons-effect"> <img src="assets/images/portfolio/image01_th.jpg" class="img-responsive img-rounded" alt=""> <div class="mask mask-rounded"> <div class="icons-wrapper"> <div class="icons"> <a href="#" class="icon"> <span class="fa-stack fa-2x"> <i class="fa fa-circle fa-stack-2x text-white"></i> <i class="fa fa-search fa-stack-1x text-extra-large text-light"></i> </span> </a> </div> </div> </div> </div></td> <td> <div class="padding-10"> <div class="block"> <strong>Multi-slot transclusion</strong><span class="text-muted"> has been approved</span> </div> <span class="text-small text-muted">An endorsement for </span><span class="text-azure">AngularJs</span> <div class="block margin-top-10"> <span class="label label-success">Approved</span> </div> </div></td> <td class="hidden-xs"> <div class="block"> <a href="#" class="block"> <i class="fa fa-comments text-azure"></i> Workroom </a> <a href="#" class="block"> <i class="fa fa-retweet text-green"></i> Re-Hire </a> </div></td> <td class="visible-lg"> <div class="col-xs-4 no-padding text-center"> <div class="border-right border-dark padding-5"> <small class="text-muted">Subscribers <br> <strong>156,987</strong></small> </div> </div> <div class="col-xs-4 no-padding text-center"> <div class="border-right border-dark padding-5"> <small class="text-muted">Female <br> <strong>38%</strong></small> </div> </div> <div class="col-xs-4 no-padding text-center"> <div class="padding-5"> <small class="text-muted">Male <br> <strong>62%</strong></small> </div> </div></td> </tr> <tr> <td class="max-width-100"> <div class="icons-effect"> <img src="assets/images/portfolio/image02_th.jpg" class="img-responsive img-rounded" alt=""> <div class="mask mask-rounded"> <div class="icons-wrapper"> <div class="icons"> <a href="#" class="icon"> <span class="fa-stack fa-2x"> <i class="fa fa-circle fa-stack-2x text-white"></i> <i class="fa fa-search fa-stack-1x text-extra-large text-light"></i> </span> </a> </div> </div> </div> </div></td> <td> <div class="padding-10"> <div class="block"> <strong>Command Line Interface</strong><span class="text-muted"> has been approved</span> </div> <span class="text-small text-muted">An endorsement for </span><span class="text-azure">Apple Watch</span> <div class="block margin-top-10"> <span class="label label-warning">In Review</span> </div> </div></td> <td class="hidden-xs"> <div class="block"> <a href="#" class="block"> <i class="fa fa-comments text-azure"></i> Workroom </a> <a href="#" class="block"> <i class="fa fa-retweet text-green"></i> Re-Hire </a> </div></td> <td class="visible-lg"> <div class="col-xs-4 no-padding text-center"> <div class="border-right border-dark padding-5"> <small class="text-muted">Subscribers <br> <strong>156,987</strong></small> </div> </div> <div class="col-xs-4 no-padding text-center"> <div class="border-right border-dark padding-5"> <small class="text-muted">Female <br> <strong>68%</strong></small> </div> </div> <div class="col-xs-4 no-padding text-center"> <div class="padding-5"> <small class="text-muted">Male <br> <strong>32%</strong></small> </div> </div></td> </tr> <tr> <td class="max-width-100"> <div class="icons-effect"> <img src="assets/images/portfolio/image03_th.jpg" class="img-responsive img-rounded" alt=""> <div class="mask mask-rounded"> <div class="icons-wrapper"> <div class="icons"> <a href="#" class="icon"> <span class="fa-stack fa-2x"> <i class="fa fa-circle fa-stack-2x text-white"></i> <i class="fa fa-search fa-stack-1x text-extra-large text-light"></i> </span> </a> </div> </div> </div> </div></td> <td> <div class="padding-10"> <div class="block"> <strong>Tools and Training</strong><span class="text-muted"> has been approved</span> </div> <span class="text-small text-muted">An endorsement for </span><span class="text-azure">Visual Basic</span> <div class="block margin-top-10"> <span class="label label-danger">Declined</span> </div> </div></td> <td class="hidden-xs"> <div class="block"> <a href="#" class="block"> <i class="fa fa-comments text-azure"></i> Workroom </a> <a href="#" class="block"> <i class="fa fa-retweet text-green"></i> Re-Hire </a> </div></td> <td class="visible-lg"> <div class="col-xs-4 no-padding text-center"> <div class="border-right border-dark padding-5"> <small class="text-muted">Subscribers <br> <strong>156,987</strong></small> </div> </div> <div class="col-xs-4 no-padding text-center"> <div class="border-right border-dark padding-5"> <small class="text-muted">Female <br> <strong>68%</strong></small> </div> </div> <div class="col-xs-4 no-padding text-center"> <div class="padding-5"> <small class="text-muted">Male <br> <strong>32%</strong></small> </div> </div></td> </tr> </tbody> </table> </div> <div class="panel-footer no-border padding-top-0"> <p class="no-margin"> <a href="#"><i class="fa <API key> text-green"></i></a> <span class="text-light margin-left-10">Show more details </span> </p> </div> </div> </div> <div class="col-xs-12 col-md-4"> <div class="panel panel-white no-radius"> <div class="panel-heading border-bottom"> <h4 class="panel-title">Applications</h4> </div> <div class="panel-body"> <ul class="list-group"> <li class="list-group-item no-radius no-margin no-border-top no-border-left no-border-right"> <div class="row"> <div class="col-xs-6"> <a href="#"><letter-icon data="Omega" color="#7F8C8D" size="sm" class="margin-right-5"></letter-icon> Omega</a> </div> <div class="col-xs-6"> <span class="block padding-top-10"><uib-progressbar value="89" class="progress-xs no-radius background-dark no-margin" type="purple"></uib-progressbar></span> </div> </div> </li> <li class="list-group-item no-radius no-margin no-border-top no-border-left no-border-right"> <div class="row"> <div class="col-xs-6"> <a href="#"><letter-icon data="Alpha" color="#947499" size="sm" class="margin-right-5"></letter-icon> Alpha</a> </div> <div class="col-xs-6"> <span class="block padding-top-10"><uib-progressbar value="54" class="progress-xs no-radius background-dark no-margin" type="purple"></uib-progressbar></span> </div> </div> </li> <li class="list-group-item no-radius no-margin no-border-top no-border-left no-border-right"> <div class="row"> <div class="col-xs-6"> <a href="#"><letter-icon data="Kappa" color="#5A8770" size="sm" class="margin-right-5"></letter-icon> Kappa</a> </div> <div class="col-xs-6"> <span class="block padding-top-10"><uib-progressbar value="32" class="progress-xs no-radius background-dark no-margin" type="purple"></uib-progressbar></span> </div> </div> </li> <li class="list-group-item no-radius no-margin no-border-top no-border-left no-border-right"> <div class="row"> <div class="col-xs-6"> <a href="#"><letter-icon data="Zeta" color="#5B9BD1" size="sm" class="margin-right-5"></letter-icon> Zeta</a> </div> <div class="col-xs-6"> <span class="block padding-top-10"><uib-progressbar value="32" class="progress-xs no-radius background-dark no-margin" type="purple"></uib-progressbar></span> </div> </div> </li> <li class="list-group-item no-radius no-margin no-border-top no-border-left no-border-right"> <div class="row"> <div class="col-xs-6"> <a href="#"><letter-icon data="Upsilon" color="#315777" size="sm" class="margin-right-5"></letter-icon> Upsilon</a> </div> <div class="col-xs-6"> <span class="block padding-top-10"><uib-progressbar value="78" class="progress-xs no-radius background-dark no-margin" type="purple"></uib-progressbar></span> </div> </div> </li> <li class="list-group-item no-radius no-margin no-border"> <div class="row"> <div class="col-xs-6"> <a href="#"><letter-icon data="Sigma" color="#ABA556" size="sm" class="margin-right-5"></letter-icon> Sigma</a> </div> <div class="col-xs-6"> <span class="block padding-top-10"><uib-progressbar value="78" class="progress-xs no-radius background-dark no-margin" type="purple"></uib-progressbar></span> </div> </div> </li> </ul> </div> <div class="panel-footer padding-20 no-border"> <p class="no-margin"> <a href="#"><i class="fa <API key> text-green"></i></a> <span class="text-light margin-left-10">Show more details </span> </p> </div> </div> </div> </div> </div> <!-- end: FIFTH SECTION -->
<HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1"> <META NAME="GENERATOR" CONTENT="Mozilla/4.08 [en] (X11; I; FreeBSD 2.2.8-19990120-SNAP i386) [Netscape]"> </HEAD> <BODY> <H2> <A NAME="Compatibility Commands"></A>Compatibility Commands</H2> The compatibility commands for old Dbm and Ndbm are described in the <A HREF="../../docs/api_c/dbm.html">dbm</A> manpage. <P><B>> berkdb dbminit <I>filename</I></B> <P>This command will invoke the dbminit function.&nbsp;&nbsp; <B><I>Filename</I></B> is used as the name of the database. <P> <HR WIDTH="100%"><B>> berkdb dbmclose</B> <P>This command will invoke the dbmclose function. <P> <HR WIDTH="100%"><B>> berkdb fetch <I>key</I></B> <P>This command will invoke the fetch function.&nbsp;&nbsp; It will return the data associated with the given <B><I>key </I></B>or a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb store <I>key data</I></B> <P>This command will invoke the store function.&nbsp;&nbsp; It will store the <B><I>key/data</I></B> pair.&nbsp; It will return a 0 on success or throw a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb delete <I>key</I></B> <P>This command will invoke the deletet function.&nbsp;&nbsp; It will delete the <B><I>key</I></B> from the database.&nbsp; It will return a 0 on success or throw a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb firstkey</B> <P>This command will invoke the firstkey function.&nbsp;&nbsp; It will return the first key in the database or a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb nextkey <I>key</I></B> <P>This command will invoke the nextkey function.&nbsp;&nbsp; It will return the next key after the given <B><I>key</I></B> or a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb hcreate <I>nelem</I></B> <P>This command will invoke the hcreate function with <B><I>nelem</I></B> elements.&nbsp; It will return a 0 on success or a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb hsearch <I>key data action</I></B> <P>This command will invoke the hsearch function with <B><I>key</I></B> and <B><I>data</I></B>.&nbsp; The <B><I>action</I></B> must be either <B>find</B> or <B>enter</B>.&nbsp; If it is <B>find</B>, it will return the resultant data.&nbsp; If it is <B>enter</B>, it will return a 0 on success or a Tcl error. <P> <HR WIDTH="100%"><B>> berkdb hdestroy</B> <P>This command will invoke the hdestroy function.&nbsp; It will return a 0. <HR WIDTH="100%"><B>> berkdb ndbm_open [-create] [-rdonly] [-truncate] [-mode <I>mode</I>] [--] <I>filename</I></B> <P>This command will invoke the dbm_open function.&nbsp;&nbsp;&nbsp; After it successfully gets a handle to a database, we bind it to a new Tcl command of the form <B><I>ndbmX, </I></B>where X is an integer starting at 0 (e.g. <B>ndbm0, ndbm1, </B>etc).&nbsp; We use the <I><API key>()&nbsp;</I> to create the top level database function.&nbsp; It is through this handle that the user can access all of the commands described below.&nbsp; Internally, the database handle is sent as the <I>ClientData</I> portion of the new command set so that all future database calls access the appropriate handle. <P>The arguments are: <UL> <LI> <B>-- </B>- Terminate the list of options and use remaining arguments as the file or subdb names (thus allowing the use of filenames beginning with a dash '-')</LI> <LI> <B>-create</B> selects the O_CREAT flag&nbsp; to create underlying files</LI> <LI> <B>-rdonly</B> selects the O_RDONLY flag for opening in read-only mode</LI> <LI> <B>-truncate</B> selects the O_TRUNC flag to truncate the database</LI> <LI> <B>-mode<I> mode</I></B> specifies the mode for created files</LI> <LI> <B><I>filename</I></B> indicates the name of the database</LI> </UL> <P><BR> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> close</B> <P>This command closes the database and renders the handle invalid.&nbsp;&nbsp; This command directly translates to the dbm_close function call.&nbsp; It returns either a 0 (for success),&nbsp; or it throws a Tcl error with a system message. <P>Additionally, since the handle is no longer valid, we will call <I>Tcl_DeleteCommand() </I>so that further uses of the handle will be dealt with properly by Tcl itself.&nbsp; <HR WIDTH="100%"> <BR><B>> &lt;ndbm> clearerr</B> <P>This command clears errors&nbsp; the database.&nbsp;&nbsp; This command directly translates to the dbm_clearerr function call.&nbsp; It returns either a 0 (for success),&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> delete <I>key</I></B> <P>This command deletes the <B><I>key</I></B> from thedatabase.&nbsp;&nbsp; This command directly translates to the dbm_delete function call.&nbsp; It returns either a 0 (for success),&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> dirfno</B> <P>This command directly translates to the dbm_dirfno function call.&nbsp; It returns either resultts,&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> error</B> <P>This command returns the last error.&nbsp;&nbsp; This command directly translates to the dbm_error function call.&nbsp; It returns an error string.. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> fetch <I>key</I></B> <P>This command gets the given <B><I>key</I></B> from the database.&nbsp;&nbsp; This command directly translates to the dbm_fetch function call.&nbsp; It returns either the data,&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> firstkey</B> <P>This command returns the first key in the database.&nbsp;&nbsp; This command directly translates to the dbm_firstkey function call.&nbsp; It returns either the key,&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> nextkey</B> <P>This command returns the next key in the database.&nbsp;&nbsp; This command directly translates to the dbm_nextkey function call.&nbsp; It returns either the key,&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> pagfno</B> <P>This command directly translates to the dbm_pagfno function call.&nbsp; It returns either resultts,&nbsp; or it throws a Tcl error with a system message. <BR> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> rdonly</B> <P>This command changes the database to readonly.&nbsp;&nbsp; This command directly translates to the dbm_rdonly function call.&nbsp; It returns either a 0 (for success),&nbsp; or it throws a Tcl error with a system message. <P> <HR WIDTH="100%"> <BR><B>> &lt;ndbm> store <I>key data </I>insert|replace</B> <P>This command puts the given <B><I>key</I></B> and <B><I>data</I></B> pair into the database.&nbsp;&nbsp; This command directly translates to the dbm_store function call.&nbsp; It will either <B>insert</B> or <B>replace</B> the data based on the action given in the third argument.&nbsp; It returns either a 0 (for success),&nbsp; or it throws a Tcl error with a system message. <BR> <HR WIDTH="100%"> </BODY> </HTML>
package org.esa.snap.dataio.netcdf.metadata.profiles.cf; import ucar.nc2.Attribute; import java.util.List; import java.util.StringTokenizer; /** * Class to extract HDF originated geo info * * @author olafd */ public class <API key> { private List<Attribute> netcdfAttributes; private int xDim = -1; private int yDim = -1; private double ulLon; private double ulLat; private double lrLon; private double lrLat; private String projection; public <API key>(List<Attribute> netcdfAttributes) { this.netcdfAttributes = netcdfAttributes; } public void extractInfo() throws <API key> { Attribute structMetadataAttr = null; for (Attribute att : netcdfAttributes) { if (att.getShortName().startsWith("StructMetadata")) { structMetadataAttr = att; break; } } final String <API key> = structMetadataAttr.getValue(0).toString(); final String[] strings = <API key>.split("\n"); for (String string : strings) { string = string.replaceAll("\t", ""); System.out.println(string); final StringTokenizer st = new StringTokenizer(string, "\n", false); while (st.hasMoreTokens()) { final String s = st.nextToken(); System.out.println("s = " + s); final String[] sSplit = s.split("="); if (sSplit != null && sSplit.length == 2) { final String sArgString = sSplit[0]; final String sValString = sSplit[1]; if (sArgString.equalsIgnoreCase("projection")) { projection = sValString; } else if (sArgString.equalsIgnoreCase("xdim")) { try { xDim = Integer.parseInt(sValString); } catch (<API key> e) { System.out.println("Cannot extract XDIM value: " + e.getMessage()); } } else if (sArgString.equalsIgnoreCase("ydim")) { try { yDim = Integer.parseInt(sValString); } catch (<API key> e) { System.out.println("Cannot extract YDIM value: " + e.getMessage()); } } else if (sArgString.toLowerCase().contains("upperleft")) { try { final String[] ulNumberStrings = sValString.substring(1, sValString.length() - 1).split(","); ulLon = Double.parseDouble(ulNumberStrings[0]); ulLat = Double.parseDouble(ulNumberStrings[1]); } catch (<API key> e) { System.out.println("Cannot extract UPPERLEFT values: " + e.getMessage()); } } else if (sArgString.toLowerCase().contains("lowerright")) { try { final String[] lrNumberStrings = sValString.substring(1, sValString.length() - 1).split(","); lrLon = Double.parseDouble(lrNumberStrings[0]); lrLat = Double.parseDouble(lrNumberStrings[1]); } catch (<API key> e) { System.out.println("Cannot extract LOWERRIGHT values: " + e.getMessage()); } } } } } } public int getxDim() { return xDim; } public int getyDim() { return yDim; } public double getUlLon() { return ulLon; } public double getUlLat() { return ulLat; } public double getLrLon() { return lrLon; } public double getLrLat() { return lrLat; } public String getProjection() { return projection; } }
`post_url` ** `use_http` ** Q HTTP POST JSON `X-Self-ID` QQ http POST / HTTP/1.1 X-Self-ID: 123456 `secret` HMAC http POST / HTTP/1.1 X-Signature: sha1=<SHA1-like> X-Self-ID: 123456 `secret` HTTP HMAC SHA1 HTTP API HMAC [](https://zh.wikipedia.org/zh-cn/%E9%87%91%E9%91%B0%E9%9B%9C%E6%B9%8A%E8%A8%8A%E6%81%AF%E9%91%91%E5%88%A5%E7%A2%BC) HMAC SHA1 # Python + Flask python import hmac from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['POST']) def receive(): sig = hmac.new(b'<your-key>', request.get_data(), 'sha1').hexdigest() received_sig = request.headers['X-Signature'][len('sha1='):] if sig == received_sig: pass else: pass # Node.js + Koa js const crypto = require('crypto'); const secret = 'some-secret'; // Koa context ctx.assert(ctx.request.headers['x-signature'] !== undefined, 401); const hmac = crypto.createHmac('sha1', secret); hmac.update(ctx.request.rawBody); const sig = hmac.digest('hex'); ctx.assert(ctx.request.headers['x-signature'] === `sha1=${sig}`, 403); `post_type` | | | | | `message` | | | `notice` | | | `request` | | | | | | | | `time` | number (int64) | | | `self_id` | number (int64) | QQ | `time` Q `time` `notice` `request` `time` Q `message` `time` HTTP 204 JSON `Content-Type` `application/json` JSON **** Q ** `block` ** boolean`true` json { "block": true } JSON HTTP API `block` `post_type` `notice` `block` JSON `string``number` `message` `message` `post_message_format` `post_message_format` `string` `array` `message` [](/Message) [](/EventFilter) | | | | | | | `post_type` | string | `message` | | | `message_type` | string | `private` | | | `sub_type` | string | `friend``group``discuss``other` | `friend` `group``discuss` | | `message_id` | number (int32) | - | ID | | `user_id` | number (int64) | - | QQ | | `message` | message | - | | | `raw_message` | string | - | | | `font` | number (int32) | - | | | `sender` | object | - | | `sender` | | | | | | `user_id` | number (int64) | QQ | | `nickname` | string | | | `sex` | string | `male` `female` `unknown` | | `age` | number (int32) | | `sender` json { "time": 1515204254, "post_type": "message", "message_type": "private", "sub_type": "friend", "message_id": 12, "user_id": 12345678, "message": "", "raw_message": "", "font": 456, "sender": { "nickname": "", "sex": "male", "age": 18 } } | | | | | | | `reply` | message | | | | `auto_escape` | boolean | CQ `reply` | | | | | | | | | `post_type` | string | `message` | | | `message_type` | string | `group` | | | `sub_type` | string | `normal``anonymous``notice` | `normal` `anonymous` `notice` | | `message_id` | number (int32) | - | ID | | `group_id` | number (int64) | - | | | `user_id` | number (int64) | - | QQ | | `anonymous` | object | - | null | | `message` | message | - | | | `raw_message` | string | - | | | `font` | number (int32) | - | | | `sender` | object | - | | `anonymous` | | | | | | `id` | number (int64) | ID | | `name` | string | | | `flag` | string | flag API | `sender` | | | | | | `user_id` | number (int64) | QQ | | `nickname` | string | | | `card` | string | | | `sex` | string | `male` `female` `unknown` | | `age` | number (int32) | | | `area` | string | | | `level` | string | | | `role` | string | `owner` `admin` `member` | | `title` | string | | `sender` | | | | | | | `reply` | message | | | | `auto_escape` | boolean | CQ `reply` | | | `at_sender` | boolean | at | at | | `delete` | boolean | | | | `kick` | boolean | **** | | | `ban` | boolean | `ban_duration` | | | `ban_duration` | number | | 30 | | | | | | | | `post_type` | string | `message` | | | `message_type` | string | `discuss` | | | `message_id` | number (int32) | - | ID | | `discuss_id` | number (int64) | - | ID | | `user_id` | number (int64) | - | QQ | | `message` | message | - | | | `raw_message` | string | - | | | `font` | number (int32) | - | | | `sender` | object | - | | `sender` | | | | | | `user_id` | number (int64) | QQ | | `nickname` | string | | | `sex` | string | `male` `female` `unknown` | | `age` | number (int32) | | | | | | | | | `reply` | message | | | | `auto_escape` | boolean | CQ `reply` | | | `at_sender` | boolean | at | at | ** Q ** | | | | | | | `post_type` | string | `notice` | | | `notice_type` | string | `group_upload` | | | `group_id` | number (int64) | - | | | `user_id` | number (int64) | - | QQ | | `file` | object | - | | `file` | | | | | | `id` | string | ID | | `name` | string | | | `size` | number (int64) | | | `busid` | number (int64) | busid | | | | | | | | `post_type` | string | `notice` | | | `notice_type` | string | `group_admin` | | | `sub_type` | string | `set``unset` | | | `group_id` | number (int64) | - | | | `user_id` | number (int64) | - | QQ | | | | | | | | `post_type` | string | `notice` | | | `notice_type` | string | `group_decrease` | | | `sub_type` | string | `leave``kick``kick_me` | | | `group_id` | number (int64) | - | | | `operator_id` | number (int64) | - | QQ `user_id` | | `user_id` | number (int64) | - | QQ | | | | | | | | `post_type` | string | `notice` | | | `notice_type` | string | `group_increase` | | | `sub_type` | string | `approve``invite` | | | `group_id` | number (int64) | - | | | `operator_id` | number (int64) | - | QQ | | `user_id` | number (int64) | - | QQ | | | | | | | | `post_type` | string | `notice` | | | `notice_type` | string | `friend_add` | | | `user_id` | number (int64) | - | QQ | | | | | | | | `post_type` | string | `request` | | | `request_type` | string | `friend` | | | `user_id` | number (int64) | - | QQ | | `comment` | string | - | | | `flag` | string | - | flag API | | | | | | | | `approve` | boolean | | | | `remark` | string | | | | | | | | | | `post_type` | string | `request` | | | `request_type` | string | `group` | | | `sub_type` | string | `add``invite` | | | `group_id` | number (int64) | - | | | `user_id` | number (int64) | - | QQ | | `comment` | string | - | | | `flag` | string | - | flag API | | | | | | | | `approve` | boolean | | | | `reason` | string | | | Q QQ Q QQ `post_type` `meta_event` ** HTTP `post_url`WebSocket WebSocket ** | | | | | | | `post_type` | string | `meta_event` | | | `meta_event_type` | string | `lifecycle` | | | `sub_type` | string | `enable``disable` | | `enable_heartbeat` `true` `heartbeat_interval` | | | | | | | `post_type` | string | `meta_event` | | | `meta_event_type` | string | `heartbeat` | | | `status` | object | - | | `status` [`get_status` ](/API
#include "objects.h" #include "errors.h" #include "game.h" #include "locations.h" #include "text.h" #include "variables.h" QSPObj qspCurObjects[QSP_MAXOBJECTS]; int qspCurObjectsCount = 0; int qspCurSelObject = -1; QSP_BOOL qspIsObjectsChanged = QSP_FALSE; QSP_BOOL qspCurIsShowObjs = QSP_TRUE; static void qspRemoveObject(int); void qspClearObjects(QSP_BOOL isFirst) { int i; if (!isFirst && qspCurObjectsCount) { for (i = 0; i < qspCurObjectsCount; ++i) { if (qspCurObjects[i].Image) free(qspCurObjects[i].Image); free(qspCurObjects[i].Desc); } qspIsObjectsChanged = QSP_TRUE; } qspCurObjectsCount = 0; qspCurSelObject = -1; } void <API key>() { QSPVariant v; QSP_CHAR **objs; int i, oldRefreshCount, oldCount = qspCurObjectsCount; if (oldCount) { objs = (QSP_CHAR **)malloc(oldCount * sizeof(QSP_CHAR *)); for (i = 0; i < oldCount; ++i) qspAddText(objs + i, qspCurObjects[i].Desc, 0, -1, QSP_TRUE); qspClearObjects(QSP_FALSE); v.IsStr = QSP_TRUE; oldRefreshCount = qspRefreshCount; for (i = 0; i < oldCount; ++i) { QSP_STR(v) = objs[i]; <API key>(QSP_FMT("ONOBJDEL"), &v, 1); if (qspRefreshCount != oldRefreshCount || qspErrorNum) break; } qspFreeStrs(objs, oldCount); } } static void qspRemoveObject(int index) { QSPVariant name; if (index < 0 || index >= qspCurObjectsCount) return; if (qspCurSelObject >= index) qspCurSelObject = -1; name.IsStr = QSP_TRUE; QSP_STR(name) = qspCurObjects[index].Desc; if (qspCurObjects[index].Image) free(qspCurObjects[index].Image); --qspCurObjectsCount; while (index < qspCurObjectsCount) { qspCurObjects[index] = qspCurObjects[index + 1]; ++index; } qspIsObjectsChanged = QSP_TRUE; <API key>(QSP_FMT("ONOBJDEL"), &name, 1); free(QSP_STR(name)); } int qspObjIndex(QSP_CHAR *name) { int i, objNameLen, bufSize; QSP_CHAR *uName, *buf; if (!qspCurObjectsCount) return -1; qspUpperStr(uName = qspGetNewText(name, -1)); bufSize = 32; buf = (QSP_CHAR *)malloc(bufSize * sizeof(QSP_CHAR)); for (i = 0; i < qspCurObjectsCount; ++i) { objNameLen = qspStrLen(qspCurObjects[i].Desc); if (objNameLen >= bufSize) { bufSize = objNameLen + 8; buf = (QSP_CHAR *)realloc(buf, bufSize * sizeof(QSP_CHAR)); } qspStrCopy(buf, qspCurObjects[i].Desc); qspUpperStr(buf); if (!qspStrsComp(buf, uName)) { free(uName); free(buf); return i; } } free(uName); free(buf); return -1; } QSP_BOOL <API key>(QSPVariant *args, int count, QSP_CHAR **jumpTo, int extArg) { QSPObj *obj; int i, objInd; QSP_CHAR *imgPath; if (count == 3) { objInd = QSP_NUM(args[2]) - 1; if (objInd < 0 || objInd > qspCurObjectsCount) return QSP_FALSE; } else objInd = qspCurObjectsCount; if (qspCurObjectsCount == QSP_MAXOBJECTS) { qspSetError(<API key>); return QSP_FALSE; } if (qspCurSelObject >= objInd) qspCurSelObject = -1; if (count >= 2 && qspIsAnyString(QSP_STR(args[1]))) imgPath = <API key>(QSP_STR(args[1])); else imgPath = nullptr; for (i = qspCurObjectsCount; i > objInd; --i) qspCurObjects[i] = qspCurObjects[i - 1]; ++qspCurObjectsCount; obj = qspCurObjects + objInd; obj->Image = imgPath; obj->Desc = qspGetNewText(QSP_STR(args[0]), -1); qspIsObjectsChanged = QSP_TRUE; if (count == 3) count = 2; <API key>(QSP_FMT("ONOBJADD"), args, count); return QSP_FALSE; } QSP_BOOL qspStatementDelObj(QSPVariant *args, int count, QSP_CHAR **jumpTo, int extArg) { switch (extArg) { case 0: qspRemoveObject(qspObjIndex(QSP_STR(args[0]))); break; case 1: if (count) qspRemoveObject(QSP_NUM(args[0]) - 1); else <API key>(); break; } return QSP_FALSE; } QSP_BOOL <API key>(QSPVariant *args, int count, QSP_CHAR **jumpTo, int extArg) { qspCurSelObject = -1; return QSP_FALSE; }
#ifndef <API key> #define <API key> #include "<API key>.h" class <API key> : public <API key> { Q_OBJECT public: <API key>(Qt::Orientation orient, QWidget *parent = 0); virtual ~<API key>(); virtual void triggerAction(QAction *action); private: <API key> *addActionButton(QAction *action); private slots: void buttonClicked(); }; #endif // <API key>
package cz.incad.Kramerius.backend.guice; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import com.google.inject.Injector; /** * Base servlet for injecting. * @author pavels * TODO: Do it by guice way */ public class GuiceServlet extends HttpServlet { @Override public void init() throws ServletException { super.init(); Injector injector = getInjector(); injector.injectMembers(this); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); Injector injector = getInjector(); injector.injectMembers(this); } protected Injector getInjector() { return (Injector) getServletContext().getAttribute(Injector.class.getName()); } }
#region using System; using System.Collections.Generic; using LeagueSharp; using LeagueSharp.Common; using SharpDX; #endregion namespace Sion { internal class Program { private static Menu Config; public static Orbwalking.Orbwalker Orbwalker; public static Spell Q; public static Spell E; public static Vector2 QCastPos = new Vector2(); private static void Main(string[] args) { CustomEvents.Game.OnGameLoad += Game_OnGameLoad; } private static void Game_OnGameLoad(EventArgs args) { if (ObjectManager.Player.BaseSkinName != "Sion") { return; } //Spells Q = new Spell(SpellSlot.Q, 1050); Q.SetSkillshot(0.6f, 100f, float.MaxValue, false, SkillshotType.SkillshotLine); Q.SetCharged("SionQ", "SionQ", 500, 720, 0.5f); E = new Spell(SpellSlot.E, 800); E.SetSkillshot(0.25f, 80f, 1800, false, SkillshotType.SkillshotLine); //Make the menu Config = new Menu("Sion", "Sion", true); //Orbwalker submenu Config.AddSubMenu(new Menu("Orbwalking", "Orbwalking")); //Add the target selector to the menu as submenu. var targetSelectorMenu = new Menu("Target Selector", "Target Selector"); TargetSelector.AddToMenu(targetSelectorMenu); Config.AddSubMenu(targetSelectorMenu); //Load the orbwalker and add it to the menu as submenu. Orbwalker = new Orbwalking.Orbwalker(Config.SubMenu("Orbwalking")); //Combo menu: Config.AddSubMenu(new Menu("Combo", "Combo")); Config.SubMenu("Combo").AddItem(new MenuItem("UseQCombo", "Use Q").SetValue(true)); Config.SubMenu("Combo").AddItem(new MenuItem("UseWCombo", "Use W").SetValue(true)); Config.SubMenu("Combo").AddItem(new MenuItem("UseECombo", "Use E").SetValue(true)); Config.SubMenu("Combo") .AddItem( new MenuItem("ComboActive", "Combo!").SetValue( new KeyBind(Config.Item("Orbwalk").GetValue<KeyBind>().Key, KeyBindType.Press))); Config.AddSubMenu(new Menu("R", "R")); Config.SubMenu("R").AddItem(new MenuItem("AntiCamLock", "Avoid locking camera").SetValue(true)); Config.SubMenu("R").AddItem(new MenuItem("MoveToMouse", "Move to mouse (Exploit)").SetValue(false)); //Disabled by default since its not legit Keepo Config.AddToMainMenu(); Game.PrintChat("Sion Loaded!"); Game.OnUpdate += Game_OnGameUpdate; Game.OnProcessPacket += <API key>; Drawing.OnDraw += Drawing_OnDraw; Obj_AI_Base.OnProcessSpellCast += <API key>; } private static void <API key>(Obj_AI_Base sender, <API key> args) { if (sender.IsMe && args.SData.Name == "SionQ") { QCastPos = args.End.To2D(); } } private static void Drawing_OnDraw(EventArgs args) { Utility.DrawCircle(ObjectManager.Player.Position, Q.Range, System.Drawing.Color.White); } private static void <API key>(GamePacketEventArgs args) { if (Config.Item("AntiCamLock").GetValue<bool>() && args.PacketData[0] == 0x83 && args.PacketData[7] == 0x47 && args.PacketData[8] == 0x47) { args.Process = false; } } private static void Game_OnGameUpdate(EventArgs args) { //Casting R if (ObjectManager.Player.HasBuff("SionR")) { if (Config.Item("MoveToMouse").GetValue<bool>()) { var p = ObjectManager.Player.Position.To2D().Extend(Game.CursorPos.To2D(), 500); ObjectManager.Player.IssueOrder(GameObjectOrder.MoveTo, p.To3D()); } return; } if (Config.Item("ComboActive").GetValue<KeyBind>().Active) { var qTarget = TargetSelector.GetTarget( !Q.IsCharging ? Q.ChargedMaxRange / 2 : Q.ChargedMaxRange, TargetSelector.DamageType.Physical); var eTarget = TargetSelector.GetTarget(E.Range, TargetSelector.DamageType.Physical); if (qTarget != null && Config.Item("UseQCombo").GetValue<bool>()) { if (Q.IsCharging) { var start = ObjectManager.Player.ServerPosition.To2D(); var end = start.Extend(QCastPos, Q.Range); var direction = (end - start).Normalized(); var normal = direction.Perpendicular(); var points = new List<Vector2>(); var hitBox = qTarget.BoundingRadius; points.Add(start + normal * (Q.Width + hitBox)); points.Add(start - normal * (Q.Width + hitBox)); points.Add(end + Q.ChargedMaxRange * direction - normal * (Q.Width + hitBox)); points.Add(end + Q.ChargedMaxRange * direction + normal * (Q.Width + hitBox)); for (var i = 0; i <= points.Count - 1; i++) { var A = points[i]; var B = points[i == points.Count - 1 ? 0 : i + 1]; if (qTarget.ServerPosition.To2D().Distance(A, B, true, true) < 50 * 50) { Q.Cast(qTarget, true); } } return; } if (Q.IsReady()) { Q.StartCharging(qTarget.ServerPosition); } } if (qTarget != null && Config.Item("UseWCombo").GetValue<bool>()) { ObjectManager.Player.Spellbook.CastSpell(SpellSlot.W, ObjectManager.Player); } if (eTarget != null && Config.Item("UseECombo").GetValue<bool>()) { E.Cast(eTarget); } } } } }
package com.amaze.filemanager.ui.notifications; import static android.app.NotificationManager.IMPORTANCE_HIGH; import static android.app.NotificationManager.IMPORTANCE_MIN; import static android.os.Build.VERSION_CODES.KITKAT; import static android.os.Build.VERSION_CODES.P; import static com.amaze.filemanager.ui.notifications.<API key>.CHANNEL_FTP_ID; import static com.amaze.filemanager.ui.notifications.<API key>.CHANNEL_NORMAL_ID; import static com.amaze.filemanager.ui.notifications.<API key>.TYPE_FTP; import static com.amaze.filemanager.ui.notifications.<API key>.TYPE_NORMAL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.robolectric.Shadows.shadowOf; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.annotation.Config; import org.robolectric.shadows.<API key>; import com.amaze.filemanager.R; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.os.Build; import androidx.core.app.NotificationCompat; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; @RunWith(AndroidJUnit4.class) @Config(sdk = {KITKAT, P}) public class <API key> { private Context context; private NotificationManager notificationManager; private <API key> <API key>; @Before public void setUp() { context = ApplicationProvider.<API key>(); notificationManager = (NotificationManager) context.getSystemService(Context.<API key>); <API key> = shadowOf(notificationManager); } @After public void tearDown() { notificationManager.cancelAll(); } @Test(expected = <API key>.class) public void <API key>() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_NORMAL_ID); <API key>.setMetadata(context, builder, -1); <API key>.setMetadata(context, builder, 2); <API key>.setMetadata(context, builder, Integer.MAX_VALUE); builder = new NotificationCompat.Builder(context, CHANNEL_FTP_ID); <API key>.setMetadata(context, builder, -1); <API key>.setMetadata(context, builder, 2); <API key>.setMetadata(context, builder, Integer.MAX_VALUE); } @Test @Config(sdk = {KITKAT}) // max sdk is N public void <API key>() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_NORMAL_ID) .setContentTitle(context.getString(R.string.waiting_title)) .setContentText(context.getString(R.string.waiting_content)) .setAutoCancel(false) .setSmallIcon(R.drawable.<API key>) .setProgress(0, 0, true); <API key>.setMetadata(context, builder, TYPE_NORMAL); Notification result = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { assertEquals(Notification.CATEGORY_SERVICE, result.category); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { assertEquals(Notification.PRIORITY_MIN, result.priority); } else { assertEquals(Notification.PRIORITY_DEFAULT, result.priority); } } @Test @Config(sdk = {KITKAT}) // max sdk is N public void testFtpNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_FTP_ID) .setContentTitle("FTP server test") .setContentText("FTP listening at 127.0.0.1:22") .setSmallIcon(R.drawable.ic_ftp_light) .setTicker(context.getString(R.string.ftp_notif_starting)) .setOngoing(true) .setOnlyAlertOnce(true); <API key>.setMetadata(context, builder, TYPE_FTP); Notification result = builder.build(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { assertEquals(Notification.CATEGORY_SERVICE, result.category); assertEquals(Notification.VISIBILITY_PUBLIC, result.visibility); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { assertEquals(Notification.PRIORITY_MAX, result.priority); } else { assertEquals(Notification.PRIORITY_DEFAULT, result.priority); } } @Test @Config(sdk = {P}) // min sdk is O public void <API key>() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_NORMAL_ID); <API key>.setMetadata(context, builder, TYPE_NORMAL); List<Object> channels = <API key>.<API key>(); assertNotNull(channels); assertEquals(1, channels.size()); NotificationChannel channel = (NotificationChannel) channels.get(0); assertEquals(IMPORTANCE_MIN, channel.getImportance()); assertEquals(CHANNEL_NORMAL_ID, channel.getId()); assertEquals(context.getString(R.string.channel_name_normal), channel.getName()); assertEquals(context.getString(R.string.<API key>), channel.getDescription()); } @Test @Config(sdk = {P}) // min sdk is O public void <API key>() { NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_FTP_ID); <API key>.setMetadata(context, builder, TYPE_FTP); List<Object> channels = <API key>.<API key>(); assertNotNull(channels); assertEquals(1, channels.size()); NotificationChannel channel = (NotificationChannel) channels.get(0); assertEquals(IMPORTANCE_HIGH, channel.getImportance()); assertEquals(CHANNEL_FTP_ID, channel.getId()); assertEquals(context.getString(R.string.channel_name_ftp), channel.getName()); assertEquals(context.getString(R.string.<API key>), channel.getDescription()); } }
from __future__ import unicode_literals from __future__ import absolute_import from django.core.urlresolvers import reverse from django.test import TestCase from django.test.client import Client from django.template import Context, Template try: from django.test import override_settings except ImportError: from django.test.utils import override_settings from wiki.models import URLPath class WebTestBase(TestCase): def setUp(self): super(TestCase, self).setUp() try: from django.contrib.auth import get_user_model User = get_user_model() except ImportError: from django.contrib.auth.models import User self.superuser1 = User.objects.create_superuser( 'admin', 'nobody@example.com', 'secret' ) self.c = c = Client() c.login(username='admin', password='secret') class ArticleTestBase(WebTestBase): """Base class for web client tests, that sets up initial root article.""" def setUp(self): super(ArticleTestBase, self).setUp() response = self.c.post( reverse('wiki:root_create'), {'content': 'root article content', 'title': 'Root Article'}, follow=True ) self.assertEqual(response.status_code, 200) # sanity check self.root_article = URLPath.root().article self.example_data = { 'content': 'The modified text', 'current_revision': '1', 'preview': '1', # 'save': '1', # probably not too important 'summary': 'why edited', 'title': 'wiki test' } def get_by_path(self, path): """ Get the article response for the path. Example: self.get_by_path("Level1/Slug2/").title """ return self.c.get(reverse('wiki:get', kwargs={'path': path})) class TemplateTestCase(TestCase): @property def template(self): raise Exception("Not implemented") def render(self, context): return Template(self.template).render(Context(context)) # See class <API key>(override_settings): def enable(self): super(<API key>, self).enable() self.<API key>() def disable(self): super(<API key>, self).disable() self.<API key>() def <API key>(self): from imp import reload from wiki.conf import settings reload(settings)
// SimpleScreen.cpp #include "stdafx.h" #include "SimpleScreen.h" using namespace std; // Point2D Point2D::Point2D() { x = -1; y = -1; } Point2D::Point2D(double x, double y) { this->x = x; this->y = y; } Point2D::~Point2D() { } // Point3D Point3D::Point3D() { } Point3D::Point3D(double x, double y, double z) { this->x = x; this->y = y; this->z = z; } Point3D::~Point3D() { } // UnitVector UnitVector::UnitVector() { } UnitVector::UnitVector(Point3D* tail, Point3D* tip) { x = tip->x - tail->x; y = tip->y - tail->y; z = tip->z - tail->z; normalize(); } UnitVector::~UnitVector() { } void UnitVector::normalize() { double magnitude = sqrt(x * x + y * y + z * z); x /= magnitude; y /= magnitude; z /= magnitude; } UnitVector* UnitVector::crossProduct(UnitVector* other) { UnitVector* C = new UnitVector(); C->x = this->y * other->z - this->z * other->y; C->y = this->z * other->x - this->x * other->z; C->z = this->x * other->y - this->y * other->x; C->normalize(); return C; } double UnitVector::dotProduct(UnitVector* other) { return this->x * other->x + this->y * other->y + this->z * other->z; } // PointSet PointSet::PointSet() { points = new vector<Point2D*>(); } PointSet::~PointSet() { points->clear(); delete points; } Point2D* PointSet::at(size_t i) { return points->at(i); } void PointSet::clear() { points->clear(); } void PointSet::add(double x, double y) { points->push_back(new Point2D(x, y)); } void PointSet::add(Point2D* pt) { points->push_back(pt); } size_t PointSet::size() { return points->size(); } // PointSet3D PointSet3D::PointSet3D() { points = new vector<Point3D*>(); } PointSet3D::~PointSet3D() { points->clear(); delete points; } Point3D* PointSet3D::at(size_t i) { return points->at(i); } void PointSet3D::clear() { points->clear(); } void PointSet3D::add(double x, double y, double z) { points->push_back(new Point3D(x, y, z)); } void PointSet3D::add(Point3D* p3d) { points->push_back(p3d); } size_t PointSet3D::size() { return points->size(); } // Rectangle Rectangle::Rectangle() { } Rectangle::Rectangle(double xMin, double yMin, double xMax, double yMax) { // Normalize the rectangle if necessary double width = (xMax >= xMin) ? xMax - xMin : xMin - xMax; double height = (yMax >= yMin) ? yMax - yMin : yMin - yMax; this->xMin = (xMax >= xMin) ? xMin : xMax; this->xMax = this->xMin + width; this->yMin = (yMax >= yMin) ? yMin : yMax; this->yMax = this->yMin + height; } Rectangle::~Rectangle() { } void Rectangle::Resize(double width, double height) { // TODO: Ensure rectangle preserves aspect ratio (width / height) // Right now it ensures the rectangle is square double w = xMax - xMin; double h = yMax - yMin; if (w > h) yMax = yMin + w; else xMax = xMin + h; } //Facet Facet::Facet() { points = new PointSet3D(); } Facet::Facet(PointSet3D* allVertices, vector<size_t> vertexNumbers) :Facet() { for (size_t v : vertexNumbers) points->add(allVertices->at(v)); } Facet::~Facet() { points->clear(); delete points; } Point3D* Facet::at(size_t i) { return points->at(i); } PointSet3D* Facet::all() { return points; } void Facet::clear() { points->clear(); } size_t Facet::size() { return points->size(); } Point3D* Facet::center() { int count = points->size(); double sumX{}, sumY{}, sumZ{}; for (int i{}; i < count; i++) { sumX += points->at(i)->x; sumY += points->at(i)->y; sumZ += points->at(i)->z; } return new Point3D(sumX / count, sumY / count, sumZ / count); } UnitVector* Facet::surfaceNormal() { UnitVector* vectorA = new UnitVector(points->at(0), points->at(1)); UnitVector* vectorB = new UnitVector(points->at(0), points->at(2)); return vectorA->crossProduct(vectorB); } // FacetSet FacetSet::FacetSet() { facets = new vector<Facet*>(); } FacetSet::~FacetSet() { facets->clear(); delete facets; } Facet* FacetSet::at(size_t i) { return facets->at(i); } PointSet3D* FacetSet::vertices(size_t facetNumber) { return facets->at(facetNumber)->all(); } void FacetSet::add(PointSet3D* allVertices, vector<size_t> vertexNumbers) { facets->push_back(new Facet(allVertices, vertexNumbers)); } void FacetSet::clear() { facets->clear(); } size_t FacetSet::size() { return facets->size(); } // SimpleScreen SimpleScreen::SimpleScreen(void(*draw)(SimpleScreen& ss), void(*eventHandler)(SimpleScreen& ss, ALLEGRO_EVENT& ev)) { al_init(); <API key>(); al_install_mouse(); al_install_keyboard(); al_init_image_addon(); <API key>(); display = al_create_display(screenWidth, screenHeight); event_queue = <API key>(); <API key>(event_queue, <API key>(display)); <API key>(event_queue, <API key>()); <API key>(event_queue, <API key>()); Clear(); points = new vector<Point2D*>(); SetProjection(); this->draw = draw; this->eventHandler = eventHandler; redraw = true; exit = false; zoomFrameClr = al_color_name("blue"); <API key> = 2; } SimpleScreen::~SimpleScreen() { worldRects.clear(); if (points != nullptr) { points->clear(); delete points; } if (cameraLocation != nullptr) delete cameraLocation; <API key>(event_queue); al_destroy_display(display); <API key>(); <API key>(); <API key>(); } void SimpleScreen::SetWorldRect(double xMin, double yMin, double xMax, double yMax) { worldRects.push_back(Rectangle(xMin, yMin, xMax, yMax)); GetWorldRect(); } void SimpleScreen::GetWorldRect() { Rectangle& r = worldRects.back(); worldXmin = r.xMin; worldYmin = r.yMin; worldXmax = r.xMax; worldYmax = r.yMax; worldWidth = r.xMax - r.xMin; worldHeight = r.yMax - r.yMin; scaleX = screenWidth / worldWidth; scaleY = screenHeight / worldHeight; } void SimpleScreen::SetProjection(double degrees, double correction) { obliqueAngle = degrees * M_PI / 180; obliqueCos = cos(obliqueAngle); obliqueSin = sin(obliqueAngle); aspectCorrection = correction; } void SimpleScreen::SetCameraLocation(double x, double y, double z) { cameraLocation = new Point3D(x, y, z); } void SimpleScreen::SetZoomFrame(string clr, double width) { zoomFrameClr = al_color_name(clr.c_str()); <API key> = width; } void SimpleScreen::LockDisplay() { lr = al_lock_bitmap(al_get_backbuffer(display), <API key>, <API key>); } void SimpleScreen::UnlockDisplay() { if (lr != nullptr) { al_unlock_bitmap(al_get_backbuffer(display)); lr = nullptr; } } void SimpleScreen::Clear() { //al_clear_to_color(al_map_rgb(0, 0, 0)); al_clear_to_color(al_map_rgb(212, 208, 200)); } void SimpleScreen::Update() { al_flip_display(); redraw = false; } void SimpleScreen::Exit() { exit = true; } void SimpleScreen::Redraw() { redraw = true; } void SimpleScreen::HandleEvents() { ALLEGRO_EVENT ev; Point2D dragBegin; Point2D dragEnd; ALLEGRO_BITMAP* image2{ nullptr }; bool isZooming = false; while (!exit) { // If necessary, call user provided draw method if (redraw) { if (draw != nullptr) draw(*this); Update(); continue; } al_wait_for_event(event_queue, &ev); // Check for quit if (ev.type == <API key>) { exit = true; break; } if ((ev.type == <API key>)) { // If left mouse button was pressed down, start drawing zoom rectangle if (draw != nullptr && !isZooming && (ev.mouse.button == 1)) { isZooming = true; dragBegin.x = ev.mouse.x; dragBegin.y = ev.mouse.y; if (image2 != nullptr) al_destroy_bitmap(image2); image2 = al_clone_bitmap(al_get_backbuffer(display)); continue; } // If right mouse button was pressed, revert to prior zoom level if possible if ((ev.mouse.button == 2) && (worldRects.size() > 1)) { Clear(); worldRects.pop_back(); GetWorldRect(); Redraw(); continue; } } // If releasing zoom rectangle, calculate new World rectangle if (draw != nullptr && isZooming && (ev.type == <API key>)) { isZooming = false; dragEnd.x = ev.mouse.x; dragEnd.y = ev.mouse.y; Rectangle rectDrag(dragBegin.x, dragBegin.y, dragEnd.x, dragEnd.y); if (((rectDrag.xMax - rectDrag.xMin) > 0) && ((rectDrag.yMax - rectDrag.yMin) > 0)) { rectDrag.Resize(screenWidth, screenHeight); double wxMin = rectDrag.xMin / screenWidth * worldWidth + worldXmin; double wxMax = rectDrag.xMax / screenWidth * worldWidth + worldXmin; double wyMin = (screenHeight - rectDrag.yMin) / screenHeight * worldHeight + worldYmin; double wyMax = (screenHeight - rectDrag.yMax) / screenHeight * worldHeight + worldYmin; Clear(); SetWorldRect(wxMin, wyMin, wxMax, wyMax); Redraw(); } continue; } // If zooming, draw bounding rectangle while maintaining // the aspect ratio of current world rectangle if (draw != nullptr && isZooming && (ev.type == <API key>)) { al_draw_bitmap(image2, 0, 0, 0); dragEnd.x = ev.mouse.x; dragEnd.y = ev.mouse.y; Rectangle rectDrag(dragBegin.x, dragBegin.y, dragEnd.x, dragEnd.y); rectDrag.Resize(screenWidth, screenHeight); al_draw_rectangle(rectDrag.xMin, rectDrag.yMin, rectDrag.xMax, rectDrag.yMax, zoomFrameClr, <API key>); al_flip_display(); continue; } // Call user provided event handler if (eventHandler != nullptr) eventHandler(*this, ev); } if (image2 != nullptr) al_destroy_bitmap(image2); } bool SimpleScreen::Contains(double x, double y) { if (x < worldXmin) return false; if (x > worldXmax) return false; if (y < worldYmin) return false; if (y > worldYmax) return false; return true; } void SimpleScreen::CalcScreenPoints(PointSet* ps) { points->clear(); for (size_t i{}; i < ps->size(); ++i) { // Convert WORLD coordinates to SCREEN coordinates double screenX = (ps->at(i)->x - worldXmin) * scaleX; double screenY = screenHeight - (ps->at(i)->y - worldYmin) * scaleY; // Add this SCREEN coordinate to array of points points->push_back(new Point2D(screenX, screenY)); } } void SimpleScreen::CalcScreenPoints3D(PointSet3D* ps3d) { points->clear(); for (size_t i{}; i < ps3d->size(); ++i) { // Convert WORLD coordinates to SCREEN coordinates double screenX = (ps3d->at(i)->x - ps3d->at(i)->z * obliqueCos * aspectCorrection - worldXmin) * scaleX; double screenY = screenHeight - (ps3d->at(i)->y - ps3d->at(i)->z * obliqueSin - worldYmin) * scaleY; // Add this SCREEN coordinate to array of points points->push_back(new Point2D(screenX, screenY)); } } void SimpleScreen::DrawAxes(string clr, float width) { // Draw X axis double screenY0 = screenHeight + worldYmin * scaleY; al_draw_line(1, screenY0, screenWidth, screenY0, al_color_name(clr.c_str()), width); // Draw Y axis double screenX0 = -worldXmin * scaleX; al_draw_line(screenX0, 1, screenX0, screenHeight, al_color_name(clr.c_str()), width); al_flip_display(); } void SimpleScreen::DrawLine(Point2D& a, Point2D& b, string clr, float width) { PointSet ps; ps.add(&a); ps.add(&b); DrawLines(&ps, clr, width, false, false, 0); } void SimpleScreen::DrawLines(PointSet* ps, string clr, float width, bool close, bool fill, long delay) { CalcScreenPoints(ps); if (fill) close = true; if (close) { vector<float> verts; for (size_t i{};i < points->size();++i) { verts.push_back(points->at(i)->x); verts.push_back(points->at(i)->y); } if (fill) { <API key>(&verts[0], ps->size(), al_color_name(clr.c_str())); } else { al_draw_polygon(&verts[0], ps->size(), <API key>, al_color_name(clr.c_str()), width, 0); } } else { for (size_t i{}; i < points->size() - 1;++i) { al_draw_line(points->at(i)->x, points->at(i)->y, points->at(i + 1)->x, points->at(i + 1)->y, al_color_name(clr.c_str()), width); if (delay > 0) { al_flip_display(); this_thread::sleep_for(chrono::milliseconds(delay)); } } } } void SimpleScreen::DrawLines(FacetSet* facets, std::string clr, float width, bool fill, long delay) { for (size_t f{}; f < facets->size();++f) { CalcScreenPoints3D(facets->at(f)->all()); vector<float> verts; for (size_t i{};i < points->size();++i) { verts.push_back(points->at(i)->x); verts.push_back(points->at(i)->y); } if (fill) { <API key>(&verts[0], points->size(), al_color_name(clr.c_str())); } else { al_draw_polygon(&verts[0], points->size(), <API key>, al_color_name(clr.c_str()), width, 0); } if (delay > 0) { al_flip_display(); this_thread::sleep_for(chrono::milliseconds(delay)); } } } void SimpleScreen::DrawLines(Facet* f, ALLEGRO_COLOR clr, float width, bool fill, long delay) { CalcScreenPoints3D(f->all()); vector<float> verts; for (size_t i{};i < points->size();++i) { verts.push_back(points->at(i)->x); verts.push_back(points->at(i)->y); } if (fill) { <API key>(&verts[0], points->size(), clr); } else { al_draw_polygon(&verts[0], points->size(), <API key>, clr, width, 0); } if (delay > 0) { al_flip_display(); this_thread::sleep_for(chrono::milliseconds(delay)); } } void SimpleScreen::DrawFacet(Facet* f, ALLEGRO_COLOR clrMin, ALLEGRO_COLOR clrMax, float width, bool culled, bool shaded, long delay) { if (shaded) culled = true; UnitVector* cameraVector = new UnitVector(f->center(), cameraLocation); double dotProduct = cameraVector->dotProduct(f->surfaceNormal()); ALLEGRO_COLOR clr = clrMax; if (shaded && dotProduct >= 0) { // Adjust the brightness of this facet based upon dotProduct float red = (clrMax.r - clrMin.r) * dotProduct + clrMin.r; float green = (clrMax.g - clrMin.g) * dotProduct + clrMin.g; float blue = (clrMax.b - clrMin.b) * dotProduct + clrMin.b; clr = al_map_rgb_f(red, green, blue); } if (!culled || dotProduct >= 0) { DrawLines(f, clr, width, shaded, delay); } } void SimpleScreen::DrawRectangle(string clr, double xMin, double yMin, double width, double height, int borderWidth, bool fill) { PointSet* ps = new PointSet(); ps->add(xMin, yMin); ps->add(xMin + width, yMin); ps->add(xMin + width, yMin + height); ps->add(xMin, yMin + height); DrawLines(ps, clr, borderWidth, true, fill); } void SimpleScreen::DrawCircle(double centerX, double centerY, double radius, string clr, int width) { PointSet* psCircle = new PointSet(); const int intervals = 97; const double deltaTheta = 2.0 * M_PI / intervals; for (int i{}; i < intervals;++i) { double theta = deltaTheta * i; double x = centerX + radius * cos(theta); double y = centerY + radius * sin(theta); psCircle->add(x, y); } DrawLines(psCircle, clr, width); } void SimpleScreen::DrawPoint(double x, double y, string clr) { x -= 0.5 / scaleX; y += 0.5 / scaleY; double screenX = (x - worldXmin) * scaleX; double screenY = screenHeight - (y - worldYmin) * scaleY; al_put_pixel(screenX, screenY, al_color_name(clr.c_str())); } void SimpleScreen::DrawPoint(double x, double y, ALLEGRO_COLOR& clr) { x -= 0.5 / scaleX; y += 0.5 / scaleY; double screenX = (x - worldXmin) * scaleX; double screenY = screenHeight - (y - worldYmin) * scaleY; al_put_pixel(screenX, screenY, clr); }
#include "InertPhaseModel.H" #include "phaseSystem.H" // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // template<class BasePhaseModel> Foam::InertPhaseModel<BasePhaseModel>::InertPhaseModel ( const phaseSystem& fluid, const word& phaseName, const label index ) : BasePhaseModel(fluid, phaseName, index) {} // * * * * * * * * * * * * * * * * Destructor * * * * * * * * * * * * * * * // template<class BasePhaseModel> Foam::InertPhaseModel<BasePhaseModel>::~InertPhaseModel() {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class BasePhaseModel> Foam::tmp<Foam::fvScalarMatrix> Foam::InertPhaseModel<BasePhaseModel>::R ( volScalarField& Yi ) const { return tmp<fvScalarMatrix> ( new fvScalarMatrix(Yi, dimMass/dimTime) ); } template<class BasePhaseModel> Foam::tmp<Foam::volScalarField> Foam::InertPhaseModel<BasePhaseModel>::Sh() const { return tmp<volScalarField> ( new volScalarField ( IOobject ( IOobject::groupName("Sh", this->name()), this->mesh().time().timeName(), this->mesh() ), this->mesh(), dimensionedScalar("zero", dimEnergy/dimTime/dimVolume, 0) ) ); }
namespace Meridian59.AdminUI.Viewers { partial class SpellsView { <summary> Erforderliche Designervariable. </summary> private System.ComponentModel.IContainer components = null; <summary> Verwendete Ressourcen bereinigen. </summary> <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Vom <API key> generierter Code <summary> Erforderliche Methode für die Designerunterstützung. Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. </summary> private void InitializeComponent() { System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>(); this.splitMain = new System.Windows.Forms.SplitContainer(); this.groupSpells = new System.Windows.Forms.GroupBox(); this.gridSpells = new Meridian59.AdminUI.Generic.BaseGridView(); this.colID = new System.Windows.Forms.<API key>(); this.colCount = new System.Windows.Forms.<API key>(); this.colOverlayRID = new System.Windows.Forms.<API key>(); this.colNameRID = new System.Windows.Forms.<API key>(); this.colFlags = new System.Windows.Forms.<API key>(); this.colLightingInfo = new System.Windows.Forms.<API key>(); this.colColorTranslation = new System.Windows.Forms.<API key>(); this.colEffect = new System.Windows.Forms.<API key>(); this.colAnimation = new System.Windows.Forms.<API key>(); this.colTargetsCount = new System.Windows.Forms.<API key>(); this.colSchoolType = new System.Windows.Forms.<API key>(); this.colAppearanceHash = new System.Windows.Forms.<API key>(); this.colName = new System.Windows.Forms.<API key>(); this.colOverlayFile = new System.Windows.Forms.<API key>(); this.splitMain2 = new System.Windows.Forms.SplitContainer(); this.groupSubOverlays = new System.Windows.Forms.GroupBox(); this.gridSubOverlays = new Meridian59.AdminUI.SubOverlayGrid(); this.splitAnimations = new System.Windows.Forms.SplitContainer(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.groupAnimation = new System.Windows.Forms.GroupBox(); this.avAnimation = new Meridian59.AdminUI.AnimationView(); this.<API key> = new System.Windows.Forms.GroupBox(); this.<API key> = new Meridian59.AdminUI.AnimationView(); this.groupImage = new System.Windows.Forms.GroupBox(); this.pictureBox = new Meridian59.AdminUI.Generic.<API key>(); ((System.ComponentModel.ISupportInitialize)(this.splitMain)).BeginInit(); this.splitMain.Panel1.SuspendLayout(); this.splitMain.Panel2.SuspendLayout(); this.splitMain.SuspendLayout(); this.groupSpells.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridSpells)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.splitMain2)).BeginInit(); this.splitMain2.Panel1.SuspendLayout(); this.splitMain2.Panel2.SuspendLayout(); this.splitMain2.SuspendLayout(); this.groupSubOverlays.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitAnimations)).BeginInit(); this.splitAnimations.Panel1.SuspendLayout(); this.splitAnimations.Panel2.SuspendLayout(); this.splitAnimations.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.groupAnimation.SuspendLayout(); this.<API key>.SuspendLayout(); this.groupImage.SuspendLayout(); this.SuspendLayout(); // splitMain this.splitMain.Dock = System.Windows.Forms.DockStyle.Fill; this.splitMain.Location = new System.Drawing.Point(0, 0); this.splitMain.Name = "splitMain"; this.splitMain.Orientation = System.Windows.Forms.Orientation.Horizontal; // splitMain.Panel1 this.splitMain.Panel1.Controls.Add(this.groupSpells); // splitMain.Panel2 this.splitMain.Panel2.Controls.Add(this.splitMain2); this.splitMain.Size = new System.Drawing.Size(930, 379); this.splitMain.SplitterDistance = 185; this.splitMain.TabIndex = 0; // groupSpells this.groupSpells.Controls.Add(this.gridSpells); this.groupSpells.Dock = System.Windows.Forms.DockStyle.Fill; this.groupSpells.Location = new System.Drawing.Point(0, 0); this.groupSpells.Name = "groupSpells"; this.groupSpells.Size = new System.Drawing.Size(930, 185); this.groupSpells.TabIndex = 0; this.groupSpells.TabStop = false; this.groupSpells.Text = "Spells"; // gridSpells this.gridSpells.<API key> = System.Windows.Forms.<API key>.AutoSize; this.gridSpells.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colID, this.colCount, this.colOverlayRID, this.colNameRID, this.colFlags, this.colLightingInfo, this.colColorTranslation, this.colEffect, this.colAnimation, this.colTargetsCount, this.colSchoolType, this.colAppearanceHash, this.colName, this.colOverlayFile}); this.gridSpells.Location = new System.Drawing.Point(3, 16); this.gridSpells.Name = "gridSpells"; this.gridSpells.Size = new System.Drawing.Size(924, 166); this.gridSpells.TabIndex = 0; this.gridSpells.SelectionChanged += new System.EventHandler(this.<API key>); // colID this.colID.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colID.DataPropertyName = "ID"; this.colID.HeaderText = "ID"; this.colID.Name = "colID"; this.colID.ReadOnly = true; this.colID.Width = 60; // colCount this.colCount.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colCount.DataPropertyName = "Count"; this.colCount.HeaderText = "COUNT"; this.colCount.Name = "colCount"; this.colCount.ReadOnly = true; this.colCount.Width = 60; // colOverlayRID this.colOverlayRID.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colOverlayRID.DataPropertyName = "OverlayFileRID"; this.colOverlayRID.HeaderText = "OVRID"; this.colOverlayRID.Name = "colOverlayRID"; this.colOverlayRID.ReadOnly = true; this.colOverlayRID.Width = 60; // colNameRID this.colNameRID.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colNameRID.DataPropertyName = "NameRID"; this.colNameRID.HeaderText = "NRID"; this.colNameRID.Name = "colNameRID"; this.colNameRID.ReadOnly = true; this.colNameRID.Width = 60; // colFlags this.colFlags.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colFlags.DataPropertyName = "Flags"; this.colFlags.HeaderText = "FLAGS"; this.colFlags.Name = "colFlags"; this.colFlags.ReadOnly = true; this.colFlags.Width = 50; // colLightingInfo this.colLightingInfo.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colLightingInfo.DataPropertyName = "LightingInfo"; <API key>.BackColor = System.Drawing.Color.PaleGoldenrod; this.colLightingInfo.DefaultCellStyle = <API key>; this.colLightingInfo.HeaderText = "LI"; this.colLightingInfo.Name = "colLightingInfo"; this.colLightingInfo.ReadOnly = true; // colColorTranslation this.colColorTranslation.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colColorTranslation.DataPropertyName = "ColorTranslation"; <API key>.BackColor = System.Drawing.Color.Thistle; this.colColorTranslation.DefaultCellStyle = <API key>; this.colColorTranslation.HeaderText = "CT"; this.colColorTranslation.Name = "colColorTranslation"; this.colColorTranslation.ReadOnly = true; this.colColorTranslation.Width = 35; // colEffect this.colEffect.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colEffect.DataPropertyName = "Effect"; <API key>.BackColor = System.Drawing.Color.Thistle; this.colEffect.DefaultCellStyle = <API key>; this.colEffect.HeaderText = "E"; this.colEffect.Name = "colEffect"; this.colEffect.ReadOnly = true; this.colEffect.Width = 35; // colAnimation this.colAnimation.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colAnimation.DataPropertyName = "Animation"; <API key>.BackColor = System.Drawing.Color.Thistle; this.colAnimation.DefaultCellStyle = <API key>; this.colAnimation.HeaderText = "ANIM"; this.colAnimation.Name = "colAnimation"; this.colAnimation.ReadOnly = true; this.colAnimation.Width = 60; // colTargetsCount this.colTargetsCount.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colTargetsCount.DataPropertyName = "TargetsCount"; <API key>.BackColor = System.Drawing.Color.SkyBlue; this.colTargetsCount.DefaultCellStyle = <API key>; this.colTargetsCount.HeaderText = "TC"; this.colTargetsCount.Name = "colTargetsCount"; this.colTargetsCount.ReadOnly = true; this.colTargetsCount.Width = 50; // colSchoolType this.colSchoolType.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colSchoolType.DataPropertyName = "SchoolType"; <API key>.BackColor = System.Drawing.Color.SkyBlue; this.colSchoolType.DefaultCellStyle = <API key>; this.colSchoolType.HeaderText = "ST"; this.colSchoolType.Name = "colSchoolType"; this.colSchoolType.ReadOnly = true; this.colSchoolType.Width = 60; // colAppearanceHash this.colAppearanceHash.AutoSizeMode = System.Windows.Forms.<API key>.None; this.colAppearanceHash.DataPropertyName = "AppearanceHash"; this.colAppearanceHash.HeaderText = "APPHASH"; this.colAppearanceHash.Name = "colAppearanceHash"; this.colAppearanceHash.ReadOnly = true; this.colAppearanceHash.Width = 70; // colName this.colName.AutoSizeMode = System.Windows.Forms.<API key>.Fill; this.colName.DataPropertyName = "Name"; <API key>.BackColor = System.Drawing.Color.Wheat; this.colName.DefaultCellStyle = <API key>; this.colName.HeaderText = "NAME"; this.colName.Name = "colName"; this.colName.ReadOnly = true; // colOverlayFile this.colOverlayFile.AutoSizeMode = System.Windows.Forms.<API key>.Fill; this.colOverlayFile.DataPropertyName = "OverlayFile"; <API key>.BackColor = System.Drawing.Color.Wheat; this.colOverlayFile.DefaultCellStyle = <API key>; this.colOverlayFile.HeaderText = "OVFILE"; this.colOverlayFile.Name = "colOverlayFile"; this.colOverlayFile.ReadOnly = true; // splitMain2 this.splitMain2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitMain2.Location = new System.Drawing.Point(0, 0); this.splitMain2.Name = "splitMain2"; // splitMain2.Panel1 this.splitMain2.Panel1.Controls.Add(this.groupSubOverlays); // splitMain2.Panel2 this.splitMain2.Panel2.Controls.Add(this.splitAnimations); this.splitMain2.Size = new System.Drawing.Size(930, 190); this.splitMain2.SplitterDistance = 382; this.splitMain2.TabIndex = 0; // groupSubOverlays this.groupSubOverlays.Controls.Add(this.gridSubOverlays); this.groupSubOverlays.Dock = System.Windows.Forms.DockStyle.Fill; this.groupSubOverlays.Location = new System.Drawing.Point(0, 0); this.groupSubOverlays.Name = "groupSubOverlays"; this.groupSubOverlays.Size = new System.Drawing.Size(382, 190); this.groupSubOverlays.TabIndex = 0; this.groupSubOverlays.TabStop = false; this.groupSubOverlays.Text = "SubOverlays"; // gridSubOverlays this.gridSubOverlays.Dock = System.Windows.Forms.DockStyle.Fill; this.gridSubOverlays.Location = new System.Drawing.Point(3, 16); this.gridSubOverlays.Name = "gridSubOverlays"; this.gridSubOverlays.Size = new System.Drawing.Size(376, 171); this.gridSubOverlays.TabIndex = 0; // splitAnimations this.splitAnimations.Dock = System.Windows.Forms.DockStyle.Fill; this.splitAnimations.Location = new System.Drawing.Point(0, 0); this.splitAnimations.Name = "splitAnimations"; // splitAnimations.Panel1 this.splitAnimations.Panel1.Controls.Add(this.splitContainer1); // splitAnimations.Panel2 this.splitAnimations.Panel2.Controls.Add(this.groupImage); this.splitAnimations.Size = new System.Drawing.Size(544, 190); this.splitAnimations.SplitterDistance = 164; this.splitAnimations.TabIndex = 0; // splitContainer1 this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // splitContainer1.Panel1 this.splitContainer1.Panel1.Controls.Add(this.groupAnimation); // splitContainer1.Panel2 this.splitContainer1.Panel2.Controls.Add(this.<API key>); this.splitContainer1.Size = new System.Drawing.Size(164, 190); this.splitContainer1.SplitterDistance = 91; this.splitContainer1.TabIndex = 1; // groupAnimation this.groupAnimation.Controls.Add(this.avAnimation); this.groupAnimation.Dock = System.Windows.Forms.DockStyle.Fill; this.groupAnimation.Location = new System.Drawing.Point(0, 0); this.groupAnimation.Name = "groupAnimation"; this.groupAnimation.Size = new System.Drawing.Size(164, 91); this.groupAnimation.TabIndex = 0; this.groupAnimation.TabStop = false; this.groupAnimation.Text = "Animation"; // avAnimation this.avAnimation.Dock = System.Windows.Forms.DockStyle.Fill; this.avAnimation.Location = new System.Drawing.Point(3, 16); this.avAnimation.Name = "avAnimation"; this.avAnimation.Size = new System.Drawing.Size(158, 72); this.avAnimation.TabIndex = 0; // <API key> this.<API key>.Controls.Add(this.<API key>); this.<API key>.Dock = System.Windows.Forms.DockStyle.Fill; this.<API key>.Location = new System.Drawing.Point(0, 0); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size(164, 95); this.<API key>.TabIndex = 0; this.<API key>.TabStop = false; this.<API key>.Text = "SubOverlayAnimation"; // <API key> this.<API key>.Dock = System.Windows.Forms.DockStyle.Fill; this.<API key>.Location = new System.Drawing.Point(3, 16); this.<API key>.Name = "<API key>"; this.<API key>.Size = new System.Drawing.Size(158, 76); this.<API key>.TabIndex = 0; // groupImage this.groupImage.Controls.Add(this.pictureBox); this.groupImage.Dock = System.Windows.Forms.DockStyle.Fill; this.groupImage.Location = new System.Drawing.Point(0, 0); this.groupImage.Name = "groupImage"; this.groupImage.Size = new System.Drawing.Size(376, 190); this.groupImage.TabIndex = 1; this.groupImage.TabStop = false; this.groupImage.Text = "Image"; // pictureBox this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.pictureBox.Location = new System.Drawing.Point(3, 16); this.pictureBox.Name = "pictureBox"; this.pictureBox.Size = new System.Drawing.Size(370, 171); this.pictureBox.TabIndex = 0; // SpellsView this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitMain); this.Name = "SpellsView"; this.Size = new System.Drawing.Size(930, 379); this.splitMain.Panel1.ResumeLayout(false); this.splitMain.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitMain)).EndInit(); this.splitMain.ResumeLayout(false); this.groupSpells.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridSpells)).EndInit(); this.splitMain2.Panel1.ResumeLayout(false); this.splitMain2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitMain2)).EndInit(); this.splitMain2.ResumeLayout(false); this.groupSubOverlays.ResumeLayout(false); this.splitAnimations.Panel1.ResumeLayout(false); this.splitAnimations.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitAnimations)).EndInit(); this.splitAnimations.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.groupAnimation.ResumeLayout(false); this.<API key>.ResumeLayout(false); this.groupImage.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitMain; private System.Windows.Forms.GroupBox groupSpells; private System.Windows.Forms.SplitContainer splitMain2; private System.Windows.Forms.GroupBox groupSubOverlays; private System.Windows.Forms.SplitContainer splitAnimations; private SubOverlayGrid gridSubOverlays; private System.Windows.Forms.GroupBox groupAnimation; private System.Windows.Forms.GroupBox <API key>; private AnimationView avAnimation; private AnimationView <API key>; private Meridian59.AdminUI.Generic.BaseGridView gridSpells; private System.Windows.Forms.<API key> colID; private System.Windows.Forms.<API key> colCount; private System.Windows.Forms.<API key> colOverlayRID; private System.Windows.Forms.<API key> colNameRID; private System.Windows.Forms.<API key> colFlags; private System.Windows.Forms.<API key> colLightingInfo; private System.Windows.Forms.<API key> colColorTranslation; private System.Windows.Forms.<API key> colEffect; private System.Windows.Forms.<API key> colAnimation; private System.Windows.Forms.<API key> colTargetsCount; private System.Windows.Forms.<API key> colSchoolType; private System.Windows.Forms.<API key> colAppearanceHash; private System.Windows.Forms.<API key> colName; private System.Windows.Forms.<API key> colOverlayFile; private System.Windows.Forms.SplitContainer splitContainer1; private Generic.<API key> pictureBox; private System.Windows.Forms.GroupBox groupImage; } }
alter table document modify number_of_pages int(6);
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/<API key>.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/<API key>.proto</summary> public static partial class <API key> { #region Descriptor <summary>File descriptor for POGOProtos/Networking/Responses/<API key>.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static <API key>() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "<API key>", "<API key>", "<API key>", "<API key>==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::<API key>(null, new pbr::<API key>[] { new pbr::<API key>(typeof(global::POGOProtos.Networking.Responses.<API key>), global::POGOProtos.Networking.Responses.<API key>.Parser, new[]{ "AccessToken" }, null, null, null) })); } #endregion } #region Messages public sealed partial class <API key> : pb::IMessage<<API key>> { private static readonly pb::MessageParser<<API key>> _parser = new pb::MessageParser<<API key>>(() => new <API key>()); [global::System.Diagnostics.<API key>] public static pb::MessageParser<<API key>> Parser { get { return _parser; } } [global::System.Diagnostics.<API key>] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.<API key>.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.<API key>] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.<API key>] public <API key>() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.<API key>] public <API key>(<API key> other) : this() { accessToken_ = other.accessToken_; } [global::System.Diagnostics.<API key>] public <API key> Clone() { return new <API key>(this); } <summary>Field number for the "access_token" field.</summary> public const int <API key> = 1; private pb::ByteString accessToken_ = pb::ByteString.Empty; [global::System.Diagnostics.<API key>] public pb::ByteString AccessToken { get { return accessToken_; } set { accessToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.<API key>] public override bool Equals(object other) { return Equals(other as <API key>); } [global::System.Diagnostics.<API key>] public bool Equals(<API key> other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (AccessToken != other.AccessToken) return false; return true; } [global::System.Diagnostics.<API key>] public override int GetHashCode() { int hash = 1; if (AccessToken.Length != 0) hash ^= AccessToken.GetHashCode(); return hash; } [global::System.Diagnostics.<API key>] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.<API key>] public void WriteTo(pb::CodedOutputStream output) { if (AccessToken.Length != 0) { output.WriteRawTag(10); output.WriteBytes(AccessToken); } } [global::System.Diagnostics.<API key>] public int CalculateSize() { int size = 0; if (AccessToken.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(AccessToken); } return size; } [global::System.Diagnostics.<API key>] public void MergeFrom(<API key> other) { if (other == null) { return; } if (other.AccessToken.Length != 0) { AccessToken = other.AccessToken; } } [global::System.Diagnostics.<API key>] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { AccessToken = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
#!/usr/bin/python import os, re aliases = os.listdir('/Users/greg/Documents/freex/') aliases = [a.lower() for a in aliases if '.freex' in a] aliases.sort(reverse=True) aliases = [re.escape(a.lower()) for a in aliases] aliasRegexpStr = '\\b'+'\\b|\\b'.join(aliases)+'\\b' aliasRegexpStr = aliasRegexpStr.replace('\\ ', ' ?\\\n? *') aliasRegexpStr = aliasRegexpStr.replace('\\ ', ' ?\\\n? *') impLinkRegexp = re.compile(aliasRegexpStr,re.IGNORECASE|re.MULTILINE)
C C C Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. C C This program is free software; you can redistribute it and/or modify it C under the terms of version 2.1 of the GNU Lesser General Public License C as published by the Free Software Foundation. C C This program is distributed in the hope that it would be useful, but C WITHOUT ANY WARRANTY; without even the implied warranty of C MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. C C Further, this software is distributed without any warranty that it is C free of the rightful claim of any third person regarding infringement C or the like. Any license provided herein, whether implied or C otherwise, applies only to this software file. Patent licenses, if C any, provided herein do not apply to combinations of this program with C other software, or any other product whatsoever. C C You should have received a copy of the GNU Lesser General Public C License along with this program; if not, write the Free Software C Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, C USA. C C Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, C Mountain View, CA 94043, or: C C http: C C For further information regarding this notice, see: C C http://oss.sgi.com/projects/GenInfo/NoticeExplan C C SUBROUTINE VXDCTI(FPN,DEST,ISB,NUM,IER,INC) C C The VXDCTI subroutine converts Cray 64-bit single-precision C floating-point numbers to VAX D_format single-precision C floating-point numbers. Numbers that produce an underflow when C converted to VAX format are converted to 32 binary zeros. Numbers C that are in overflow on the CRAY are converted to a "reserved" C floating-point representation with the sign bit set if negative. C Numbers that are valid on the CRAY but overflow on the VAX are C converted to the most positive possible number or most negative C possible number, depending on the sign. C C Presently, you must supply a parameter which, in the future, C will contain a nonzero value if any numbers converted produced C an overflow. No such indication will be given for underflow. C REAL FPN(1) ! Variable or array of any length and C ! type real, containing Cray 64-bit, C ! single-precision, floating-point C ! numbers to convert. C INTEGER DEST(1) ! Variable or array of type real to C ! contain the converted values. C INTEGER ISB ! Byte number at which to begin C ! storing the converted results. Type C ! integer variable, expression, or C ! constant. Bytes are numbered from C ! 1, beginning at the leftmost byte C ! position of DEST. C INTEGER NUM ! Number of Cray floating-point C ! numbers to convert. Type integer C ! variable, expression, or constant. C INTEGER IER ! Overflow indicator of type integer. C ! Value is 0 if all Cray values C ! convert to VAX values without C ! overflow. Value is nonzero if one C ! or more Cray values overflowed in C ! the conversion. C INTEGER INC ! Memory increment for fetching the C ! number to be converted. Optional C ! parameter of type integer variable, C ! expression, or constant. Default C ! value is 1. INTEGER ITEMP(64), JTEMP(32) CDIR$ VFUNCTION VD64O INTEGER VD64O IF (NUMARG() .EQ.5) THEN JNC = 1 ELSE IF (NUMARG() .EQ. 6) THEN JNC = INC ELSE CALL ABORT('VAX conversion routine called with incorrect number +of arguments') ENDIF IF (NUM .LT. 0) THEN CALL ABORT('Invalid input to VAX conversion routine') ENDIF NUMC = NUM JSB = ISB J = 1 IER = 0 IF (NUM .EQ. 0) RETURN 40 CONTINUE NUMP = MIN0(NUMC,64) CDIR$ SHORTLOOP DO 80 I = 1, NUMP ITEMP(I) = VD64O(DBLE(FPN(J))) J = J + JNC 80 CONTINUE CALL VXMOVE00(ITEMP,1,NUMP*8,DEST,JSB) JSB = JSB + 8*NUMP NUMC = NUMC - NUMP IF (NUMC .GT. 0) GO TO 40 RETURN CDIR$ ID "@(#) libu/vms/vxdcti.f 92.0 10/08/98 14:57:41" END
// $Id: power_module.cpp 5188 2012-08-30 00:31:31Z dub $ #include "power_module.hpp" #include "booksim_config.hpp" #include "buffer_monitor.hpp" #include "switch_monitor.hpp" #include "iq_router.hpp" Power_Module::Power_Module(Network * n , const Configuration &config) : Module( 0, "power_module" ){ string pfile = config.GetStr("tech_file"); PowerConfig pconfig; pconfig.ParseFile(pfile); net = n; output_file_name = config.GetStr("power_output_file"); classes = config.GetInt("classes"); channel_width = (double)config.GetInt("channel_width"); channel_sweep = (double)config.GetInt("channel_sweep"); numVC = (double)config.GetInt("num_vcs"); depthVC = (double)config.GetInt("vc_buf_size"); ///////////////////////////////Constants///////////////////////////// //wire length in (mm) wire_length = pconfig.GetFloat("wire_length"); ///////Metal Parameters//////////// // Wire left/right coupling capacitance [ F/mm ] Cw_cpl = pconfig.GetFloat("Cw_cpl"); // Wire up/down groudn capacitance [ F/mm ] Cw_gnd = pconfig.GetFloat("Cw_gnd"); Cw = 2.0 * Cw_cpl + 2.0 * Cw_gnd ; Rw = pconfig.GetFloat("Rw"); // metal pitch [mm] MetalPitch = pconfig.GetFloat("MetalPitch"); ///////Device Parameters//////////// LAMBDA = pconfig.GetFloat("LAMBDA") ; // [um/LAMBDA] Cd = pconfig.GetFloat("Cd"); // [F/um] (for Delay) Cg = pconfig.GetFloat("Cg"); // [F/um] (for Delay) Cgdl = pconfig.GetFloat("Cgdl"); // [F/um] (for Delay) Cd_pwr = pconfig.GetFloat("Cd_pwr") ; // [F/um] (for Power) Cg_pwr = pconfig.GetFloat("Cg_pwr") ; // [F/um] (for Power) IoffN = pconfig.GetFloat("IoffN"); // [A/um] IoffP = pconfig.GetFloat("IoffP"); // [A/um] // Leakage from bitlines, two-port cell [A] IoffSRAM = pconfig.GetFloat("IoffSRAM"); // [Ohm] ( D1=1um Inverter) R = pconfig.GetFloat("R"); // [F] ( D1=1um Inverter - for Power ) Ci_delay = (1.0 + 2.0) * ( Cg + Cgdl ); // [F] ( D1=1um Inverter - for Power ) Co_delay = (1.0 + 2.0) * Cd ; Ci = (1.0 + 2.0) * Cg_pwr ; Co = (1.0 + 2.0) * Cd_pwr ; Vdd = pconfig.GetFloat("Vdd"); FO4 = R * ( 3.0 * Cd + 12 * Cg + 12 * Cgdl); tCLK = 20 * FO4; fCLK = 1.0 / tCLK; H_INVD2=(double)pconfig.GetInt("H_INVD2"); W_INVD2=(double)pconfig.GetInt("W_INVD2") ; H_DFQD1=(double)pconfig.GetInt("H_DFQD1"); W_DFQD1= (double)pconfig.GetInt("W_DFQD1"); H_ND2D1= (double)pconfig.GetInt("H_ND2D1"); W_ND2D1=(double)pconfig.GetInt("W_ND2D1"); H_SRAM=(double)pconfig.GetInt("H_SRAM"); W_SRAM=(double)pconfig.GetInt("W_SRAM"); ChannelPitch = 2.0 * MetalPitch ; CrossbarPitch = 2.0 * MetalPitch ; } Power_Module::~Power_Module(){ } //Channels void Power_Module::calcChannel(const FlitChannel* f){ double channelLength = f->GetLatency()* wire_length; wire const this_wire = wireOptimize(channelLength); double const & K = this_wire.K; double const & N = this_wire.N; double const & M = this_wire.M; //area channelArea += areaChannel(K,N,M); //activity factor; const vector<int> temp = f->GetActivity(); vector<double> a(classes); for(int i = 0; i< classes; i++){ a[i] = ((double)temp[i])/totalTime; } //power calculation double const bitPower = powerRepeatedWire(channelLength, K,M,N); channelClkPower += powerWireClk(M,channel_width); for(int i = 0; i< classes; i++){ channelWirePower += bitPower * a[i]*channel_width; channelDFFPower += powerWireDFF(M, channel_width, a[i]); } channelLeakPower+= <API key>(K,M,N)*channel_width; } wire const & Power_Module::wireOptimize(double L){ map<double, wire>::iterator iter = wire_map.find(L); if(iter == wire_map.end()){ double W = 64; double bestMetric = 100000000 ; double bestK = -1; double bestM = -1; double bestN = -1; for (double K = 1.0 ; K < 10 ; K+=0.1 ) { for (double N = 1.0 ; N < 40 ; N += 1.0 ) { for (double M = 1.0 ; M < 40.0 ; M +=1.0 ) { double l = 1.0 * L/( N * M) ; double k0 = R * (Co_delay + Ci_delay) ; double k1 = R/K * Cw + K * Rw * Ci_delay ; double k2 = 0.5 * Rw * Cw ; double Tw = k0 + (k1 * l) + k2 * (l * l) ; double alpha = 0.2 ; double power = alpha * W * powerRepeatedWire( L, K, M, N) + powerWireDFF( M, W, alpha ) ; double metric = M * M * M * M * power ; if ( (N*Tw) < (0.8 * tCLK) ) { if ( metric < bestMetric ) { bestMetric = metric ; bestK = K ; bestM = M ; bestN = N ; } } } } } cout<<"L = "<<L<<" K = "<<bestK<<" M = "<<bestM<<" N = "<<bestN<<endl; wire const temp = {L, bestK, bestM, bestN}; iter = wire_map.insert(make_pair(L, temp)).first; } return iter->second; } double Power_Module::powerRepeatedWire(double L, double K, double M, double N){ double segments = 1.0 * M * N ; double Ca = K * (Ci + Co) + Cw * (L/segments) ; double Pa = 0.5 * Ca * Vdd * Vdd * fCLK; return Pa * M * N ; } double Power_Module::<API key> (double K, double M, double N){ double Pl = K * 0.5 * ( IoffN + 2.0 * IoffP ) * Vdd ; return Pl * M * N ; } double Power_Module:: powerWireClk (double M, double W){ // number of clock wires running down one repeater bank double columns = H_DFQD1 * MetalPitch / ChannelPitch ; // length of clock wire double clockLength = W * ChannelPitch ; double Cclk = (1 + 5.0/16.0 * (1+Co_delay/Ci_delay)) * (clockLength * Cw * columns +W * Ci_delay); return M * Cclk * (Vdd * Vdd) * fCLK ; } double Power_Module::powerWireDFF(double M, double W, double alpha){ double Cdin = 2 * 0.8 * (Ci + Co) + 2 * ( 2.0/3.0 * 0.8 * Co ) ; double Cclk = 2 * 0.8 * (Ci + Co) + 2 * ( 2.0/3.0 * 0.8 * Cg_pwr) ; double Cint = (alpha * 0.5) * Cdin + alpha * Cclk ; return Cint * M * W * (Vdd*Vdd) * fCLK ; } //Memory void Power_Module::calcBuffer(const BufferMonitor *bm){ double depth = numVC * depthVC ; double Pleak = powerMemoryBitLeak( depth ) * channel_width ; //area const vector<int> reads = bm->GetReads(); const vector<int> writes = bm->GetWrites(); for(int i = 0; i<bm->NumInputs(); i++){ inputArea += areaInputModule( depth ); inputLeakagePower += Pleak ; for(int j = 0; j< classes; j++){ double ar = ((double)reads[i* classes+j])/totalTime; double aw = ((double)writes[i* classes+j])/totalTime; if(ar>1 ||aw >1){ cout<<"activity factor is greater than one, soemthing is stomping memory\n"; exit(-1); } double Pwl = powerWordLine( channel_width, depth) ; double Prd = powerMemoryBitRead( depth ) * channel_width ; double Pwr = powerMemoryBitWrite( depth ) * channel_width ; inputReadPower += ar * ( Pwl + Prd ) ; inputWritePower += aw * ( Pwl + Pwr ) ; } } } double Power_Module::powerWordLine(double memoryWidth, double memoryDepth){ // wordline capacitance double Ccell = 2 * ( 4.0 * LAMBDA ) * Cg_pwr + 6 * MetalPitch * Cw ; double Cwl = memoryWidth * Ccell ; // wordline circuits double Warray = 8 * MetalPitch + memoryDepth ; double x = 1.0 + (5.0/16.0) * (1 + Co/Ci) ; double Cpredecode = x * (Cw * Warray * Ci) ; double Cdecode = x * Cwl ; // bitline circuits double Harray = 6 * memoryWidth * MetalPitch ; double y = (1 + 0.25) * (1 + Co/Ci) ; double Cprecharge = y * ( Cw * Harray + 3 * channel_width * Ci ) ; double Cwren = y * ( Cw * Harray + 2 * channel_width * Ci ) ; double Cbd = Cprecharge + Cwren ; double Cwd = 2 * Cpredecode + Cdecode ; return ( Cbd + Cwd ) * Vdd * Vdd * fCLK ; } double Power_Module::powerMemoryBitRead(double memoryDepth){ // bitline capacitance double Ccell = 4.0 * LAMBDA * Cd_pwr + 8 * MetalPitch * Cw ; double Cbl = memoryDepth * Ccell ; double Vswing = Vdd ; return ( Cbl ) * ( Vdd * Vswing ) * fCLK ; } double Power_Module:: powerMemoryBitWrite(double memoryDepth){ // bitline capacitance double Ccell = 4.0 * LAMBDA * Cd_pwr + 8 * MetalPitch * Cw ; double Cbl = memoryDepth * Ccell ; // internal capacitance double Ccc = 2 * (Co + Ci) ; return (0.5 * Ccc * (Vdd*Vdd)) + ( Cbl ) * ( Vdd * Vdd ) * fCLK ; } double Power_Module::powerMemoryBitLeak(double memoryDepth ){ return memoryDepth * IoffSRAM * Vdd ; } //switch void Power_Module::calcSwitch(const SwitchMonitor* sm){ switchArea += areaCrossbar(sm->NumInputs(), sm->NumOutputs()); outputArea += areaOutputModule(sm->NumOutputs()); switchPowerLeak += powerCrossbarLeak(channel_width, sm->NumInputs(), sm->NumOutputs()); const vector<int> activity = sm->GetActivity(); vector<double> type_activity(classes); for(int i = 0; i<sm->NumOutputs(); i++){ for(int k = 0; k<classes; k++){ type_activity[k] = 0; } for(int j = 0; j<sm->NumInputs(); j++){ for(int k = 0; k<classes; k++){ double a = activity[k+classes*(i+sm->NumOutputs()*j)]; a = a/totalTime; if(a>1){ cout<<"Switcht activity factor is greater than 1!!!\n";exit(-1); } double Px = powerCrossbar(channel_width, sm->NumInputs(),sm->NumOutputs(),j,i); switchPower += a*channel_width*Px; switchPowerCtrl += a *powerCrossbarCtrl(channel_width, sm->NumInputs(),sm->NumOutputs()); type_activity[k]+=a; } } outputPowerClk += powerWireClk( 1, channel_width ) ; for(int k = 0; k<classes; k++){ outputPower += type_activity[k] * powerWireDFF( 1, channel_width, 1.0 ) ; outputCtrlPower += type_activity[k] * powerOutputCtrl(channel_width ) ; } } } double Power_Module::powerCrossbar(double width, double inputs, double outputs, double from, double to){ // datapath traversal power double Wxbar = width * outputs * CrossbarPitch ; double Hxbar = width * inputs * CrossbarPitch ; // wires double CwIn = Wxbar * Cw ; double CwOut = Hxbar * Cw ; // cross-points double Cxi = (1.0/16.0) * CwOut ; double Cxo = 4.0 * Cxi * (Co_delay/Ci_delay) ; // drivers double Cti = (1.0/16.0) * CwIn ; double Cto = 4.0 * Cti * (Co_delay/Ci_delay) ; double CinputDriver = 5.0/16.0 * (1 + Co_delay/Ci_delay) * (0.5 * Cw * Wxbar + Cti) ; // total switched capacitance //this maybe missing +Cto double Cin = CinputDriver + CwIn + Cti + (outputs * Cxi) ; if ( to < outputs/2 ) { Cin -= ( 0.5 * CwIn + outputs/2 * Cxi) ; } //this maybe missing +cti double Cout = CwOut + Cto + (inputs * Cxo) ; if ( from < inputs/2) { Cout -= ( 0.5 * CwOut + (inputs/2 * Cxo)) ; } return 0.5 * (Cin + Cout) * (Vdd * Vdd * fCLK) ; } double Power_Module::powerCrossbarCtrl(double width, double inputs, double outputs){ // datapath traversal power double Wxbar = width * outputs * CrossbarPitch ; double Hxbar = width * inputs * CrossbarPitch ; // wires double CwIn = Wxbar * Cw ; // drivers double Cti = (5.0/16.0) * CwIn ; // need some estimate of how many control wires are required double Cctrl = width * Cti + (Wxbar + Hxbar) * Cw ; double Cdrive = (5.0/16.0) * (1 + Co_delay/Ci_delay) * Cctrl ; return (Cdrive + Cctrl) * (Vdd*Vdd) * fCLK ; } double Power_Module::powerCrossbarLeak (double width, double inputs, double outputs){ // datapath traversal power double Wxbar = width * outputs * CrossbarPitch ; double Hxbar = width * inputs * CrossbarPitch ; // wires double CwIn = Wxbar * Cw ; double CwOut = Hxbar * Cw ; // cross-points double Cxi = (1.0/16.0) * CwOut ; // drivers double Cti = (1.0/16.0) * CwIn ; return 0.5 * (IoffN + 2 * IoffP)*width*(inputs*outputs*Cxi+inputs*Cti+outputs*Cti)/Ci; } //output module double Power_Module:: powerOutputCtrl(double width) { double Woutmod = channel_width * ChannelPitch ; double Cen = Ci ; double Cenable = (1 + 5.0/16.0)*(1.0+Co/Ci)*(Woutmod* Cw + width* Cen) ; return Cenable * (Vdd*Vdd) * fCLK ; } //area double Power_Module:: areaChannel (double K, double N, double M){ double Adff = M * W_DFQD1 * H_DFQD1 ; double Ainv = M * N * ( W_INVD2 + 3 * K) * H_INVD2 ; return channel_width * (Adff + Ainv) * MetalPitch * MetalPitch ; } double Power_Module:: areaCrossbar(double Inputs, double Outputs) { return (Inputs * channel_width * CrossbarPitch) * (Outputs * channel_width * CrossbarPitch) ; } double Power_Module:: areaInputModule(double Words) { double Asram = ( channel_width * H_SRAM ) * (Words * W_SRAM) ; return Asram * (MetalPitch * MetalPitch) ; } double Power_Module:: areaOutputModule(double Outputs) { double Adff = Outputs * W_DFQD1 * H_DFQD1 ; return channel_width * Adff * MetalPitch * MetalPitch ; } void Power_Module::run(){ totalTime = GetSimTime(); channelWirePower=0; channelClkPower=0; channelDFFPower=0; channelLeakPower=0; inputReadPower=0; inputWritePower=0; inputLeakagePower=0; switchPower=0; switchPowerCtrl=0; switchPowerLeak=0; outputPower=0; outputPowerClk=0; outputCtrlPower=0; channelArea=0; switchArea=0; inputArea=0; outputArea=0; maxInputPort = 0; maxOutputPort = 0; vector<FlitChannel *> inject = net->GetInject(); vector<FlitChannel *> eject = net->GetEject(); vector<FlitChannel *> chan = net->GetChannels(); for(int i = 0; i<net->NumNodes(); i++){ calcChannel(inject[i]); } for(int i = 0; i<net->NumNodes(); i++){ calcChannel(eject[i]); } for(int i = 0; i<net->NumChannels();i++){ calcChannel(chan[i]); } vector<Router*> routers = net->GetRouters(); for(size_t i = 0; i < routers.size(); i++){ IQRouter* temp = dynamic_cast<IQRouter*>(routers[i]); const BufferMonitor * bm = temp->GetBufferMonitor(); calcBuffer(bm); const SwitchMonitor * sm = temp->GetSwitchMonitor(); calcSwitch(sm); } double totalpower = channelWirePower+channelClkPower+channelDFFPower+channelLeakPower+ inputReadPower+inputWritePower+inputLeakagePower+ switchPower+switchPowerCtrl+switchPowerLeak+outputPower+outputPowerClk+outputCtrlPower; double totalarea = channelArea+switchArea+inputArea+outputArea; cout<< " cout<< "- OCN Power Summary\n" ; cout<< "- Completion Time: "<<totalTime <<"\n" ; cout<< "- Flit Widths: "<<channel_width<<"\n" ; cout<< "- Channel Wire Power: "<<channelWirePower <<"\n" ; cout<< "- Channel Clock Power: "<<channelClkPower <<"\n" ; cout<< "- Channel Retiming Power: "<<channelDFFPower <<"\n" ; cout<< "- Channel Leakage Power: "<<channelLeakPower <<"\n" ; cout<< "- Input Read Power: "<<inputReadPower <<"\n" ; cout<< "- Input Write Power: "<<inputWritePower <<"\n" ; cout<< "- Input Leakage Power: "<<inputLeakagePower <<"\n" ; cout<< "- Switch Power: "<<switchPower <<"\n" ; cout<< "- Switch Control Power: "<<switchPowerCtrl <<"\n" ; cout<< "- Switch Leakage Power: "<<switchPowerLeak <<"\n" ; cout<< "- Output DFF Power: "<<outputPower <<"\n" ; cout<< "- Output Clk Power: "<<outputPowerClk <<"\n" ; cout<< "- Output Control Power: "<<outputCtrlPower <<"\n" ; cout<< "- Total Power: "<<totalpower <<"\n"; cout<< " cout<< "\n" ; cout<< " cout<< "- OCN Area Summary\n" ; cout<< "- Channel Area: "<<channelArea<<"\n" ; cout<< "- Switch Area: "<<switchArea<<"\n" ; cout<< "- Input Area: "<<inputArea<<"\n" ; cout<< "- Output Area: "<<outputArea<<"\n" ; cout<< "- Total Area: "<<totalarea<<endl; cout<< " }
#include "net/cookies/cookie_monster.h" #include <algorithm> #include <memory> #include <string> #include <vector> #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/run_loop.h" #include "base/<API key>.h" #include "base/strings/<API key>.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/string_tokenizer.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" #include "base/threading/thread.h" #include "base/threading/<API key>.h" #include "base/time/time.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_constants.h" #include "net/cookies/<API key>.h" // For CookieStore mock #include "net/cookies/<API key>.h" #include "net/cookies/cookie_util.h" #include "net/cookies/parsed_cookie.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace net { using CookiePredicate = CookieStore::CookiePredicate; using base::Time; using base::TimeDelta; namespace { // TODO(erikwright): Replace the pre-existing <API key> (and // brethren) with this one, and remove the 'New' prefix. class <API key> : public CookieMonster::<API key> { public: MOCK_METHOD1(Load, void(const LoadedCallback& loaded_callback)); MOCK_METHOD2(LoadCookiesForKey, void(const std::string& key, const LoadedCallback& loaded_callback)); MOCK_METHOD1(AddCookie, void(const CanonicalCookie& cc)); MOCK_METHOD1(<API key>, void(const CanonicalCookie& cc)); MOCK_METHOD1(DeleteCookie, void(const CanonicalCookie& cc)); virtual void Flush(const base::Closure& callback) { if (!callback.is_null()) base::<API key>::Get()->PostTask(FROM_HERE, callback); } MOCK_METHOD0(<API key>, void()); private: virtual ~<API key>() {} }; // False means 'less than or equal', so we test both ways for full equal. MATCHER_P(CookieEquals, expected, "") { return !(arg.FullCompare(expected) || expected.FullCompare(arg)); } const char <API key>[] = "http: const char <API key>[] = "http: const char <API key>[] = "https: const char <API key>[] = "http: const char kOtherDomain[] = "http: bool <API key>(CanonicalCookie* to_save, const CanonicalCookie& cookie) { if (to_save) *to_save = cookie; return true; } bool <API key>(CanonicalCookie* to_save, const CanonicalCookie& cookie) { if (to_save) *to_save = cookie; return false; } bool <API key>(const std::string& true_value, const CanonicalCookie& cookie) { return cookie.Value() == true_value; } struct <API key> { static std::unique_ptr<CookieStore> Create() { return base::MakeUnique<CookieMonster>(nullptr, nullptr); } static const bool supports_http_only = true; static const bool <API key> = true; static const bool <API key> = true; static const bool filters_schemes = true; static const bool has_path_prefix_bug = false; static const int <API key> = 0; static const bool <API key> = false; }; struct <API key> { static std::unique_ptr<CookieStore> Create() { return base::MakeUnique<CookieMonster>(nullptr, nullptr); } static const bool supports_http_only = true; static const bool <API key> = true; static const bool <API key> = true; static const bool filters_schemes = true; static const bool has_path_prefix_bug = false; static const int <API key> = 0; static const bool <API key> = true; }; <API key>(CookieMonster, CookieStoreTest, <API key>); <API key>(<API key>, CookieStoreTest, <API key>); template <typename T> class <API key> : public CookieStoreTest<T> { public: using CookieStoreTest<T>::SetCookie; protected: using CookieStoreTest<T>::http_www_google_; using CookieStoreTest<T>::https_www_google_; CookieList <API key>(CookieMonster* cm, const GURL& url, const CookieOptions& options) { DCHECK(cm); <API key> callback; cm-><API key>( url, options, base::Bind(&<API key>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); return callback.cookies(); } bool SetAllCookies(CookieMonster* cm, const CookieList& list) { DCHECK(cm); <API key><bool> callback; cm->SetAllCookiesAsync(list, base::Bind(&<API key><bool>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); return callback.result(); } int <API key>(CookieMonster* cm, const base::Time& delete_begin, const base::Time& delete_end) { DCHECK(cm); <API key><int> callback; cm-><API key>( delete_begin, delete_end, base::Bind(&<API key><int>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); return callback.result(); } int <API key>(CookieMonster* cm, const base::Time delete_begin, const base::Time delete_end, const CookiePredicate& predicate) { DCHECK(cm); <API key><int> callback; cm-><API key>( delete_begin, delete_end, predicate, base::Bind(&<API key><int>::Run, base::Unretained(&callback))); callback.WaitUntilDone(); return callback.result(); } // Helper for <API key> test; repopulates CM with same layout // each time. void <API key>(CookieMonster* cm) { GURL <API key>(<API key>); GURL <API key>(<API key>); GURL <API key>(<API key>); GURL <API key>(<API key>); GURL url_other(kOtherDomain); this->DeleteAll(cm); // Static population for probe: // * Three levels of domain cookie (.b.a, .c.b.a, .d.c.b.a) // * Three levels of host cookie (w.b.a, w.c.b.a, w.d.c.b.a) // * http_only cookie (w.c.b.a) // * same_site cookie (w.c.b.a) // * Two secure cookies (.c.b.a, w.c.b.a) // * Two domain path cookies (.c.b.a/dir1, .c.b.a/dir1/dir2) // * Two host path cookies (w.c.b.a/dir1, w.c.b.a/dir1/dir2) // Domain cookies EXPECT_TRUE(this-><API key>( cm, <API key>, "dom_1", "A", ".harvard.edu", "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "dom_2", "B", ".math.harvard.edu", "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "dom_3", "C", ".bourbaki.math.harvard.edu", "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); // Host cookies EXPECT_TRUE(this-><API key>( cm, <API key>, "host_1", "A", std::string(), "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "host_2", "B", std::string(), "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "host_3", "C", std::string(), "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); // http_only cookie EXPECT_TRUE(this-><API key>( cm, <API key>, "httpo_check", "A", std::string(), "/", base::Time(), base::Time(), base::Time(), false, true, CookieSameSite::DEFAULT_MODE, <API key>)); // same-site cookie EXPECT_TRUE(this-><API key>( cm, <API key>, "firstp_check", "A", std::string(), "/", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::STRICT_MODE, <API key>)); // Secure cookies EXPECT_TRUE(this-><API key>( cm, <API key>, "sec_dom", "A", ".math.harvard.edu", "/", base::Time(), base::Time(), base::Time(), true, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "sec_host", "B", std::string(), "/", base::Time(), base::Time(), base::Time(), true, false, CookieSameSite::DEFAULT_MODE, <API key>)); // Domain path cookies EXPECT_TRUE(this-><API key>( cm, <API key>, "dom_path_1", "A", ".math.harvard.edu", "/dir1", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "dom_path_2", "B", ".math.harvard.edu", "/dir1/dir2", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); // Host path cookies EXPECT_TRUE(this-><API key>( cm, <API key>, "host_path_1", "A", std::string(), "/dir1", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(this-><API key>( cm, <API key>, "host_path_2", "B", std::string(), "/dir1/dir2", base::Time(), base::Time(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_EQ(14U, this->GetAllCookies(cm).size()); } Time <API key>(CookieMonster* cm) { const CookieList all_cookies(this->GetAllCookies(cm)); return all_cookies.front().LastAccessDate(); } bool FindAndDeleteCookie(CookieMonster* cm, const std::string& domain, const std::string& name) { CookieList cookies = this->GetAllCookies(cm); for (CookieList::iterator it = cookies.begin(); it != cookies.end(); ++it) if (it->Domain() == domain && it->Name() == name) return this-><API key>(cm, *it); return false; } int CountInString(const std::string& str, char c) { return std::count(str.begin(), str.end(), c); } void <API key>() { int domain_max_cookies = CookieMonster::kDomainMaxCookies; int <API key> = CookieMonster::kDomainPurgeCookies; const int <API key> = (domain_max_cookies + <API key>) * 2; // Add a bunch of cookies on a single host, should purge them. { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); for (int i = 0; i < <API key>; ++i) { std::string cookie = base::StringPrintf("a%03d=b", i); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), cookie)); std::string cookies = this->GetCookies(cm.get(), http_www_google_.url()); // Make sure we find it in the cookies. EXPECT_NE(cookies.find(cookie), std::string::npos); // Count the number of cookies. EXPECT_LE(CountInString(cookies, '='), domain_max_cookies); } } // Add a bunch of cookies on multiple hosts within a single eTLD. // Should keep at least kDomainMaxCookies - kDomainPurgeCookies // between them. We shouldn't go above kDomainMaxCookies for both together. GURL url_google_specific(http_www_google_.Format("http: { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); for (int i = 0; i < <API key>; ++i) { std::string cookie_general = base::StringPrintf("a%03d=b", i); EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), cookie_general)); std::string cookie_specific = base::StringPrintf("c%03d=b", i); EXPECT_TRUE(SetCookie(cm.get(), url_google_specific, cookie_specific)); std::string cookies_general = this->GetCookies(cm.get(), http_www_google_.url()); EXPECT_NE(cookies_general.find(cookie_general), std::string::npos); std::string cookies_specific = this->GetCookies(cm.get(), url_google_specific); EXPECT_NE(cookies_specific.find(cookie_specific), std::string::npos); EXPECT_LE((CountInString(cookies_general, '=') + CountInString(cookies_specific, '=')), domain_max_cookies); } // After all this, there should be at least // kDomainMaxCookies - kDomainPurgeCookies for both URLs. std::string cookies_general = this->GetCookies(cm.get(), http_www_google_.url()); std::string cookies_specific = this->GetCookies(cm.get(), url_google_specific); int total_cookies = (CountInString(cookies_general, '=') + CountInString(cookies_specific, '=')); EXPECT_GE(total_cookies, domain_max_cookies - <API key>); EXPECT_LE(total_cookies, domain_max_cookies); } } CookiePriority CharToPriority(char ch) { switch (ch) { case 'L': return COOKIE_PRIORITY_LOW; case 'M': return <API key>; case 'H': return <API key>; } NOTREACHED(); return <API key>; } // Instantiates a CookieMonster, adds multiple cookies (to http_www_google_) // with priorities specified by |coded_priority_str|, and tests priority-aware // domain cookie eviction. // Example: |<API key>| of "2MN 3LS MN 4HN" specifies sequential // (i.e., from least- to most-recently accessed) insertion of 2 // medium-priority non-secure cookies, 3 low-priority secure cookies, 1 // medium-priority non-secure cookie, and 4 high-priority non-secure cookies. // Within each priority, only the least-accessed cookies should be evicted. // Thus, to describe expected suriving cookies, it suffices to specify the // expected population of surviving cookies per priority, i.e., // |expected_low_count|, |<API key>|, and |expected_high_count|. void <API key>(CookieMonster* cm, const std::string& coded_priority_str, size_t expected_low_count, size_t <API key>, size_t expected_high_count, size_t expected_nonsecure, size_t expected_secure) { SCOPED_TRACE(coded_priority_str); this->DeleteAll(cm); int next_cookie_id = 0; // A list of cookie IDs, indexed by secure status, then by priority. std::vector<int> id_list[2][3]; // A list of all the cookies stored, along with their properties. std::vector<std::pair<bool, CookiePriority>> cookie_data; // Parse |coded_priority_str| and add cookies. for (const std::string& token : base::SplitString(coded_priority_str, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { DCHECK(!token.empty()); bool is_secure = token.back() == 'S'; // The second-to-last character is the priority. Grab and discard it. CookiePriority priority = CharToPriority(token[token.size() - 2]); // Discard the security status and priority tokens. The rest of the string // (possibly empty) specifies repetition. int rep = 1; if (!token.empty()) { bool result = base::StringToInt( base::StringPiece(token.begin(), token.end() - 2), &rep); DCHECK(result); } for (; rep > 0; --rep, ++next_cookie_id) { std::string cookie = base::StringPrintf("a%d=b;priority=%s;%s", next_cookie_id, <API key>(priority).c_str(), is_secure ? "secure" : ""); EXPECT_TRUE(SetCookie(cm, https_www_google_.url(), cookie)); cookie_data.push_back(std::make_pair(is_secure, priority)); id_list[is_secure][priority].push_back(next_cookie_id); } } int num_cookies = static_cast<int>(cookie_data.size()); // A list of cookie IDs, indexed by secure status, then by priority. std::vector<int> surviving_id_list[2][3]; // Parse the list of cookies std::string cookie_str = this->GetCookies(cm, https_www_google_.url()); size_t num_nonsecure = 0; size_t num_secure = 0; for (const std::string& token : base::SplitString( cookie_str, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { // Assuming *it is "a#=b", so extract and parse "#" portion. int id = -1; bool result = base::StringToInt( base::StringPiece(token.begin() + 1, token.end() - 2), &id); DCHECK(result); DCHECK_GE(id, 0); DCHECK_LT(id, num_cookies); surviving_id_list[cookie_data[id].first][cookie_data[id].second] .push_back(id); if (cookie_data[id].first) num_secure += 1; else num_nonsecure += 1; } EXPECT_EQ(expected_nonsecure, num_nonsecure); EXPECT_EQ(expected_secure, num_secure); // Validate each priority. size_t expected_count[3] = { expected_low_count, <API key>, expected_high_count}; for (int i = 0; i < 3; ++i) { size_t num_for_priority = surviving_id_list[0][i].size() + surviving_id_list[1][i].size(); EXPECT_EQ(expected_count[i], num_for_priority); // Verify that the remaining cookies are the most recent among those // with the same priorities. if (expected_count[i] == num_for_priority) { // Non-secure: std::sort(surviving_id_list[0][i].begin(), surviving_id_list[0][i].end()); EXPECT_TRUE(std::equal( surviving_id_list[0][i].begin(), surviving_id_list[0][i].end(), id_list[0][i].end() - surviving_id_list[0][i].size())); // Secure: std::sort(surviving_id_list[1][i].begin(), surviving_id_list[1][i].end()); EXPECT_TRUE(std::equal( surviving_id_list[1][i].begin(), surviving_id_list[1][i].end(), id_list[1][i].end() - surviving_id_list[1][i].size())); } } } // Represents a number of cookies to create, if they are Secure cookies, and // a url to add them to. struct CookiesEntry { size_t num_cookies; bool is_secure; }; // A number of secure and a number of non-secure alternative hosts to create // for testing. typedef std::pair<size_t, size_t> AltHosts; // Takes an array of CookieEntries which specify the number, type, and order // of cookies to create. Cookies are created in the order they appear in // cookie_entries. The value of cookie_entries[x].num_cookies specifies how // many cookies of that type to create consecutively, while if // cookie_entries[x].is_secure is |true|, those cookies will be marke as // Secure. void <API key>(const CookiesEntry* cookie_entries, size_t num_cookie_entries, size_t <API key>, size_t <API key>, const AltHosts* alt_host_entries) { std::unique_ptr<CookieMonster> cm; if (alt_host_entries == nullptr) { cm.reset(new CookieMonster(nullptr, nullptr)); } else { // When generating all of these cookies on alternate hosts, they need to // be all older than the max "safe" date for GC, which is currently 30 // days, so we set them to 60. cm = <API key>( alt_host_entries->first, alt_host_entries->first, alt_host_entries->second, alt_host_entries->second, 60); } int next_cookie_id = 0; for (size_t i = 0; i < num_cookie_entries; i++) { for (size_t j = 0; j < cookie_entries[i].num_cookies; j++) { std::string cookie; if (cookie_entries[i].is_secure) cookie = base::StringPrintf("a%d=b; Secure", next_cookie_id); else cookie = base::StringPrintf("a%d=b", next_cookie_id); EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), cookie)); ++next_cookie_id; } } CookieList cookies = this->GetAllCookies(cm.get()); EXPECT_EQ(<API key> + <API key>, cookies.size()); size_t <API key> = 0; size_t <API key> = 0; for (const auto& cookie : cookies) { if (cookie.IsSecure()) ++<API key>; else ++<API key>; } EXPECT_EQ(<API key>, <API key>); EXPECT_EQ(<API key>, <API key>); } void <API key>() { // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint. DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies); DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies - CookieMonster::kDomainPurgeCookies); std::unique_ptr<CookieMonster> cm(new CookieMonster(NULL, NULL)); // Each test case adds 181 cookies, so 31 cookies are evicted. // Cookie same priority, repeated for each priority. <API key>(cm.get(), "181LN", 150U, 0U, 0U, 150U, 0U); <API key>(cm.get(), "181MN", 0U, 150U, 0U, 150U, 0U); <API key>(cm.get(), "181HN", 0U, 0U, 150U, 150U, 0U); // Pairwise scenarios. // Round 1 => none; round2 => 31M; round 3 => none. <API key>(cm.get(), "10HN 171MN", 0U, 140U, 10U, 150U, 0U); // Round 1 => 10L; round2 => 21M; round 3 => none. <API key>(cm.get(), "141MN 40LN", 30U, 120U, 0U, 150U, 0U); // Round 1 => none; round2 => 30M; round 3 => 1H. <API key>(cm.get(), "101HN 80MN", 0U, 50U, 100U, 150U, 0U); // For {low, medium} priorities right on quota, different orders. // Round 1 => 1L; round 2 => none, round3 => 30H. <API key>(cm.get(), "31LN 50MN 100HN", 30U, 50U, 70U, 150U, 0U); // Round 1 => none; round 2 => 1M, round3 => 30H. <API key>(cm.get(), "51MN 100HN 30LN", 30U, 50U, 70U, 150U, 0U); // Round 1 => none; round 2 => none; round3 => 31H. <API key>(cm.get(), "101HN 50MN 30LN", 30U, 50U, 70U, 150U, 0U); // Round 1 => 10L; round 2 => 10M; round3 => 11H. <API key>(cm.get(), "81HN 60MN 40LN", 30U, 50U, 70U, 150U, 0U); // More complex scenarios. // Round 1 => 10L; round 2 => 10M; round 3 => 11H. <API key>(cm.get(), "21HN 60MN 40LN 60HN", 30U, 50U, 70U, 150U, 0U); // Round 1 => 10L; round 2 => 21M; round 3 => 0H. <API key>(cm.get(), "11HN 10MN 20LN 110MN 20LN 10HN", 30U, 99U, 21U, 150U, 0U); // Round 1 => none; round 2 => none; round 3 => 31H. <API key>(cm.get(), "11LN 10MN 140HN 10MN 10LN", 21U, 20U, 109U, 150U, 0U); // Round 1 => none; round 2 => 21M; round 3 => 10H. <API key>(cm.get(), "11MN 10HN 10LN 60MN 90HN", 10U, 50U, 90U, 150U, 0U); // Round 1 => none; round 2 => 31M; round 3 => none. <API key>(cm.get(), "11MN 10HN 10LN 90MN 60HN", 10U, 70U, 70U, 150U, 0U); // Round 1 => 20L; round 2 => 0; round 3 => 11H <API key>(cm.get(), "50LN 131HN", 30U, 0U, 120U, 150U, 0U); // Round 1 => 20L; round 2 => 0; round 3 => 11H <API key>(cm.get(), "131HN 50LN", 30U, 0U, 120U, 150U, 0U); // Round 1 => 20L; round 2 => none; round 3 => 11H. <API key>(cm.get(), "50HN 50LN 81HN", 30U, 0U, 120U, 150U, 0U); // Round 1 => 20L; round 2 => none; round 3 => 11H. <API key>(cm.get(), "81HN 50LN 50HN", 30U, 0U, 120U, 150U, 0U); } void <API key>() { // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint. DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies); DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies - CookieMonster::kDomainPurgeCookies); std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // Each test case adds 181 cookies, so 31 cookies are evicted. // Cookie same priority, repeated for each priority. // Round 1 => 31L; round2 => none; round 3 => none. <API key>(cm.get(), "181LS", 150U, 0U, 0U, 0U, 150U); // Round 1 => none; round2 => 31M; round 3 => none. <API key>(cm.get(), "181MS", 0U, 150U, 0U, 0U, 150U); // Round 1 => none; round2 => none; round 3 => 31H. <API key>(cm.get(), "181HS", 0U, 0U, 150U, 0U, 150U); // Pairwise scenarios. // Round 1 => none; round2 => 31M; round 3 => none. <API key>(cm.get(), "10HS 171MS", 0U, 140U, 10U, 0U, 150U); // Round 1 => 10L; round2 => 21M; round 3 => none. <API key>(cm.get(), "141MS 40LS", 30U, 120U, 0U, 0U, 150U); // Round 1 => none; round2 => 30M; round 3 => 1H. <API key>(cm.get(), "101HS 80MS", 0U, 50U, 100U, 0U, 150U); // For {low, medium} priorities right on quota, different orders. // Round 1 => 1L; round 2 => none, round3 => 30H. <API key>(cm.get(), "31LS 50MS 100HS", 30U, 50U, 70U, 0U, 150U); // Round 1 => none; round 2 => 1M, round3 => 30H. <API key>(cm.get(), "51MS 100HS 30LS", 30U, 50U, 70U, 0U, 150U); // Round 1 => none; round 2 => none; round3 => 31H. <API key>(cm.get(), "101HS 50MS 30LS", 30U, 50U, 70U, 0U, 150U); // Round 1 => 10L; round 2 => 10M; round3 => 11H. <API key>(cm.get(), "81HS 60MS 40LS", 30U, 50U, 70U, 0U, 150U); // More complex scenarios. // Round 1 => 10L; round 2 => 10M; round 3 => 11H. <API key>(cm.get(), "21HS 60MS 40LS 60HS", 30U, 50U, 70U, 0U, 150U); // Round 1 => 10L; round 2 => 21M; round 3 => none. <API key>(cm.get(), "11HS 10MS 20LS 110MS 20LS 10HS", 30U, 99U, 21U, 0U, 150U); // Round 1 => none; round 2 => none; round 3 => 31H. <API key>(cm.get(), "11LS 10MS 140HS 10MS 10LS", 21U, 20U, 109U, 0U, 150U); // Round 1 => none; round 2 => 21M; round 3 => 10H. <API key>(cm.get(), "11MS 10HS 10LS 60MS 90HS", 10U, 50U, 90U, 0U, 150U); // Round 1 => none; round 2 => 31M; round 3 => none. <API key>(cm.get(), "11MS 10HS 10LS 90MS 60HS", 10U, 70U, 70U, 0U, 150U); } void <API key>() { // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint. DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies); DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies - CookieMonster::kDomainPurgeCookies); std::unique_ptr<CookieMonster> cm(new CookieMonster(NULL, NULL)); // Each test case adds 180 secure cookies, and some non-secure cookie. The // secure cookies take priority, so the non-secure cookie is removed, along // with 30 secure cookies. Repeated for each priority, and with the // non-secure cookie as older and newer. // Round 1 => 1LN; round 2 => 30LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "1LN 180LS", 150U, 0U, 0U, 0U, 150U); // Round 1 => none; round 2 => none; round 3 => 1MN. // Round 4 => none; round 5 => 30MS; round 6 => none. <API key>(cm.get(), "1MN 180MS", 0U, 150U, 0U, 0U, 150U); // Round 1 => none; round 2 => none; round 3 => none. // Round 4 => 1HN; round 5 => none; round 6 => 30HS. <API key>(cm.get(), "1HN 180HS", 0U, 0U, 150U, 0U, 150U); // Round 1 => 1LN; round 2 => 30LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "180LS 1LN", 150U, 0U, 0U, 0U, 150U); // Round 1 => none; round 2 => none; round 3 => 1MN. // Round 4 => none; round 5 => 30MS; round 6 => none. <API key>(cm.get(), "180MS 1MN", 0U, 150U, 0U, 0U, 150U); // Round 1 => none; round 2 => none; round 3 => none. // Round 4 => 1HN; round 5 => none; round 6 => 30HS. <API key>(cm.get(), "180HS 1HN", 0U, 0U, 150U, 0U, 150U); // Low-priority secure cookies are removed before higher priority non-secure // cookies. // Round 1 => none; round 2 => 31LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "180LS 1MN", 149U, 1U, 0U, 1U, 149U); // Round 1 => none; round 2 => 31LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "180LS 1HN", 149U, 0U, 1U, 1U, 149U); // Round 1 => none; round 2 => 31LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "1MN 180LS", 149U, 1U, 0U, 1U, 149U); // Round 1 => none; round 2 => 31LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "1HN 180LS", 149U, 0U, 1U, 1U, 149U); // Higher-priority non-secure cookies are removed before any secure cookie // with greater than low-priority. Is it true? How about the quota? // Round 1 => none; round 2 => none; round 3 => none. // Round 4 => none; round 5 => 31MS; round 6 => none. <API key>(cm.get(), "180MS 1HN", 0U, 149U, 1U, 1U, 149U); // Round 1 => none; round 2 => none; round 3 => none. // Round 4 => none; round 5 => 31MS; round 6 => none. <API key>(cm.get(), "1HN 180MS", 0U, 149U, 1U, 1U, 149U); // Pairwise: // Round 1 => 31LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "1LS 180LN", 150U, 0U, 0U, 149U, 1U); // Round 1 => 31LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "100LS 81LN", 150U, 0U, 0U, 50U, 100U); // Round 1 => 31LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "150LS 31LN", 150U, 0U, 0U, 0U, 150U); // Round 1 => none; round 2 => none; round 3 => none. // Round 4 => 31HN; round 5 => none; round 6 => none. <API key>(cm.get(), "1LS 180HN", 1U, 0U, 149U, 149U, 1U); // Round 1 => none; round 2 => 31LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "100LS 81HN", 69U, 0U, 81U, 81U, 69U); // Round 1 => none; round 2 => 31LS; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "150LS 31HN", 119U, 0U, 31U, 31U, 119U); // Quota calculations inside non-secure/secure blocks remain in place: // Round 1 => none; round 2 => 20LS; round 3 => none. // Round 4 => 11HN; round 5 => none; round 6 => none. <API key>(cm.get(), "50HN 50LS 81HS", 30U, 0U, 120U, 39U, 111U); // Round 1 => none; round 2 => none; round 3 => 31MN. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "11MS 10HN 10LS 90MN 60HN", 10U, 70U, 70U, 129U, 21U); // Round 1 => 31LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. <API key>(cm.get(), "40LS 40LN 101HS", 49U, 0U, 101U, 9U, 141U); // Multiple GC rounds end up with consistent behavior: // GC is started as soon as there are 181 cookies in the store. // On each major round it tries to preserve the quota for each priority. // It is not aware about more cookies going in. // 1 GC notices there are 181 cookies - 100HS 81LN 0MN // Round 1 => 31LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. // 2 GC notices there are 181 cookies - 100HS 69LN 12MN // Round 1 => 31LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => none. // 3 GC notices there are 181 cookies - 100HS 38LN 43MN // Round 1 => 8LN; round 2 => none; round 3 => none. // Round 4 => none; round 5 => none; round 6 => 23HS. // 4 GC notcies there are 181 cookies - 77HS 30LN 74MN // Round 1 => none; round 2 => none; round 3 => 24MN. // Round 4 => none; round 5 => none; round 6 => 7HS. <API key>(cm.get(), "100HS 100LN 100MN", 30U, 76U, 70U, 106U, 70U); } // Function for creating a CM with a number of cookies in it, // no store (and hence no ability to affect access time). CookieMonster* CreateMonsterForGC(int num_cookies) { CookieMonster* cm(new CookieMonster(NULL, NULL)); for (int i = 0; i < num_cookies; i++) { SetCookie(cm, GURL(base::StringPrintf("http://h%05d.izzle", i)), "a=1"); } return cm; } bool IsCookieInList(const CanonicalCookie& cookie, const CookieList& list) { for (CookieList::const_iterator it = list.begin(); it != list.end(); ++it) { if (it->Name() == cookie.Name() && it->Value() == cookie.Value() && it->Domain() == cookie.Domain() && it->Path() == cookie.Path() && it->CreationDate() == cookie.CreationDate() && it->ExpiryDate() == cookie.ExpiryDate() && it->LastAccessDate() == cookie.LastAccessDate() && it->IsSecure() == cookie.IsSecure() && it->IsHttpOnly() == cookie.IsHttpOnly() && it->Priority() == cookie.Priority()) { return true; } } return false; } }; using CookieMonsterTest = <API key><<API key>>; using <API key> = <API key><<API key>>; // TODO(erikwright): Replace the other callbacks and synchronous helper methods // in this test suite with these Mocks. template <typename T, typename C> class MockCookieCallback { public: C AsCallback() { return base::Bind(&T::Invoke, base::Unretained(static_cast<T*>(this))); } }; class <API key> : public MockCookieCallback<<API key>, CookieStore::GetCookiesCallback> { public: MOCK_METHOD1(Invoke, void(const std::string& cookies)); }; class <API key> : public MockCookieCallback<<API key>, CookieStore::SetCookiesCallback> { public: MOCK_METHOD1(Invoke, void(bool success)); }; class MockClosure : public MockCookieCallback<MockClosure, base::Closure> { public: MOCK_METHOD0(Invoke, void(void)); }; class <API key> : public MockCookieCallback<<API key>, CookieMonster::<API key>> { public: MOCK_METHOD1(Invoke, void(const CookieList& cookies)); }; class MockDeleteCallback : public MockCookieCallback<MockDeleteCallback, CookieMonster::DeleteCallback> { public: MOCK_METHOD1(Invoke, void(int num_deleted)); }; struct CookiesInputInfo { const GURL url; const std::string name; const std::string value; const std::string domain; const std::string path; const base::Time expiration_time; bool secure; bool http_only; CookieSameSite same_site; CookiePriority priority; }; ACTION_P(QuitRunLoop, run_loop) { run_loop->Quit(); } // TODO(erikwright): When the synchronous helpers 'GetCookies' etc. are removed, // rename these, removing the 'Action' suffix. ACTION_P4(DeleteCookieAction, cookie_monster, url, name, callback) { cookie_monster->DeleteCookieAsync(url, name, callback->AsCallback()); } ACTION_P3(GetCookiesAction, cookie_monster, url, callback) { cookie_monster-><API key>(url, CookieOptions(), callback->AsCallback()); } ACTION_P4(SetCookieAction, cookie_monster, url, cookie_line, callback) { cookie_monster-><API key>(url, cookie_line, CookieOptions(), callback->AsCallback()); } ACTION_P3(SetAllCookiesAction, cookie_monster, list, callback) { cookie_monster->SetAllCookiesAsync(list, callback->AsCallback()); } ACTION_P4(<API key>, cookie_monster, delete_begin, delete_end, callback) { cookie_monster-><API key>(delete_begin, delete_end, callback->AsCallback()); } ACTION_P3(<API key>, cookie_monster, cc, callback) { cookie_monster-><API key>( cc.url, cc.name, cc.value, cc.domain, cc.path, base::Time(), cc.expiration_time, base::Time(), cc.secure, cc.http_only, cc.same_site, false /* enforces strict secure cookies */, cc.priority, callback->AsCallback()); } ACTION_P2(GetAllCookiesAction, cookie_monster, callback) { cookie_monster->GetAllCookiesAsync(callback->AsCallback()); } ACTION_P5(<API key>, cookie_monster, delete_begin, delete_end, predicate, callback) { cookie_monster-><API key>( delete_begin, delete_end, predicate, callback->AsCallback()); } ACTION_P3(<API key>, cookie_monster, cookie, callback) { cookie_monster-><API key>(cookie, callback->AsCallback()); } ACTION_P2(DeleteAllAction, cookie_monster, callback) { cookie_monster->DeleteAllAsync(callback->AsCallback()); } ACTION_P3(<API key>, cookie_monster, url, callback) { cookie_monster-><API key>(url, CookieOptions(), callback->AsCallback()); } ACTION_P3(<API key>, cookie_monster, url, callback) { cookie_monster-><API key>(url, callback->AsCallback()); } ACTION_P(PushCallbackAction, callback_vector) { callback_vector->push(arg1); } ACTION_P2(<API key>, cookie_monster, callback) { cookie_monster-><API key>(callback->AsCallback()); } } // namespace // This test suite verifies the task deferral behaviour of the CookieMonster. // Specifically, for each asynchronous method, verify that: // 1. invoking it on an uninitialized cookie store causes the store to begin // chain-loading its backing data or loading data for a specific domain key // (eTLD+1). // 2. The initial invocation does not complete until the loading completes. // 3. Invocations after the loading has completed complete immediately. class <API key> : public CookieMonsterTest { protected: <API key>() : expect_load_called_(false) { persistent_store_ = new <API key>(); cookie_monster_.reset(new CookieMonster(persistent_store_.get(), nullptr)); } // Defines a cookie to be returned from <API key>::Load void DeclareLoadedCookie(const GURL& url, const std::string& cookie_line, const base::Time& creation_time) { AddCookieToList(url, cookie_line, creation_time, &loaded_cookies_); } // Runs the message loop, waiting until <API key>::Load is called. // Call CompleteLoading to cause the load to complete. void WaitForLoadCall() { load_run_loop_.Run(); // Verify that PeristentStore::Load was called. testing::Mock::VerifyAndClear(persistent_store_.get()); } // Invokes the <API key>::LoadCookiesForKey completion callbacks // and <API key>::Load completion callback. void CompleteLoading() { while (!<API key>.empty()) { <API key>.front().Run(std::move(loaded_cookies_)); loaded_cookies_.clear(); <API key>.pop(); } loaded_callback_.Run(std::move(loaded_cookies_)); } // Performs the provided action, expecting it to cause a call to // <API key>::Load. Call WaitForLoadCall to verify the load call // is received. void BeginWith(testing::Action<void(void)> action) { EXPECT_CALL(*this, Begin()).WillOnce(action); ExpectLoadCall(); Begin(); } void <API key>(std::string key, testing::Action<void(void)> action) { EXPECT_CALL(*this, Begin()).WillOnce(action); ExpectLoadCall(); <API key>(key); Begin(); } // Declares an expectation that <API key>::Load will be called, // saving the provided callback and sending a quit to |load_run_loop_|. void ExpectLoadCall() { // Make sure the |load_run_loop_| is not reused. CHECK(!expect_load_called_); expect_load_called_ = true; EXPECT_CALL(*persistent_store_.get(), Load(testing::_)) .WillOnce(testing::DoAll(testing::SaveArg<0>(&loaded_callback_), QuitRunLoop(&load_run_loop_))); } // Declares an expectation that <API key>::LoadCookiesForKey // will be called, saving the provided callback. void <API key>(const std::string& key) { EXPECT_CALL(*persistent_store_.get(), LoadCookiesForKey(key, testing::_)) .WillOnce(PushCallbackAction(&<API key>)); } // Invokes the initial action. MOCK_METHOD0(Begin, void(void)); // Returns the CookieMonster instance under test. CookieMonster& cookie_monster() { return *cookie_monster_.get(); } private: // Declares that mock expectations in this test suite are strictly ordered. testing::InSequence in_sequence_; // Holds cookies to be returned from <API key>::Load or // <API key>::LoadCookiesForKey. std::vector<std::unique_ptr<CanonicalCookie>> loaded_cookies_; // Stores the callback passed from the CookieMonster to the // <API key>::Load CookieMonster::<API key>::LoadedCallback loaded_callback_; // Stores the callback passed from the CookieMonster to the // <API key>::LoadCookiesForKey std::queue<CookieMonster::<API key>::LoadedCallback> <API key>; // base::RunLoop used to wait for <API key>::Load to be called. base::RunLoop load_run_loop_; // Indicates whether ExpectLoadCall() has been called. bool expect_load_called_; // Stores the CookieMonster under test. std::unique_ptr<CookieMonster> cookie_monster_; // Stores the mock <API key>. scoped_refptr<<API key>> persistent_store_; }; TEST_F(<API key>, DeferredGetCookies) { DeclareLoadedCookie(http_www_google_.url(), "X=1; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(3)); <API key> <API key>; <API key>( http_www_google_.domain(), GetCookiesAction(&cookie_monster(), http_www_google_.url(), &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke("X=1")) .WillOnce(GetCookiesAction(&cookie_monster(), http_www_google_.url(), &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke("X=1")).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, DeferredSetCookie) { <API key> <API key>; <API key>( http_www_google_.domain(), SetCookieAction(&cookie_monster(), http_www_google_.url(), "A=B", &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke(true)) .WillOnce(SetCookieAction(&cookie_monster(), http_www_google_.url(), "X=Y", &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(true)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { <API key> <API key>; CookieList list; list.push_back(*CanonicalCookie::Create( http_www_google_.url(), "A", "B", http_www_google_.domain(), "/", base::Time::Now(), base::Time(), false, true, CookieSameSite::DEFAULT_MODE, false, <API key>)); list.push_back(*CanonicalCookie::Create( http_www_google_.url(), "C", "D", http_www_google_.domain(), "/", base::Time::Now(), base::Time(), false, true, CookieSameSite::DEFAULT_MODE, false, <API key>)); BeginWith( SetAllCookiesAction(&cookie_monster(), list, &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke(true)) .WillOnce( SetAllCookiesAction(&cookie_monster(), list, &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(true)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { MockClosure <API key>; <API key>( http_www_google_.domain(), DeleteCookieAction(&cookie_monster(), http_www_google_.url(), "A", &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke()) .WillOnce(DeleteCookieAction(&cookie_monster(), http_www_google_.url(), "X", &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke()).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { <API key> <API key>; CookiesInputInfo cookie_info = {www_google_foo_.url(), "A", "B", std::string(), "/foo", base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>}; <API key>( http_www_google_.domain(), <API key>(&cookie_monster(), cookie_info, &<API key>)); WaitForLoadCall(); CookiesInputInfo cookie_info_exp = {www_google_foo_.url(), "A", "B", std::string(), "/foo", base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>}; EXPECT_CALL(<API key>, Invoke(true)) .WillOnce(<API key>(&cookie_monster(), cookie_info_exp, &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(true)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { DeclareLoadedCookie(http_www_google_.url(), "X=1; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(3)); <API key> <API key>; BeginWith(GetAllCookiesAction(&cookie_monster(), &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke(testing::_)) .WillOnce( GetAllCookiesAction(&cookie_monster(), &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(testing::_)) .WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { DeclareLoadedCookie(http_www_google_.url(), "X=1; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(3)); <API key> <API key>; <API key>( http_www_google_.domain(), <API key>(&cookie_monster(), http_www_google_.url(), &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke(testing::_)) .WillOnce(<API key>(&cookie_monster(), http_www_google_.url(), &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(testing::_)) .WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { DeclareLoadedCookie(http_www_google_.url(), "X=1; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(3)); <API key> <API key>; <API key>(http_www_google_.domain(), <API key>( &cookie_monster(), http_www_google_.url(), &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke(testing::_)) .WillOnce(<API key>( &cookie_monster(), http_www_google_.url(), &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(testing::_)) .WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { MockDeleteCallback delete_callback; BeginWith(DeleteAllAction(&cookie_monster(), &delete_callback)); WaitForLoadCall(); EXPECT_CALL(delete_callback, Invoke(false)) .WillOnce(DeleteAllAction(&cookie_monster(), &delete_callback)); base::RunLoop loop; EXPECT_CALL(delete_callback, Invoke(false)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { MockDeleteCallback delete_callback; BeginWith(<API key>(&cookie_monster(), base::Time(), base::Time::Now(), &delete_callback)); WaitForLoadCall(); EXPECT_CALL(delete_callback, Invoke(false)) .WillOnce(<API key>(&cookie_monster(), base::Time(), base::Time::Now(), &delete_callback)); base::RunLoop loop; EXPECT_CALL(delete_callback, Invoke(false)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { MockDeleteCallback delete_callback; CookiePredicate predicate = base::Bind(&<API key>, nullptr); BeginWith(<API key>( &cookie_monster(), base::Time(), base::Time::Now(), predicate, &delete_callback)); WaitForLoadCall(); EXPECT_CALL(delete_callback, Invoke(false)) .WillOnce(<API key>( &cookie_monster(), base::Time(), base::Time::Now(), predicate, &delete_callback)); base::RunLoop loop; EXPECT_CALL(delete_callback, Invoke(false)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { std::vector<std::unique_ptr<CanonicalCookie>> cookies; std::unique_ptr<CanonicalCookie> cookie = <API key>( http_www_google_.url(), "X=1; path=/", base::Time::Now()); MockDeleteCallback <API key>; BeginWith(<API key>(&cookie_monster(), *cookie, &<API key>)); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke(0)) .WillOnce(<API key>(&cookie_monster(), *cookie, &<API key>)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke(0)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(<API key>, <API key>) { MockDeleteCallback delete_callback; BeginWith(<API key>(&cookie_monster(), &delete_callback)); WaitForLoadCall(); EXPECT_CALL(delete_callback, Invoke(false)) .WillOnce( <API key>(&cookie_monster(), &delete_callback)); base::RunLoop loop; EXPECT_CALL(delete_callback, Invoke(false)).WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } // Verify that a series of queued tasks are executed in order upon loading of // the backing store and that new tasks received while the queued tasks are // being dispatched go to the end of the queue. TEST_F(<API key>, DeferredTaskOrder) { DeclareLoadedCookie(http_www_google_.url(), "X=1; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(3)); <API key> <API key>; <API key> <API key>; <API key> <API key>; EXPECT_CALL(*this, Begin()) .WillOnce(testing::DoAll( GetCookiesAction(&cookie_monster(), http_www_google_.url(), &<API key>), SetCookieAction(&cookie_monster(), http_www_google_.url(), "A=B", &<API key>))); ExpectLoadCall(); <API key>(http_www_google_.domain()); Begin(); WaitForLoadCall(); EXPECT_CALL(<API key>, Invoke("X=1")) .WillOnce(GetCookiesAction(&cookie_monster(), http_www_google_.url(), &<API key>)); EXPECT_CALL(<API key>, Invoke(true)); base::RunLoop loop; EXPECT_CALL(<API key>, Invoke("A=B; X=1")) .WillOnce(QuitRunLoop(&loop)); CompleteLoading(); loop.Run(); } TEST_F(CookieMonsterTest, TestCookieDeleteAll) { scoped_refptr<<API key>> store(new <API key>); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); CookieOptions options; options.<API key>(); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), kValidCookieLine)); EXPECT_EQ("A=B", GetCookies(cm.get(), http_www_google_.url())); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), "C=D; httponly", options)); EXPECT_EQ("A=B; C=D", <API key>(cm.get(), http_www_google_.url(), options)); EXPECT_EQ(2, DeleteAll(cm.get())); EXPECT_EQ("", <API key>(cm.get(), http_www_google_.url(), options)); EXPECT_EQ(0u, store->commands().size()); // Create a persistent cookie. EXPECT_TRUE(SetCookie( cm.get(), http_www_google_.url(), std::string(kValidCookieLine) + "; expires=Mon, 18-Apr-22 22:50:13 GMT")); ASSERT_EQ(1u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type); EXPECT_EQ(1, DeleteAll(cm.get())); // sync_to_store = true. ASSERT_EQ(2u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type); EXPECT_EQ("", <API key>(cm.get(), http_www_google_.url(), options)); } TEST_F(CookieMonsterTest, <API key>) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); Time now = Time::Now(); // Nothing has been added so nothing should be deleted. EXPECT_EQ(0, <API key>(cm.get(), now - TimeDelta::FromDays(99), Time())); // Create 5 cookies with different creation dates. EXPECT_TRUE( cm-><API key>(http_www_google_.url(), "T-0=Now", now)); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-1=Yesterday", now - TimeDelta::FromDays(1))); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-2=DayBefore", now - TimeDelta::FromDays(2))); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-3=ThreeDays", now - TimeDelta::FromDays(3))); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-7=LastWeek", now - TimeDelta::FromDays(7))); // Try to delete threedays and the daybefore. EXPECT_EQ(2, <API key>(cm.get(), now - TimeDelta::FromDays(3), now - TimeDelta::FromDays(1))); // Try to delete yesterday, also make sure that delete_end is not // inclusive. EXPECT_EQ( 1, <API key>(cm.get(), now - TimeDelta::FromDays(2), now)); // Make sure the delete_begin is inclusive. EXPECT_EQ( 1, <API key>(cm.get(), now - TimeDelta::FromDays(7), now)); // Delete the last (now) item. EXPECT_EQ(1, <API key>(cm.get(), Time(), Time())); // Really make sure everything is gone. EXPECT_EQ(0, DeleteAll(cm.get())); } TEST_F(CookieMonsterTest, <API key>) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); Time now = Time::Now(); CanonicalCookie test_cookie; CookiePredicate true_predicate = base::Bind(&<API key>, &test_cookie); CookiePredicate false_predicate = base::Bind(&<API key>, &test_cookie); // Nothing has been added so nothing should be deleted. EXPECT_EQ( 0, <API key>( cm.get(), now - TimeDelta::FromDays(99), Time(), true_predicate)); // Create 5 cookies with different creation dates. EXPECT_TRUE( cm-><API key>(http_www_google_.url(), "T-0=Now", now)); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-1=Yesterday", now - TimeDelta::FromDays(1))); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-2=DayBefore", now - TimeDelta::FromDays(2))); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-3=ThreeDays", now - TimeDelta::FromDays(3))); EXPECT_TRUE(cm-><API key>( http_www_google_.url(), "T-7=LastWeek", now - TimeDelta::FromDays(7))); // Try to delete threedays and the daybefore, but we should do nothing due // to the predicate. EXPECT_EQ(0, <API key>( cm.get(), now - TimeDelta::FromDays(3), now - TimeDelta::FromDays(1), false_predicate)); // Same as above with a null predicate, so it shouldn't delete anything. EXPECT_EQ(0, <API key>( cm.get(), now - TimeDelta::FromDays(3), now - TimeDelta::FromDays(1), CookiePredicate())); // Same as above, but we use the true_predicate, so it works. EXPECT_EQ(2, <API key>( cm.get(), now - TimeDelta::FromDays(3), now - TimeDelta::FromDays(1), true_predicate)); // Try to delete yesterday, also make sure that delete_end is not // inclusive. EXPECT_EQ(0, <API key>( cm.get(), now - TimeDelta::FromDays(2), now, false_predicate)); EXPECT_EQ(1, <API key>( cm.get(), now - TimeDelta::FromDays(2), now, true_predicate)); // Check our cookie values. std::unique_ptr<CanonicalCookie> expected_cookie = CanonicalCookie::Create(http_www_google_.url(), "T-1=Yesterday", now - TimeDelta::FromDays(1), CookieOptions()); EXPECT_THAT(test_cookie, CookieEquals(*expected_cookie)) << "Actual:\n" << test_cookie.DebugString() << "\nExpected:\n" << expected_cookie->DebugString(); // Make sure the delete_begin is inclusive. EXPECT_EQ(0, <API key>( cm.get(), now - TimeDelta::FromDays(7), now, false_predicate)); EXPECT_EQ(1, <API key>( cm.get(), now - TimeDelta::FromDays(7), now, true_predicate)); // Delete the last (now) item. EXPECT_EQ(0, <API key>(cm.get(), Time(), Time(), false_predicate)); EXPECT_EQ(1, <API key>(cm.get(), Time(), Time(), true_predicate)); expected_cookie = CanonicalCookie::Create(http_www_google_.url(), "T-0=Now", now, CookieOptions()); EXPECT_THAT(test_cookie, CookieEquals(*expected_cookie)) << "Actual:\n" << test_cookie.DebugString() << "\nExpected:\n" << expected_cookie->DebugString(); // Really make sure everything is gone. EXPECT_EQ(0, DeleteAll(cm.get())); } static const base::TimeDelta <API key> = base::TimeDelta::FromMilliseconds(200); static const base::TimeDelta kAccessDelay = <API key> + base::TimeDelta::FromMilliseconds(20); TEST_F(CookieMonsterTest, TestLastAccess) { std::unique_ptr<CookieMonster> cm( new CookieMonster(nullptr, nullptr, <API key>)); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B")); const Time last_access_date(<API key>(cm.get())); // Reading the cookie again immediately shouldn't update the access date, // since we're inside the threshold. EXPECT_EQ("A=B", GetCookies(cm.get(), http_www_google_.url())); EXPECT_EQ(last_access_date, <API key>(cm.get())); // Reading after a short wait will update the access date, if the cookie // is requested with options that would update the access date. First, test // that the flag's behavior is respected. base::PlatformThread::Sleep(kAccessDelay); CookieOptions options; options.<API key>(); EXPECT_EQ("A=B", <API key>(cm.get(), http_www_google_.url(), options)); EXPECT_EQ(last_access_date, <API key>(cm.get())); // Getting all cookies for a URL doesn't update the accessed time either. CookieList cookies = GetAllCookiesForURL(cm.get(), http_www_google_.url()); CookieList::iterator it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ(http_www_google_.host(), it->Domain()); EXPECT_EQ("A", it->Name()); EXPECT_EQ("B", it->Value()); EXPECT_EQ(last_access_date, <API key>(cm.get())); EXPECT_TRUE(++it == cookies.end()); // If the flag isn't set, the last accessed time should be updated. options = CookieOptions(); EXPECT_EQ("A=B", <API key>(cm.get(), http_www_google_.url(), options)); EXPECT_FALSE(last_access_date == <API key>(cm.get())); } TEST_F(CookieMonsterTest, <API key>) { <API key>(); } TEST_F(CookieMonsterTest, <API key>) { <API key>(); } TEST_F(CookieMonsterTest, <API key>) { <API key>(); } TEST_F(<API key>, <API key>) { <API key>(); } TEST_F(CookieMonsterTest, <API key>) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); std::unique_ptr<CookieMonster> cm_foo(new CookieMonster(nullptr, nullptr)); // Only cm_foo should allow foo:// cookies. std::vector<std::string> schemes; schemes.push_back("foo"); cm_foo-><API key>(schemes); GURL foo_url("foo://host/path"); GURL http_url("http://host/path"); EXPECT_TRUE(SetCookie(cm.get(), http_url, "x=1")); EXPECT_FALSE(SetCookie(cm.get(), foo_url, "x=1")); EXPECT_TRUE(SetCookie(cm_foo.get(), foo_url, "x=1")); EXPECT_FALSE(SetCookie(cm_foo.get(), http_url, "x=1")); } TEST_F(CookieMonsterTest, GetAllCookiesForURL) { std::unique_ptr<CookieMonster> cm( new CookieMonster(nullptr, nullptr, <API key>)); // Create an httponly cookie. CookieOptions options; options.<API key>(); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), "A=B; httponly", options)); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), http_www_google_.Format("C=D; domain=.%D"), options)); EXPECT_TRUE(<API key>( cm.get(), https_www_google_.url(), http_www_google_.Format("E=F; domain=.%D; secure"), options)); const Time last_access_date(<API key>(cm.get())); base::PlatformThread::Sleep(kAccessDelay); // Check cookies for url. CookieList cookies = GetAllCookiesForURL(cm.get(), http_www_google_.url()); CookieList::iterator it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ(http_www_google_.host(), it->Domain()); EXPECT_EQ("A", it->Name()); ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ(http_www_google_.Format(".%D"), it->Domain()); EXPECT_EQ("C", it->Name()); ASSERT_TRUE(++it == cookies.end()); // Check cookies for url excluding http-only cookies. cookies = <API key>(cm.get(), http_www_google_.url(), CookieOptions()); it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ(http_www_google_.Format(".%D"), it->Domain()); EXPECT_EQ("C", it->Name()); ASSERT_TRUE(++it == cookies.end()); // Test secure cookies. cookies = GetAllCookiesForURL(cm.get(), https_www_google_.url()); it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ(http_www_google_.host(), it->Domain()); EXPECT_EQ("A", it->Name()); ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ(http_www_google_.Format(".%D"), it->Domain()); EXPECT_EQ("C", it->Name()); ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ(http_www_google_.Format(".%D"), it->Domain()); EXPECT_EQ("E", it->Name()); ASSERT_TRUE(++it == cookies.end()); // Reading after a short wait should not update the access date. EXPECT_EQ(last_access_date, <API key>(cm.get())); } TEST_F(CookieMonsterTest, <API key>) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); CookieOptions options; EXPECT_TRUE(<API key>(cm.get(), www_google_foo_.url(), "A=B; path=/foo;", options)); EXPECT_TRUE(<API key>(cm.get(), www_google_bar_.url(), "C=D; path=/bar;", options)); EXPECT_TRUE( <API key>(cm.get(), http_www_google_.url(), "E=F;", options)); CookieList cookies = GetAllCookiesForURL(cm.get(), www_google_foo_.url()); CookieList::iterator it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ("A", it->Name()); EXPECT_EQ("/foo", it->Path()); ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ("E", it->Name()); EXPECT_EQ("/", it->Path()); ASSERT_TRUE(++it == cookies.end()); cookies = GetAllCookiesForURL(cm.get(), www_google_bar_.url()); it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ("C", it->Name()); EXPECT_EQ("/bar", it->Path()); ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ("E", it->Name()); EXPECT_EQ("/", it->Path()); ASSERT_TRUE(++it == cookies.end()); } TEST_F(CookieMonsterTest, CookieSorting) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B1; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B2; path=/foo")); EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), "B=B3; path=/foo/bar")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A1; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A2; path=/foo")); EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), "A=A3; path=/foo/bar")); // Re-set cookie which should not change sort order. EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), "B=B3; path=/foo/bar")); CookieList cookies = GetAllCookies(cm.get()); ASSERT_EQ(6u, cookies.size()); // According to RFC 6265 5.3 (11) re-setting this cookie should retain the // initial creation-time from above, and the sort order should not change. // Chrome's current implementation deviates from the spec so capturing this to // avoid any inadvertent changes to this behavior. EXPECT_EQ("A3", cookies[0].Value()); EXPECT_EQ("B3", cookies[1].Value()); EXPECT_EQ("B2", cookies[2].Value()); EXPECT_EQ("A2", cookies[3].Value()); EXPECT_EQ("B1", cookies[4].Value()); EXPECT_EQ("A1", cookies[5].Value()); } TEST_F(CookieMonsterTest, DeleteCookieByName) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A1; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A2; path=/foo")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=A3; path=/bar")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B1; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B2; path=/foo")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=B3; path=/bar")); DeleteCookie(cm.get(), http_www_google_.AppendPath("foo/bar"), "A"); CookieList cookies = GetAllCookies(cm.get()); size_t expected_size = 4; EXPECT_EQ(expected_size, cookies.size()); for (CookieList::iterator it = cookies.begin(); it != cookies.end(); ++it) { EXPECT_NE("A1", it->Value()); EXPECT_NE("A2", it->Value()); } } // Tests importing from a persistent cookie store that contains duplicate // equivalent cookies. This situation should be handled by removing the // duplicate cookie (both from the in-memory cache, and from the backing store). TEST_F(CookieMonsterTest, <API key>) { scoped_refptr<<API key>> store(new <API key>); // We will fill some initial cookies into the <API key>, // to simulate a database with 4 duplicates. Note that we need to // be careful not to have any duplicate creation times at all (as it's a // violation of a CookieMonster invariant) even if Time::Now() doesn't // move between calls. std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies; // Insert 4 cookies with name "X" on path "/", with varying creation // dates. We expect only the most recent one to be preserved following // the import. AddCookieToList(GURL("http: "X=1; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(3), &initial_cookies); AddCookieToList(GURL("http: "X=2; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(1), &initial_cookies); AddCookieToList(GURL("http: "X=3; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(4), &initial_cookies); AddCookieToList(GURL("http: "X=4; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now(), &initial_cookies); // Insert 2 cookies with name "X" on path "/2", with varying creation // dates. We expect only the most recent one to be preserved the import. AddCookieToList(GURL("http: "X=a1; path=/2; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(9), &initial_cookies); AddCookieToList(GURL("http: "X=a2; path=/2; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(2), &initial_cookies); // Insert 1 cookie with name "Y" on path "/". AddCookieToList(GURL("http: "Y=a; path=/; expires=Mon, 18-Apr-22 22:50:14 GMT", Time::Now() + TimeDelta::FromDays(10), &initial_cookies); // Inject our initial cookies into the mock <API key>. store->SetLoadExpectation(true, std::move(initial_cookies)); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Verify that duplicates were not imported for path "/". // (If this had failed, GetCookies() would have also returned X=1, X=2, X=4). EXPECT_EQ("X=3; Y=a", GetCookies(cm.get(), GURL("http: // Verify that same-named cookie on a different path ("/x2") didn't get // messed up. EXPECT_EQ("X=a1; X=3; Y=a", GetCookies(cm.get(), GURL("http: // Verify that the <API key> was told to kill its 4 duplicates. ASSERT_EQ(4u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[0].type); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[2].type); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[3].type); } // Tests importing from a persistent cookie store that contains cookies // with duplicate creation times. This situation should be handled by // dropping the cookies before insertion/visibility to user. TEST_F(CookieMonsterTest, <API key>) { scoped_refptr<<API key>> store(new <API key>); Time now(Time::Now()); Time earlier(now - TimeDelta::FromDays(1)); // Insert 8 cookies, four with the current time as creation times, and // four with the earlier time as creation times. We should only get // two cookies remaining, but which two (other than that there should // be one from each set) will be random. std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies; AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); AddCookieToList(GURL("http: &initial_cookies); // Inject our initial cookies into the mock <API key>. store->SetLoadExpectation(true, std::move(initial_cookies)); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); CookieList list(GetAllCookies(cm.get())); EXPECT_EQ(2U, list.size()); // Confirm that we have one of each. std::string name1(list[0].Name()); std::string name2(list[1].Name()); EXPECT_TRUE(name1 == "X" || name2 == "X"); EXPECT_TRUE(name1 == "Y" || name2 == "Y"); EXPECT_NE(name1, name2); } TEST_F(CookieMonsterTest, <API key>) { scoped_refptr<<API key>> store(new <API key>); scoped_refptr<<API key>> delegate( new <API key>); std::unique_ptr<CookieMonster> cm( new CookieMonster(store.get(), delegate.get())); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "C=D")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "E=F")); EXPECT_EQ("A=B; C=D; E=F", GetCookies(cm.get(), http_www_google_.url())); ASSERT_EQ(3u, delegate->changes().size()); EXPECT_FALSE(delegate->changes()[0].second); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[0].first.Domain()); EXPECT_EQ("A", delegate->changes()[0].first.Name()); EXPECT_EQ("B", delegate->changes()[0].first.Value()); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[1].first.Domain()); EXPECT_FALSE(delegate->changes()[1].second); EXPECT_EQ("C", delegate->changes()[1].first.Name()); EXPECT_EQ("D", delegate->changes()[1].first.Value()); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[2].first.Domain()); EXPECT_FALSE(delegate->changes()[2].second); EXPECT_EQ("E", delegate->changes()[2].first.Name()); EXPECT_EQ("F", delegate->changes()[2].first.Value()); delegate->reset(); EXPECT_TRUE( FindAndDeleteCookie(cm.get(), http_www_google_.url().host(), "C")); EXPECT_EQ("A=B; E=F", GetCookies(cm.get(), http_www_google_.url())); ASSERT_EQ(1u, delegate->changes().size()); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[0].first.Domain()); EXPECT_TRUE(delegate->changes()[0].second); EXPECT_EQ("C", delegate->changes()[0].first.Name()); EXPECT_EQ("D", delegate->changes()[0].first.Value()); delegate->reset(); EXPECT_FALSE(FindAndDeleteCookie(cm.get(), "random.host", "E")); EXPECT_EQ("A=B; E=F", GetCookies(cm.get(), http_www_google_.url())); EXPECT_EQ(0u, delegate->changes().size()); // Insert a cookie "a" for path "/path1" EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "a=val1; path=/path1; " "expires=Mon, 18-Apr-22 22:50:13 GMT")); ASSERT_EQ(1u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type); ASSERT_EQ(1u, delegate->changes().size()); EXPECT_FALSE(delegate->changes()[0].second); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[0].first.Domain()); EXPECT_EQ("a", delegate->changes()[0].first.Name()); EXPECT_EQ("val1", delegate->changes()[0].first.Value()); delegate->reset(); // Insert a cookie "a" for path "/path1", that is httponly. This should // overwrite the non-http-only version. CookieOptions allow_httponly; allow_httponly.<API key>(); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), "a=val2; path=/path1; httponly; " "expires=Mon, 18-Apr-22 22:50:14 GMT", allow_httponly)); ASSERT_EQ(3u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[2].type); ASSERT_EQ(2u, delegate->changes().size()); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[0].first.Domain()); EXPECT_TRUE(delegate->changes()[0].second); EXPECT_EQ("a", delegate->changes()[0].first.Name()); EXPECT_EQ("val1", delegate->changes()[0].first.Value()); EXPECT_EQ(http_www_google_.url().host(), delegate->changes()[1].first.Domain()); EXPECT_FALSE(delegate->changes()[1].second); EXPECT_EQ("a", delegate->changes()[1].first.Name()); EXPECT_EQ("val2", delegate->changes()[1].first.Value()); delegate->reset(); } TEST_F(CookieMonsterTest, <API key>) { const std::string kTrueValue = "A"; std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // We test that we can see all cookies with our predicated. This includes // host, http_only, host secure, and all domain cookies. CookiePredicate value_matcher = base::Bind(&<API key>, kTrueValue); <API key>(cm.get()); EXPECT_EQ(7, <API key>( cm.get(), base::Time(), base::Time::Now(), value_matcher)); EXPECT_EQ("dom_2=B; dom_3=C; host_3=C", GetCookies(cm.get(), GURL(<API key>))); EXPECT_EQ("dom_2=B; host_2=B; sec_host=B", GetCookies(cm.get(), GURL(<API key>))); EXPECT_EQ("", GetCookies(cm.get(), GURL(<API key>))); EXPECT_EQ("dom_path_2=B; host_path_2=B; dom_2=B; host_2=B; sec_host=B", GetCookies(cm.get(), GURL(<API key> + std::string("/dir1/dir2/xxx")))); } TEST_F(CookieMonsterTest, UniqueCreationTime) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); CookieOptions options; // Add in three cookies through every public interface to the // CookieMonster and confirm that none of them have duplicate // creation times. // <API key> and <API key> // are not included as they aren't going to be public for very much // longer. // SetCookie, <API key>, <API key> EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "SetCookie1=A")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "SetCookie2=A")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "SetCookie3=A")); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), "<API key>=A", options)); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), "<API key>=A", options)); EXPECT_TRUE(<API key>(cm.get(), http_www_google_.url(), "<API key>=A", options)); EXPECT_TRUE(<API key>( cm.get(), http_www_google_.url(), "<API key>", "A", http_www_google_.Format(".%D"), "/", Time(), Time(), Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(<API key>( cm.get(), http_www_google_.url(), "<API key>", "A", http_www_google_.Format(".%D"), "/", Time(), Time(), Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); EXPECT_TRUE(<API key>( cm.get(), http_www_google_.url(), "<API key>", "A", http_www_google_.Format(".%D"), "/", Time(), Time(), Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); // Now we check CookieList cookie_list(GetAllCookies(cm.get())); EXPECT_EQ(9u, cookie_list.size()); typedef std::map<int64_t, CanonicalCookie> TimeCookieMap; TimeCookieMap check_map; for (CookieList::const_iterator it = cookie_list.begin(); it != cookie_list.end(); it++) { const int64_t creation_date = it->CreationDate().ToInternalValue(); TimeCookieMap::const_iterator existing_cookie_it( check_map.find(creation_date)); EXPECT_TRUE(existing_cookie_it == check_map.end()) << "Cookie " << it->Name() << " has same creation date (" << it->CreationDate().ToInternalValue() << ") as previously entered cookie " << existing_cookie_it->second.Name(); if (existing_cookie_it == check_map.end()) { check_map.insert( TimeCookieMap::value_type(it->CreationDate().ToInternalValue(), *it)); } } } // Mainly a test of GetEffectiveDomain, or more specifically, of the // expected behavior of GetEffectiveDomain within the CookieMonster. TEST_F(CookieMonsterTest, GetKey) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // This test is really only interesting if GetKey() actually does something. EXPECT_EQ("google.com", cm->GetKey("www.google.com")); EXPECT_EQ("google.izzie", cm->GetKey("www.google.izzie")); EXPECT_EQ("google.izzie", cm->GetKey(".google.izzie")); EXPECT_EQ("bbc.co.uk", cm->GetKey("bbc.co.uk")); EXPECT_EQ("bbc.co.uk", cm->GetKey("a.b.c.d.bbc.co.uk")); EXPECT_EQ("apple.com", cm->GetKey("a.b.c.d.apple.com")); EXPECT_EQ("apple.izzie", cm->GetKey("a.b.c.d.apple.izzie")); // Cases where the effective domain is null, so we use the host // as the key. EXPECT_EQ("co.uk", cm->GetKey("co.uk")); const std::string extension_name("<API key>"); EXPECT_EQ(extension_name, cm->GetKey(extension_name)); EXPECT_EQ("com", cm->GetKey("com")); EXPECT_EQ("hostalias", cm->GetKey("hostalias")); EXPECT_EQ("localhost", cm->GetKey("localhost")); } // Test that cookies transfer from/to the backing store correctly. TEST_F(CookieMonsterTest, <API key>) { // Store details for cookies transforming through the backing store interface. base::Time current(base::Time::Now()); scoped_refptr<<API key>> store( new <API key>); base::Time new_access_time; base::Time expires(base::Time::Now() + base::TimeDelta::FromSeconds(100)); const CookiesInputInfo input_info[] = { {GURL("http://a.b.google.com"), "a", "1", "", "/path/to/cookie", expires, false, false, CookieSameSite::DEFAULT_MODE, <API key>}, {GURL("https: "/path/from/cookie", expires + TimeDelta::FromSeconds(10), true, true, CookieSameSite::DEFAULT_MODE, <API key>}, {GURL("https://google.com"), "c", "3", "", "/another/path/to/cookie", base::Time::Now() + base::TimeDelta::FromSeconds(100), true, false, CookieSameSite::STRICT_MODE, <API key>}}; const int INPUT_DELETE = 1; // Create new cookies and flush them to the store. { std::unique_ptr<CookieMonster> cmout( new CookieMonster(store.get(), nullptr)); for (const CookiesInputInfo* p = input_info; p < &input_info[arraysize(input_info)]; p++) { EXPECT_TRUE(<API key>( cmout.get(), p->url, p->name, p->value, p->domain, p->path, base::Time(), p->expiration_time, base::Time(), p->secure, p->http_only, p->same_site, p->priority)); } GURL del_url(input_info[INPUT_DELETE] .url.Resolve(input_info[INPUT_DELETE].path) .spec()); DeleteCookie(cmout.get(), del_url, input_info[INPUT_DELETE].name); } // Create a new cookie monster and make sure that everything is correct { std::unique_ptr<CookieMonster> cmin( new CookieMonster(store.get(), nullptr)); CookieList cookies(GetAllCookies(cmin.get())); ASSERT_EQ(2u, cookies.size()); // Ordering is path length, then creation time. So second cookie // will come first, and we need to swap them. std::swap(cookies[0], cookies[1]); for (int output_index = 0; output_index < 2; output_index++) { int input_index = output_index * 2; const CookiesInputInfo* input = &input_info[input_index]; const CanonicalCookie* output = &cookies[output_index]; EXPECT_EQ(input->name, output->Name()); EXPECT_EQ(input->value, output->Value()); EXPECT_EQ(input->url.host(), output->Domain()); EXPECT_EQ(input->path, output->Path()); EXPECT_LE(current.ToInternalValue(), output->CreationDate().ToInternalValue()); EXPECT_EQ(input->secure, output->IsSecure()); EXPECT_EQ(input->http_only, output->IsHttpOnly()); EXPECT_EQ(input->same_site, output->SameSite()); EXPECT_TRUE(output->IsPersistent()); EXPECT_EQ(input->expiration_time.ToInternalValue(), output->ExpiryDate().ToInternalValue()); } } } TEST_F(CookieMonsterTest, CookieListOrdering) { // Put a random set of cookies into a monster and make sure // they're returned in the right order. std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); EXPECT_TRUE( SetCookie(cm.get(), GURL("http://d.c.b.a.google.com/aa/x.html"), "c=1")); EXPECT_TRUE(SetCookie(cm.get(), GURL("http://b.a.google.com/aa/bb/cc/x.html"), "d=1; domain=b.a.google.com")); EXPECT_TRUE(SetCookie(cm.get(), GURL("http://b.a.google.com/aa/bb/cc/x.html"), "a=4; domain=b.a.google.com")); EXPECT_TRUE(SetCookie(cm.get(), GURL("http://c.b.a.google.com/aa/bb/cc/x.html"), "e=1; domain=c.b.a.google.com")); EXPECT_TRUE(SetCookie(cm.get(), GURL("http://d.c.b.a.google.com/aa/bb/x.html"), "b=1")); EXPECT_TRUE(SetCookie(cm.get(), GURL("http://news.bbc.co.uk/midpath/x.html"), "g=10")); { unsigned int i = 0; CookieList cookies(GetAllCookiesForURL( cm.get(), GURL("http://d.c.b.a.google.com/aa/bb/cc/dd"))); ASSERT_EQ(5u, cookies.size()); EXPECT_EQ("d", cookies[i++].Name()); EXPECT_EQ("a", cookies[i++].Name()); EXPECT_EQ("e", cookies[i++].Name()); EXPECT_EQ("b", cookies[i++].Name()); EXPECT_EQ("c", cookies[i++].Name()); } { unsigned int i = 0; CookieList cookies(GetAllCookies(cm.get())); ASSERT_EQ(6u, cookies.size()); EXPECT_EQ("d", cookies[i++].Name()); EXPECT_EQ("a", cookies[i++].Name()); EXPECT_EQ("e", cookies[i++].Name()); EXPECT_EQ("g", cookies[i++].Name()); EXPECT_EQ("b", cookies[i++].Name()); EXPECT_EQ("c", cookies[i++].Name()); } } // This test and CookieMonstertest.TestGCTimes (in <API key>.cc) // are somewhat complementary twins. This test is probing for whether // garbage collection always happens when it should (i.e. that we actually // get rid of cookies when we should). The perftest is probing for // whether garbage collection happens when it shouldn't. See comments // before that test for more details. // Disabled on Windows, see crbug.com/126095 #if defined(OS_WIN) #define <API key> <API key> #else #define <API key> <API key> #endif TEST_F(CookieMonsterTest, <API key>) { // First we check to make sure that a whole lot of recent cookies // doesn't get rid of anything after garbage collection is checked for. { std::unique_ptr<CookieMonster> cm( CreateMonsterForGC(CookieMonster::kMaxCookies * 2)); EXPECT_EQ(CookieMonster::kMaxCookies * 2, GetAllCookies(cm.get()).size()); SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2"); EXPECT_EQ(CookieMonster::kMaxCookies * 2 + 1, GetAllCookies(cm.get()).size()); } // Now we explore a series of relationships between cookie last access // time and size of store to make sure we only get rid of cookies when // we really should. const struct TestCase { size_t num_cookies; size_t num_old_cookies; size_t <API key>; // Indexed by ExpiryAndKeyScheme size_t <API key>; } test_cases[] = { {// A whole lot of recent cookies; gc shouldn't happen. CookieMonster::kMaxCookies * 2, 0, CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies * 2 + 1}, {// Some old cookies, but still overflowing max. CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies / 2, CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies * 2 - CookieMonster::kMaxCookies / 2 + 1}, {// Old cookies enough to bring us right down to our purge line. CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies + CookieMonster::kPurgeCookies + 1, CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies - CookieMonster::kPurgeCookies}, {// Old cookies enough to bring below our purge line (which we // shouldn't do). CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies * 3 / 2, CookieMonster::kMaxCookies * 2, CookieMonster::kMaxCookies - CookieMonster::kPurgeCookies}}; for (int ci = 0; ci < static_cast<int>(arraysize(test_cases)); ++ci) { const TestCase* test_case = &test_cases[ci]; std::unique_ptr<CookieMonster> cm = <API key>( test_case->num_cookies, test_case->num_old_cookies, 0, 0, CookieMonster::<API key> * 2); EXPECT_EQ(test_case-><API key>, GetAllCookies(cm.get()).size()) << "For test case " << ci; // Will trigger GC SetCookie(cm.get(), GURL("http://newdomain.com"), "b=2"); EXPECT_EQ(test_case-><API key>, GetAllCookies(cm.get()).size()) << "For test case " << ci; } } // Tests that if the main load event happens before the loaded event for a // particular key, the tasks for that key run first. TEST_F(CookieMonsterTest, <API key>) { const GURL kUrl = GURL(<API key>); scoped_refptr<<API key>> store(new <API key>); store-><API key>(true); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Get all cookies task that queues a task to set a cookie when executed. <API key><bool> set_cookie_callback; cm-><API key>( kUrl, "a=b", CookieOptions(), base::Bind(&<API key><bool>::Run, base::Unretained(&set_cookie_callback))); <API key> <API key>; cm->GetAllCookiesAsync( base::Bind(&<API key>::Run, base::Unretained(&<API key>))); // Two load events should have been queued. ASSERT_EQ(2u, store->commands().size()); ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type); ASSERT_EQ(CookieStoreCommand::<API key>, store->commands()[1].type); // The main load completes first (With no cookies). store->commands()[0].loaded_callback.Run( std::vector<std::unique_ptr<CanonicalCookie>>()); // The tasks should run in order, and the get should see the cookies. set_cookie_callback.WaitUntilDone(); EXPECT_TRUE(set_cookie_callback.result()); <API key>.WaitUntilDone(); EXPECT_EQ(1u, <API key>.cookies().size()); // The loaded for key event completes late, with not cookies (Since they // were already loaded). store->commands()[1].loaded_callback.Run( std::vector<std::unique_ptr<CanonicalCookie>>()); // The just set cookie should still be in the store. <API key> <API key>; cm->GetAllCookiesAsync( base::Bind(&<API key>::Run, base::Unretained(&<API key>))); <API key>.WaitUntilDone(); EXPECT_EQ(1u, <API key>.cookies().size()); } // Tests that case that DeleteAll is waiting for load to complete, and then a // get is queued. The get should wait to run until after all the cookies are // retrieved, and should return nothing, since all cookies were just deleted. TEST_F(CookieMonsterTest, <API key>) { const GURL kUrl = GURL(<API key>); scoped_refptr<<API key>> store(new <API key>); store-><API key>(true); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); <API key><int> delete_callback; cm->DeleteAllAsync(base::Bind(&<API key><int>::Run, base::Unretained(&delete_callback))); <API key> <API key>; cm-><API key>( kUrl, CookieOptions(), base::Bind(&<API key>::Run, base::Unretained(&<API key>))); // Only the main load should have been queued. ASSERT_EQ(1u, store->commands().size()); ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type); std::vector<std::unique_ptr<CanonicalCookie>> cookies; // When passed to the CookieMonster, it takes ownership of the pointed to // cookies. cookies.push_back( CanonicalCookie::Create(kUrl, "a=b", base::Time(), CookieOptions())); ASSERT_TRUE(cookies[0]); store->commands()[0].loaded_callback.Run(std::move(cookies)); delete_callback.WaitUntilDone(); EXPECT_EQ(1, delete_callback.result()); <API key>.WaitUntilDone(); EXPECT_EQ(0u, <API key>.cookies().size()); } // Tests that a set cookie call sandwiched between two get all cookies, all // before load completes, affects the first but not the second. The set should // also not trigger a LoadCookiesForKey (As that could complete only after the // main load for the store). TEST_F(CookieMonsterTest, <API key>) { const GURL kUrl = GURL(<API key>); scoped_refptr<<API key>> store(new <API key>); store-><API key>(true); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); <API key> <API key>; cm->GetAllCookiesAsync( base::Bind(&<API key>::Run, base::Unretained(&<API key>))); <API key><bool> set_cookie_callback; cm-><API key>( kUrl, "a=b", CookieOptions(), base::Bind(&<API key><bool>::Run, base::Unretained(&set_cookie_callback))); <API key> <API key>; cm->GetAllCookiesAsync( base::Bind(&<API key>::Run, base::Unretained(&<API key>))); // Only the main load should have been queued. ASSERT_EQ(1u, store->commands().size()); ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type); // The load completes (With no cookies). store->commands()[0].loaded_callback.Run( std::vector<std::unique_ptr<CanonicalCookie>>()); <API key>.WaitUntilDone(); EXPECT_EQ(0u, <API key>.cookies().size()); set_cookie_callback.WaitUntilDone(); EXPECT_TRUE(set_cookie_callback.result()); <API key>.WaitUntilDone(); EXPECT_EQ(1u, <API key>.cookies().size()); } namespace { void <API key>(const base::Closure& closure, const CookieList& cookie_list) { closure.Run(); } } // namespace // Tests that if a single cookie task is queued as a result of a task performed // on all cookies when loading completes, it will be run after any already // queued tasks. TEST_F(CookieMonsterTest, <API key>) { const GURL kUrl = GURL(<API key>); scoped_refptr<<API key>> store(new <API key>); store-><API key>(true); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Get all cookies task that queues a task to set a cookie when executed. <API key><bool> set_cookie_callback; cm->GetAllCookiesAsync(base::Bind( &<API key>, base::Bind(&CookieStore::<API key>, base::Unretained(cm.get()), kUrl, "a=b", CookieOptions(), base::Bind(&<API key><bool>::Run, base::Unretained(&set_cookie_callback))))); // Get cookie task. Queued before the delete task is executed, so should not // see the set cookie. <API key> <API key>; cm->GetAllCookiesAsync( base::Bind(&<API key>::Run, base::Unretained(&<API key>))); // Only the main load should have been queued. ASSERT_EQ(1u, store->commands().size()); ASSERT_EQ(CookieStoreCommand::LOAD, store->commands()[0].type); // The load completes. store->commands()[0].loaded_callback.Run( std::vector<std::unique_ptr<CanonicalCookie>>()); // The get cookies call should see no cookies set. <API key>.WaitUntilDone(); EXPECT_EQ(0u, <API key>.cookies().size()); set_cookie_callback.WaitUntilDone(); EXPECT_TRUE(set_cookie_callback.result()); // A subsequent get cookies call should see the new cookie. <API key> <API key>; cm->GetAllCookiesAsync( base::Bind(&<API key>::Run, base::Unretained(&<API key>))); <API key>.WaitUntilDone(); EXPECT_EQ(1u, <API key>.cookies().size()); } namespace { // Mock <API key> that keeps track of the number of Flush() calls. class <API key> : public CookieMonster::<API key> { public: <API key>() : flush_count_(0) {} void Load(const LoadedCallback& loaded_callback) override { std::vector<std::unique_ptr<CanonicalCookie>> out_cookies; base::<API key>::Get()->PostTask( FROM_HERE, base::Bind(loaded_callback, base::Passed(&out_cookies))); } void LoadCookiesForKey(const std::string& key, const LoadedCallback& loaded_callback) override { Load(loaded_callback); } void AddCookie(const CanonicalCookie&) override {} void <API key>(const CanonicalCookie&) override {} void DeleteCookie(const CanonicalCookie&) override {} void <API key>() override {} void Flush(const base::Closure& callback) override { ++flush_count_; if (!callback.is_null()) callback.Run(); } int flush_count() { return flush_count_; } private: ~<API key>() override {} volatile int flush_count_; }; // Counts the number of times Callback() has been run. class CallbackCounter : public base::<API key><CallbackCounter> { public: CallbackCounter() : callback_count_(0) {} void Callback() { ++callback_count_; } int callback_count() { return callback_count_; } private: friend class base::<API key><CallbackCounter>; ~CallbackCounter() {} volatile int callback_count_; }; } // namespace // Test that FlushStore() is forwarded to the store and callbacks are posted. TEST_F(CookieMonsterTest, FlushStore) { scoped_refptr<CallbackCounter> counter(new CallbackCounter()); scoped_refptr<<API key>> store(new <API key>()); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); ASSERT_EQ(0, store->flush_count()); ASSERT_EQ(0, counter->callback_count()); // Before initialization, FlushStore() should just run the callback. cm->FlushStore(base::Bind(&CallbackCounter::Callback, counter)); base::RunLoop().RunUntilIdle(); ASSERT_EQ(0, store->flush_count()); ASSERT_EQ(1, counter->callback_count()); // NULL callback is safe. cm->FlushStore(base::Closure()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(0, store->flush_count()); ASSERT_EQ(1, counter->callback_count()); // After initialization, FlushStore() should delegate to the store. GetAllCookies(cm.get()); // Force init. cm->FlushStore(base::Bind(&CallbackCounter::Callback, counter)); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1, store->flush_count()); ASSERT_EQ(2, counter->callback_count()); // NULL callback is still safe. cm->FlushStore(base::Closure()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(2, store->flush_count()); ASSERT_EQ(2, counter->callback_count()); // If there's no backing store, FlushStore() is always a safe no-op. cm.reset(new CookieMonster(nullptr, nullptr)); GetAllCookies(cm.get()); // Force init. cm->FlushStore(base::Closure()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(2, counter->callback_count()); cm->FlushStore(base::Bind(&CallbackCounter::Callback, counter)); base::RunLoop().RunUntilIdle(); ASSERT_EQ(3, counter->callback_count()); } TEST_F(CookieMonsterTest, SetAllCookies) { scoped_refptr<<API key>> store(new <API key>()); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); cm-><API key>(true); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "U=V; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "W=X; path=/foo")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "Y=Z; path=/")); CookieList list; list.push_back(*CanonicalCookie::Create( http_www_google_.url(), "A", "B", http_www_google_.url().host(), "/", base::Time::Now(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); list.push_back(*CanonicalCookie::Create( http_www_google_.url(), "W", "X", http_www_google_.url().host(), "/bar", base::Time::Now(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); list.push_back(*CanonicalCookie::Create( http_www_google_.url(), "Y", "Z", http_www_google_.url().host(), "/", base::Time::Now(), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); // SetAllCookies must not flush. ASSERT_EQ(0, store->flush_count()); EXPECT_TRUE(SetAllCookies(cm.get(), list)); EXPECT_EQ(0, store->flush_count()); CookieList cookies = GetAllCookies(cm.get()); size_t expected_size = 3; // "A", "W" and "Y". "U" is gone. EXPECT_EQ(expected_size, cookies.size()); CookieList::iterator it = cookies.begin(); ASSERT_TRUE(it != cookies.end()); EXPECT_EQ("W", it->Name()); EXPECT_EQ("X", it->Value()); EXPECT_EQ("/bar", it->Path()); // The path has been updated. ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ("A", it->Name()); EXPECT_EQ("B", it->Value()); ASSERT_TRUE(++it != cookies.end()); EXPECT_EQ("Y", it->Name()); EXPECT_EQ("Z", it->Value()); } TEST_F(CookieMonsterTest, ComputeCookieDiff) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); base::Time now = base::Time::Now(); base::Time creation_time = now - base::TimeDelta::FromSeconds(1); std::unique_ptr<CanonicalCookie> cookie1(CanonicalCookie::Create( http_www_google_.url(), "A", "B", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> cookie2(CanonicalCookie::Create( http_www_google_.url(), "C", "D", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> cookie3(CanonicalCookie::Create( http_www_google_.url(), "E", "F", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> cookie4(CanonicalCookie::Create( http_www_google_.url(), "G", "H", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> <API key>( CanonicalCookie::Create( http_www_google_.url(), "G", "iamnew", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> cookie5(CanonicalCookie::Create( http_www_google_.url(), "I", "J", http_www_google_.url().host(), "/", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> <API key>( CanonicalCookie::Create( http_www_google_.url(), "I", "J", http_www_google_.url().host(), "/", now, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> cookie6(CanonicalCookie::Create( http_www_google_.url(), "K", "L", http_www_google_.url().host(), "/foo", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> <API key>( CanonicalCookie::Create( http_www_google_.url(), "K", "L", http_www_google_.url().host(), "/bar", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> cookie7(CanonicalCookie::Create( http_www_google_.url(), "M", "N", http_www_google_.url().host(), "/foo", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); std::unique_ptr<CanonicalCookie> <API key>( CanonicalCookie::Create( http_www_google_.url(), "M", "N", http_www_google_.url().host(), "/bar", creation_time, base::Time(), false, false, CookieSameSite::DEFAULT_MODE, false, <API key>)); CookieList old_cookies; old_cookies.push_back(*cookie1); old_cookies.push_back(*cookie2); old_cookies.push_back(*cookie4); old_cookies.push_back(*cookie5); old_cookies.push_back(*cookie6); old_cookies.push_back(*cookie7); CookieList new_cookies; new_cookies.push_back(*cookie1); new_cookies.push_back(*cookie3); new_cookies.push_back(*<API key>); new_cookies.push_back(*<API key>); new_cookies.push_back(*<API key>); new_cookies.push_back(*cookie7); new_cookies.push_back(*<API key>); CookieList cookies_to_add; CookieList cookies_to_delete; cm->ComputeCookieDiff(&old_cookies, &new_cookies, &cookies_to_add, &cookies_to_delete); // |cookie1| has not changed. EXPECT_FALSE(IsCookieInList(*cookie1, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*cookie1, cookies_to_delete)); // |cookie2| has been deleted. EXPECT_FALSE(IsCookieInList(*cookie2, cookies_to_add)); EXPECT_TRUE(IsCookieInList(*cookie2, cookies_to_delete)); // |cookie3| has been added. EXPECT_TRUE(IsCookieInList(*cookie3, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*cookie3, cookies_to_delete)); // |cookie4| has a new value: new cookie overrides the old one (which does not // need to be explicitly removed). EXPECT_FALSE(IsCookieInList(*cookie4, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*cookie4, cookies_to_delete)); EXPECT_TRUE(IsCookieInList(*<API key>, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*<API key>, cookies_to_delete)); // |cookie5| has a new creation time: new cookie overrides the old one (which // does not need to be explicitly removed). EXPECT_FALSE(IsCookieInList(*cookie5, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*cookie5, cookies_to_delete)); EXPECT_TRUE(IsCookieInList(*<API key>, cookies_to_add)); EXPECT_FALSE( IsCookieInList(*<API key>, cookies_to_delete)); // |cookie6| has a new path: the new cookie does not overrides the old one, // which needs to be explicitly removed. EXPECT_FALSE(IsCookieInList(*cookie6, cookies_to_add)); EXPECT_TRUE(IsCookieInList(*cookie6, cookies_to_delete)); EXPECT_TRUE(IsCookieInList(*<API key>, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*<API key>, cookies_to_delete)); // |cookie7| is kept and |<API key>| is added as a new cookie. EXPECT_FALSE(IsCookieInList(*cookie7, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*cookie7, cookies_to_delete)); EXPECT_TRUE(IsCookieInList(*<API key>, cookies_to_add)); EXPECT_FALSE(IsCookieInList(*<API key>, cookies_to_delete)); } // Check that DeleteAll does flush (as a sanity check that flush_count() // works). TEST_F(CookieMonsterTest, DeleteAll) { scoped_refptr<<API key>> store(new <API key>()); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); cm-><API key>(true); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "X=Y; path=/")); ASSERT_EQ(0, store->flush_count()); EXPECT_EQ(1, DeleteAll(cm.get())); EXPECT_EQ(1, store->flush_count()); } TEST_F(CookieMonsterTest, HistogramCheck) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); // Should match call in <API key>, but doesn't really matter // since the histogram should have been initialized by the CM construction // above. base::HistogramBase* expired_histogram = base::Histogram::FactoryGet( "Cookie.<API key>", 1, 10 * 365 * 24 * 60, 50, base::Histogram::<API key>); std::unique_ptr<base::HistogramSamples> samples1( expired_histogram->SnapshotSamples()); ASSERT_TRUE(<API key>( cm.get(), GURL("http://fake.a.url"), "a", "b", "a.url", "/", base::Time(), base::Time::Now() + base::TimeDelta::FromMinutes(59), base::Time(), false, false, CookieSameSite::DEFAULT_MODE, <API key>)); std::unique_ptr<base::HistogramSamples> samples2( expired_histogram->SnapshotSamples()); EXPECT_EQ(samples1->TotalCount() + 1, samples2->TotalCount()); // kValidCookieLine creates a session cookie. ASSERT_TRUE(SetCookie(cm.get(), http_www_google_.url(), kValidCookieLine)); std::unique_ptr<base::HistogramSamples> samples3( expired_histogram->SnapshotSamples()); EXPECT_EQ(samples2->TotalCount(), samples3->TotalCount()); } TEST_F(CookieMonsterTest, InvalidExpiryTime) { std::string cookie_line = std::string(kValidCookieLine) + "; expires=Blarg arg arg"; std::unique_ptr<CanonicalCookie> cookie(CanonicalCookie::Create( http_www_google_.url(), cookie_line, Time::Now(), CookieOptions())); ASSERT_FALSE(cookie->IsPersistent()); } // Test that CookieMonster writes session cookies into the underlying // CookieStore if the "persist session cookies" option is on. TEST_F(CookieMonsterTest, <API key>) { scoped_refptr<<API key>> store(new <API key>); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); cm-><API key>(true); // All cookies set with SetCookie are session cookies. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B")); EXPECT_EQ("A=B", GetCookies(cm.get(), http_www_google_.url())); // The cookie was written to the backing store. EXPECT_EQ(1u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type); EXPECT_EQ("A", store->commands()[0].cookie.Name()); EXPECT_EQ("B", store->commands()[0].cookie.Value()); // Modify the cookie. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=C")); EXPECT_EQ("A=C", GetCookies(cm.get(), http_www_google_.url())); EXPECT_EQ(3u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type); EXPECT_EQ("A", store->commands()[1].cookie.Name()); EXPECT_EQ("B", store->commands()[1].cookie.Value()); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[2].type); EXPECT_EQ("A", store->commands()[2].cookie.Name()); EXPECT_EQ("C", store->commands()[2].cookie.Value()); // Delete the cookie. DeleteCookie(cm.get(), http_www_google_.url(), "A"); EXPECT_EQ("", GetCookies(cm.get(), http_www_google_.url())); EXPECT_EQ(4u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[3].type); EXPECT_EQ("A", store->commands()[3].cookie.Name()); EXPECT_EQ("C", store->commands()[3].cookie.Value()); } // Test the commands sent to the persistent cookie store. TEST_F(CookieMonsterTest, <API key>) { scoped_refptr<<API key>> store(new <API key>); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Add a cookie. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B; expires=Mon, 18-Apr-22 22:50:13 GMT")); this->MatchCookieLines("A=B", GetCookies(cm.get(), http_www_google_.url())); ASSERT_EQ(1u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[0].type); // Remove it. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B; max-age=0")); this->MatchCookieLines(std::string(), GetCookies(cm.get(), http_www_google_.url())); ASSERT_EQ(2u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[1].type); // Add a cookie. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B; expires=Mon, 18-Apr-22 22:50:13 GMT")); this->MatchCookieLines("A=B", GetCookies(cm.get(), http_www_google_.url())); ASSERT_EQ(3u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[2].type); // Overwrite it. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=Foo; expires=Mon, 18-Apr-22 22:50:14 GMT")); this->MatchCookieLines("A=Foo", GetCookies(cm.get(), http_www_google_.url())); ASSERT_EQ(5u, store->commands().size()); EXPECT_EQ(CookieStoreCommand::REMOVE, store->commands()[3].type); EXPECT_EQ(CookieStoreCommand::ADD, store->commands()[4].type); // Create some non-persistent cookies and check that they don't go to the // persistent storage. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "B=Bar")); this->MatchCookieLines("A=Foo; B=Bar", GetCookies(cm.get(), http_www_google_.url())); EXPECT_EQ(5u, store->commands().size()); } // Test to assure that cookies with control characters are purged appropriately. TEST_F(CookieMonsterTest, <API key>) { const Time now1(Time::Now()); const Time now2(Time::Now() + TimeDelta::FromSeconds(1)); const Time now3(Time::Now() + TimeDelta::FromSeconds(2)); const Time later(now1 + TimeDelta::FromDays(1)); const GURL url("http://host/path"); const std::string domain("host"); const std::string path("/path"); scoped_refptr<<API key>> store(new <API key>); std::vector<std::unique_ptr<CanonicalCookie>> initial_cookies; AddCookieToList(url, "foo=bar; path=" + path, now1, &initial_cookies); // We have to manually build this cookie because it contains a control // character, and our cookie line parser rejects control characters. std::unique_ptr<CanonicalCookie> cc = CanonicalCookie::Create( url, "baz", "\x05" "boo", domain, path, now2, later, false, false, CookieSameSite::DEFAULT_MODE, false, <API key>); initial_cookies.push_back(std::move(cc)); AddCookieToList(url, "hello=world; path=" + path, now3, &initial_cookies); // Inject our initial cookies into the mock <API key>. store->SetLoadExpectation(true, std::move(initial_cookies)); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); EXPECT_EQ("foo=bar; hello=world", GetCookies(cm.get(), url)); } // Test that cookie source schemes are histogrammed correctly. TEST_F(CookieMonsterTest, <API key>) { base::HistogramTester histograms; const std::string <API key> = "Cookie.CookieSourceScheme"; scoped_refptr<<API key>> store(new <API key>); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); histograms.ExpectTotalCount(<API key>, 0); // Set a secure cookie on a cryptographic scheme. EXPECT_TRUE( SetCookie(cm.get(), https_www_google_.url(), "A=B; path=/; Secure")); histograms.ExpectTotalCount(<API key>, 1); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); // Set a non-secure cookie on a cryptographic scheme. EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "C=D; path=/;")); histograms.ExpectTotalCount(<API key>, 2); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); // Set a secure cookie on a non-cryptographic scheme. EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), "D=E; path=/; Secure")); histograms.ExpectTotalCount(<API key>, 3); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); // Overwrite a secure cookie (set by a cryptographic scheme) on a // non-cryptographic scheme. EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), "A=B; path=/; Secure")); histograms.ExpectTotalCount(<API key>, 4); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 2); // counted. EXPECT_TRUE( SetCookie(cm.get(), https_www_google_.url(), "F=G; path=/; Secure")); histograms.ExpectTotalCount(<API key>, 5); std::string cookies1 = GetCookies(cm.get(), https_www_google_.url()); EXPECT_NE(std::string::npos, cookies1.find("F=G")); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "F=G; path=/; Expires=Thu, 01-Jan-1970 00:00:01 GMT")); std::string cookies2 = GetCookies(cm.get(), https_www_google_.url()); EXPECT_EQ(std::string::npos, cookies2.find("F=G")); histograms.ExpectTotalCount(<API key>, 5); // Set a non-secure cookie on a non-cryptographic scheme. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "H=I; path=/")); histograms.ExpectTotalCount(<API key>, 6); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); } // Test that cookie delete equivalent histograms are recorded correctly when // strict secure cookies are not enabled. TEST_F(CookieMonsterTest, <API key>) { base::HistogramTester histograms; const std::string <API key> = "Cookie.<API key>"; scoped_refptr<<API key>> store(new <API key>); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Set a secure cookie from a secure origin EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=B; Secure")); histograms.ExpectTotalCount(<API key>, 1); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 1); // Set a new cookie with a different name from a variety of origins (including // the same one). EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "B=A;")); histograms.ExpectTotalCount(<API key>, 2); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 2); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "C=A;")); histograms.ExpectTotalCount(<API key>, 3); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 3); // Set a non-secure cookie from an insecure origin that matches the name of an // already existing cookie and additionally is equivalent to the existing // cookie. EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "A=B;")); histograms.ExpectTotalCount(<API key>, 5); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 4); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 1); // Set a non-secure cookie from an insecure origin that matches the name of an // already existing cookie but is not equivalent. EXPECT_TRUE( SetCookie(cm.get(), http_www_google_.url(), "A=C; path=/some/path")); histograms.ExpectTotalCount(<API key>, 6); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 5); // Set a secure cookie from a secure origin that matches the name of an // already existing cookies and is equivalent. EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=D; secure")); histograms.ExpectTotalCount(<API key>, 8); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 6); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 2); // Set a secure cookie from a secure origin that matches the name of an // already existing cookie and is not equivalent. EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=E; secure; path=/some/other/path")); histograms.ExpectTotalCount(<API key>, 9); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 7); } TEST_F(<API key>, SetSecureCookies) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); GURL http_url("http: GURL <API key>("http://google.com"); GURL https_url("https: // A non-secure cookie can be created from either a URL with a secure or // insecure scheme. EXPECT_TRUE(SetCookie(cm.get(), http_url, "A=C;")); EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B;")); // A secure cookie cannot be created from a URL with an insecure scheme. EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=B; Secure")); // A secure cookie can be created from a URL with a secure scheme. EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); // If a non-secure cookie is created from a URL with an insecure scheme, and a // secure cookie with the same name already exists, do not update the cookie. EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C;")); // If a non-secure cookie is created from a URL with an secure scheme, and a // secure cookie with the same name already exists, update the cookie. EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C;")); // If a non-secure cookie is created from a URL with an insecure scheme, and // a secure cookie with the same name already exists, do not update the cookie // if the new cookie's path matches the existing cookie's path. // With an existing cookie whose path is '/', a cookie with the same name // cannot be set on the same domain, regardless of path: EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; path=/")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; path=/my/path")); // But if the existing cookie has a path somewhere under the root, cookies // with the same name may be set for paths which don't overlap the existing // cookie. EXPECT_TRUE( SetCookie(cm.get(), https_url, "WITH_PATH=B; Secure; path=/my/path")); EXPECT_TRUE(SetCookie(cm.get(), http_url, "WITH_PATH=C")); EXPECT_TRUE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/")); EXPECT_TRUE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/your/path")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/my/path")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "WITH_PATH=C; path=/my/path/sub")); // If a non-secure cookie is created from a URL with an insecure scheme, and // a secure cookie with the same name already exists, if the domain strings // domain-match, do not update the cookie. EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; domain=google.com")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=C; domain=www.google.com")); // Since A=B was set above with no domain string, set a different cookie here // so the insecure examples aren't trying to overwrite the one above. EXPECT_TRUE(SetCookie(cm.get(), https_url, "B=C; Secure; domain=google.com")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "B=D; domain=google.com")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "B=D")); EXPECT_FALSE(SetCookie(cm.get(), <API key>, "B=D")); // Verify that if an httponly version of the cookie exists, adding a Secure // version of the cookie still does not overwrite it. CookieOptions include_httponly; include_httponly.<API key>(); include_httponly.<API key>(); EXPECT_TRUE(<API key>(cm.get(), https_url, "C=D; httponly", include_httponly)); // Note that the lack of an explicit options object below uses the default, // which in this case includes "exclude_httponly = true". EXPECT_FALSE(SetCookie(cm.get(), https_url, "C=E; Secure")); } // Tests for behavior if strict secure cookies is enabled. TEST_F(<API key>, EvictSecureCookies) { // Hard-coding limits in the test, but use DCHECK_EQ to enforce constraint. DCHECK_EQ(180U, CookieMonster::kDomainMaxCookies); DCHECK_EQ(150U, CookieMonster::kDomainMaxCookies - CookieMonster::kDomainPurgeCookies); DCHECK_EQ(3300U, CookieMonster::kMaxCookies); DCHECK_EQ(30, CookieMonster::<API key>); // If secure cookies for one domain hit the per domain limit (180), a // non-secure cookie will not evict them (and, in fact, the non-secure cookie // will be removed right after creation). const CookiesEntry test1[] = {{180U, true}, {1U, false}}; <API key>(test1, arraysize(test1), 150U, 0U, nullptr); // If non-secure cookies for one domain hit the per domain limit (180), the // creation of secure cookies will evict the non-secure cookies first, making // room for the secure cookies. const CookiesEntry test2[] = {{180U, false}, {20U, true}}; <API key>(test2, arraysize(test2), 20U, 149U, nullptr); // If secure cookies for one domain go past the per domain limit (180), they // will be evicted as normal by the per domain purge amount (30) down to a // lower amount (150), and then will continue to create the remaining cookies // (19 more to 169). const CookiesEntry test3[] = {{200U, true}}; <API key>(test3, arraysize(test3), 169U, 0U, nullptr); // If a non-secure cookie is created, and a number of secure cookies exceeds // the per domain limit (18), the total cookies will be evicted down to a // lower amount (150), enforcing the eviction of the non-secure cookie, and // the remaining secure cookies will be created (another 19 to 169). const CookiesEntry test4[] = {{1U, false}, {199U, true}}; <API key>(test4, arraysize(test4), 169U, 0U, nullptr); // If an even number of non-secure and secure cookies are created below the // per-domain limit (180), all will be created and none evicted. const CookiesEntry test5[] = {{75U, false}, {75U, true}}; <API key>(test5, arraysize(test5), 75U, 75U, nullptr); // If the same number of secure and non-secure cookies are created (50 each) // below the per domain limit (180), and then another set of secure cookies // are created to bring the total above the per-domain limit, all secure // cookies will be retained, and the non-secure cookies will be culled down // to the limit. const CookiesEntry test6[] = {{50U, true}, {50U, false}, {81U, true}}; <API key>(test6, arraysize(test6), 131U, 19U, nullptr); // If the same number of non-secure and secure cookies are created (50 each) // below the per domain limit (180), and then another set of non-secure // cookies are created to bring the total above the per-domain limit, all // secure cookies will be retained, and the non-secure cookies will be culled // down to the limit. const CookiesEntry test7[] = {{50U, false}, {50U, true}, {81U, false}}; <API key>(test7, arraysize(test7), 50U, 100U, nullptr); // If the same number of non-secure and secure cookies are created (50 each) // below the per domain limit (180), and then another set of non-secure // cookies are created to bring the total above the per-domain limit, all // secure cookies will be retained, and the non-secure cookies will be culled // down to the limit, then the remaining non-secure cookies will be created const CookiesEntry test8[] = {{50U, false}, {50U, true}, {90U, false}}; <API key>(test8, arraysize(test8), 50U, 109U, nullptr); // past the global 'safe' date, and then the number of non-secure cookies for // a single domain are brought to the per-domain limit (180), followed by // another set of secure cookies on that same domain (20), all the secure // cookies for that domain should be retained, while the non-secure should be // culled down to the per-domain limit. The non-secure cookies for other // domains should remain untouched. const CookiesEntry test9[] = {{180U, false}, {20U, true}}; const AltHosts test9_alt_hosts(0, 20); <API key>(test9, arraysize(test9), 20U, 169U, &test9_alt_hosts); // cookie limit (3300) and are past the global 'safe' date, and then a single // non-secure cookie is created now, the secure cookies are removed so that // the global total number of cookies is at the global purge goal (3000), but // the non-secure cookie is not evicted since it is too young. const CookiesEntry test10[] = {{1U, false}}; const AltHosts test10_alt_hosts(3300, 0); <API key>(test10, arraysize(test10), 2999U, 1U, &test10_alt_hosts); // global cookie limit (3300) and are past the global 'safe' date, and then a // single non-secure cookie is created now, the non-secure cookies are removed // so that the global total number of cookies is at the global purge goal // (3000). const CookiesEntry test11[] = {{1U, false}}; const AltHosts test11_alt_hosts(0, 3300); <API key>(test11, arraysize(test11), 0U, 3000U, &test11_alt_hosts); // global cookie limit (3300) and are past the global 'safe' date, and then a // single ecure cookie is created now, the non-secure cookies are removed so // that the global total number of cookies is at the global purge goal (3000), // but the secure cookie is not evicted. const CookiesEntry test12[] = {{1U, true}}; const AltHosts test12_alt_hosts(0, 3300); <API key>(test12, arraysize(test12), 1U, 2999U, &test12_alt_hosts); // hosts and hit the global cookie limit (3300) and are past the global 'safe' // date, and then a single non-secure cookie is created now, the global // non-secure cookies are removed so that the global total number of cookies // is at the global purge goal (3000), but the secure cookies are not evicted. const CookiesEntry test13[] = {{1U, false}}; const AltHosts test13_alt_hosts(1500, 1800); <API key>(test13, arraysize(test13), 1500U, 1500, &test13_alt_hosts); // hosts and hit the global cookie limit (3300) and are past the global 'safe' // date, and then a single secure cookie is created now, the global non-secure // cookies are removed so that the global total number of cookies is at the // global purge goal (3000), but the secure cookies are not evicted. const CookiesEntry test14[] = {{1U, true}}; const AltHosts test14_alt_hosts(1500, 1800); <API key>(test14, arraysize(test14), 1501U, 1499, &test14_alt_hosts); } // Tests that strict secure cookies doesn't trip equivalent cookie checks TEST_F(<API key>, EquivalentCookies) { std::unique_ptr<CookieMonster> cm(new CookieMonster(nullptr, nullptr)); GURL http_url("http: GURL <API key>("http://google.com"); GURL https_url("https: // Tests that non-equivalent cookies because of the path attribute can be set // successfully. EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C; path=/some/other/path")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; path=/some/other/path")); // Tests that non-equivalent cookies because of the domain attribute can be // set successfully. EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=B; Secure")); EXPECT_TRUE(SetCookie(cm.get(), https_url, "A=C; domain=google.com")); EXPECT_FALSE(SetCookie(cm.get(), http_url, "A=D; domain=google.com")); } // Test that cookie delete equivalent histograms are recorded correctly for // strict secure cookies. TEST_F(<API key>, <API key>) { base::HistogramTester histograms; const std::string <API key> = "Cookie.<API key>"; scoped_refptr<<API key>> store(new <API key>); std::unique_ptr<CookieMonster> cm(new CookieMonster(store.get(), nullptr)); // Set a secure cookie from a secure origin EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=B; Secure")); histograms.ExpectTotalCount(<API key>, 1); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 1); // Set a new cookie with a different name from a variety of origins (including // the same one). EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "B=A;")); histograms.ExpectTotalCount(<API key>, 2); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 2); EXPECT_TRUE(SetCookie(cm.get(), http_www_google_.url(), "C=A;")); histograms.ExpectTotalCount(<API key>, 3); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 3); // Set a non-secure cookie from an insecure origin that matches the name of an // already existing cookie and additionally is equivalent to the existing // cookie. EXPECT_FALSE(SetCookie(cm.get(), http_www_google_.url(), "A=B;")); histograms.ExpectTotalCount(<API key>, 6); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 4); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 1); // Set a non-secure cookie from an insecure origin that matches the name of an // already existing cookie but is not equivalent. EXPECT_FALSE( SetCookie(cm.get(), http_www_google_.url(), "A=B; path=/some/path")); histograms.ExpectTotalCount(<API key>, 8); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 5); histograms.ExpectBucketCount( <API key>, CookieMonster::<API key>, 2); // Set a secure cookie from a secure origin that matches the name of an // already existing cookies and is equivalent. EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=B; secure")); histograms.ExpectTotalCount(<API key>, 10); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 6); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 1); // Set a secure cookie from a secure origin that matches the name of an // already existing cookie and is not equivalent. EXPECT_TRUE(SetCookie(cm.get(), https_www_google_.url(), "A=C; secure; path=/some/path")); histograms.ExpectTotalCount(<API key>, 11); histograms.ExpectBucketCount(<API key>, CookieMonster::<API key>, 7); } class <API key> : public CookieMonsterTest { public: <API key>() : test_url_("http: store_(new <API key>), monster_(new CookieMonster(store_.get(), nullptr)) {} ~<API key>() override {} CookieMonster* monster() { return monster_.get(); } protected: const GURL test_url_; private: scoped_refptr<<API key>> store_; std::unique_ptr<CookieMonster> monster_; }; void RecordCookieChanges(std::vector<CanonicalCookie>* out_cookies, std::vector<CookieStore::ChangeCause>* out_causes, const CanonicalCookie& cookie, CookieStore::ChangeCause cause) { DCHECK(out_cookies); out_cookies->push_back(cookie); if (out_causes) out_causes->push_back(cause); } TEST_F(<API key>, <API key>) { std::vector<CanonicalCookie> cookies; std::unique_ptr<CookieStore::<API key>> sub( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, nullptr))); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0U, cookies.size()); } TEST_F(<API key>, <API key>) { std::vector<CanonicalCookie> cookies; SetCookie(monster(), test_url_, "abc=def"); base::RunLoop().RunUntilIdle(); std::unique_ptr<CookieStore::<API key>> sub( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, nullptr))); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0U, cookies.size()); } TEST_F(<API key>, NotifyOnSet) { std::vector<CanonicalCookie> cookies; std::vector<CookieStore::ChangeCause> causes; std::unique_ptr<CookieStore::<API key>> sub( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, &causes))); SetCookie(monster(), test_url_, "abc=def"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1U, cookies.size()); EXPECT_EQ(1U, causes.size()); EXPECT_EQ("abc", cookies[0].Name()); EXPECT_EQ("def", cookies[0].Value()); EXPECT_EQ(CookieStore::ChangeCause::INSERTED, causes[0]); } TEST_F(<API key>, NotifyOnDelete) { std::vector<CanonicalCookie> cookies; std::vector<CookieStore::ChangeCause> causes; std::unique_ptr<CookieStore::<API key>> sub( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, &causes))); SetCookie(monster(), test_url_, "abc=def"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1U, cookies.size()); EXPECT_EQ(1U, causes.size()); DeleteCookie(monster(), test_url_, "abc"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2U, cookies.size()); EXPECT_EQ(2U, causes.size()); EXPECT_EQ("abc", cookies[1].Name()); EXPECT_EQ("def", cookies[1].Value()); EXPECT_EQ(CookieStore::ChangeCause::EXPLICIT, causes[1]); } TEST_F(<API key>, NotifyOnUpdate) { std::vector<CanonicalCookie> cookies; std::vector<CookieStore::ChangeCause> causes; std::unique_ptr<CookieStore::<API key>> sub( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies, &causes))); SetCookie(monster(), test_url_, "abc=def"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1U, cookies.size()); // Replacing an existing cookie is actually a two-phase delete + set // operation, so we get an extra notification. SetCookie(monster(), test_url_, "abc=ghi"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(3U, cookies.size()); EXPECT_EQ(3U, causes.size()); EXPECT_EQ("abc", cookies[1].Name()); EXPECT_EQ("def", cookies[1].Value()); EXPECT_EQ(CookieStore::ChangeCause::OVERWRITE, causes[1]); EXPECT_EQ("abc", cookies[2].Name()); EXPECT_EQ("ghi", cookies[2].Value()); EXPECT_EQ(CookieStore::ChangeCause::INSERTED, causes[2]); } TEST_F(<API key>, MultipleNotifies) { std::vector<CanonicalCookie> cookies0; std::vector<CanonicalCookie> cookies1; std::unique_ptr<CookieStore::<API key>> sub0( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies0, nullptr))); std::unique_ptr<CookieStore::<API key>> sub1( monster()-><API key>( test_url_, "def", base::Bind(&RecordCookieChanges, &cookies1, nullptr))); SetCookie(monster(), test_url_, "abc=def"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1U, cookies0.size()); EXPECT_EQ(0U, cookies1.size()); SetCookie(monster(), test_url_, "def=abc"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1U, cookies0.size()); EXPECT_EQ(1U, cookies1.size()); } TEST_F(<API key>, <API key>) { std::vector<CanonicalCookie> cookies0; std::vector<CanonicalCookie> cookies1; std::unique_ptr<CookieStore::<API key>> sub0( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies0, nullptr))); std::unique_ptr<CookieStore::<API key>> sub1( monster()-><API key>( test_url_, "abc", base::Bind(&RecordCookieChanges, &cookies1, nullptr))); SetCookie(monster(), test_url_, "abc=def"); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1U, cookies0.size()); EXPECT_EQ(1U, cookies0.size()); } } // namespace net
# This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file import os import re import logging import tempfile import argparse from twisted.internet.defer import inlineCallbacks import subprocess from email.Utils import getaddresses, parseaddr from email.message import Message import mailcap from cStringIO import StringIO from alot.commands import Command, registerCommand from alot.commands.globals import ExternalCommand from alot.commands.globals import FlushCommand from alot.commands.globals import ComposeCommand from alot.commands.globals import MoveCommand from alot.commands.globals import CommandCanceled from alot.commands.envelope import SendCommand from alot import completion from alot.db.utils import decode_header from alot.db.utils import encode_header from alot.db.utils import extract_headers from alot.db.utils import extract_body from alot.db.envelope import Envelope from alot.db.attachment import Attachment from alot.db.errors import DatabaseROError from alot.settings import settings from alot.helper import <API key> from alot.helper import split_commandstring from alot.helper import email_as_string from alot.utils.booleanaction import BooleanAction from alot.completion import ContactsCompleter from alot.widgets.globals import AttachmentWidget MODE = 'thread' def determine_sender(mail, action='reply'): """ Inspect a given mail to reply/forward/bounce and find the most appropriate account to act from and construct a suitable From-Header to use. :param mail: the email to inspect :type mail: `email.message.Message` :param action: intended use case: one of "reply", "forward" or "bounce" :type action: str """ assert action in ['reply', 'forward', 'bounce'] realname = None address = None # get accounts my_accounts = settings.get_accounts() assert my_accounts, 'no accounts set!' # extract list of addresses to check for my address # X-Envelope-To and Envelope-To are used to store the recipient address # if not included in other fields candidate_addresses = getaddresses(mail.get_all('To', []) + mail.get_all('Cc', []) + mail.get_all('Delivered-To', []) + mail.get_all('X-Envelope-To', []) + mail.get_all('Envelope-To', []) + mail.get_all('From', [])) logging.debug('candidate addresses: %s' % candidate_addresses) # pick the most important account that has an address in candidates # and use that accounts realname and the address found here for account in my_accounts: acc_addresses = account.get_addresses() for alias in acc_addresses: if realname is not None: break regex = re.compile(re.escape(alias), flags=re.IGNORECASE) for seen_name, seen_address in candidate_addresses: if regex.match(seen_address): logging.debug("match!: '%s' '%s'" % (seen_address, alias)) if settings.get(action + '_force_realname'): realname = account.realname else: realname = seen_name if settings.get(action + '_force_address'): address = account.address else: address = seen_address # revert to default account if nothing found if realname is None: account = my_accounts[0] realname = account.realname address = account.address logging.debug('using realname: "%s"' % realname) logging.debug('using address: %s' % address) from_value = address if realname == '' else '%s <%s>' % (realname, address) return from_value, account @registerCommand(MODE, 'reply', arguments=[ (['--all'], {'action': 'store_true', 'help': 'reply to all'}), (['--spawn'], {'action': BooleanAction, 'default': None, 'help': 'open editor in new window'})]) class ReplyCommand(Command): """reply to message""" repeatable = True def __init__(self, message=None, all=False, spawn=None, **kwargs): """ :param message: message to reply to (defaults to selected message) :type message: `alot.db.message.Message` :param all: group reply; copies recipients from Bcc/Cc/To to the reply :type all: bool :param spawn: force spawning of editor in a new terminal :type spawn: bool """ self.message = message self.groupreply = all self.force_spawn = spawn Command.__init__(self, **kwargs) def apply(self, ui): # get message to forward if not given in constructor if not self.message: self.message = ui.current_buffer.<API key>() mail = self.message.get_email() # set body text name, address = self.message.get_author() timestamp = self.message.get_date() qf = settings.get_hook('reply_prefix') if qf: quotestring = qf(name, address, timestamp, ui=ui, dbm=ui.dbman) else: quotestring = 'Quoting %s (%s)\n' % (name or address, timestamp) mailcontent = quotestring quotehook = settings.get_hook('text_quote') if quotehook: mailcontent += quotehook(self.message.accumulate_body()) else: quote_prefix = settings.get('quote_prefix') for line in self.message.accumulate_body().splitlines(): mailcontent += quote_prefix + line + '\n' envelope = Envelope(bodytext=mailcontent) # copy subject subject = decode_header(mail.get('Subject', '')) reply_subject_hook = settings.get_hook('reply_subject') if reply_subject_hook: subject = reply_subject_hook(subject) else: rsp = settings.get('<API key>') if not subject.lower().startswith(('re:', rsp.lower())): subject = rsp + subject envelope.add('Subject', subject) # set From-header and sending account try: from_header, account = determine_sender(mail, 'reply') except AssertionError as e: ui.notify(e.message, priority='error') return envelope.add('From', from_header) # set To sender = mail['Reply-To'] or mail['From'] my_addresses = settings.get_addresses() sender_address = parseaddr(sender)[1] cc = '' # check if reply is to self sent message if sender_address in my_addresses: recipients = [mail['To']] emsg = 'Replying to own message, set recipients to: %s' \ % recipients logging.debug(emsg) else: recipients = [sender] if self.groupreply: # make sure that our own address is not included # if the message was self-sent, then our address is not included MFT = mail.get_all('Mail-Followup-To', []) followupto = self.clear_my_address(my_addresses, MFT) if followupto and settings.get('honor_followup_to'): logging.debug('honor followup to: %s', followupto) recipients = [followupto] # since Mail-Followup-To was set, ignore the Cc header else: if sender != mail['From']: recipients.append(mail['From']) # append To addresses if not replying to self sent message if sender_address not in my_addresses: cleared = self.clear_my_address( my_addresses, mail.get_all('To', [])) recipients.append(cleared) # copy cc for group-replies if 'Cc' in mail: cc = self.clear_my_address( my_addresses, mail.get_all('Cc', [])) envelope.add('Cc', decode_header(cc)) to = ', '.join(recipients) logging.debug('reply to: %s' % to) envelope.add('To', decode_header(to)) # if any of the recipients is a mailinglist that we are subscribed to, # set Mail-Followup-To header so that duplicates are avoided if settings.get('followup_to'): # to and cc are already cleared of our own address allrecipients = [to] + [cc] lists = settings.get('mailinglists') # check if any recipient address matches a known mailing list if any([addr in lists for n, addr in getaddresses(allrecipients)]): followupto = ', '.join(allrecipients) logging.debug('mail followup to: %s' % followupto) envelope.add('Mail-Followup-To', decode_header(followupto)) # set In-Reply-To header envelope.add('In-Reply-To', '<%s>' % self.message.get_message_id()) # set References header old_references = mail.get('References', '') if old_references: old_references = old_references.split() references = old_references[-8:] if len(old_references) > 8: references = old_references[:1] + references references.append('<%s>' % self.message.get_message_id()) envelope.add('References', ' '.join(references)) else: envelope.add('References', '<%s>' % self.message.get_message_id()) # continue to compose ui.apply_command(ComposeCommand(envelope=envelope, spawn=self.force_spawn)) def clear_my_address(self, my_addresses, value): """return recipient header without the addresses in my_addresses""" new_value = [] for name, address in getaddresses(value): if address not in my_addresses: if name != '': new_value.append('"%s" <%s>' % (name, address)) else: new_value.append(address) return ', '.join(new_value) @registerCommand(MODE, 'forward', arguments=[ (['--attach'], {'action': 'store_true', 'help': 'attach original mail'}), (['--spawn'], {'action': BooleanAction, 'default': None, 'help': 'open editor in new window'})]) class ForwardCommand(Command): """forward message""" repeatable = True def __init__(self, message=None, attach=True, spawn=None, **kwargs): """ :param message: message to forward (defaults to selected message) :type message: `alot.db.message.Message` :param attach: attach original mail instead of inline quoting its body :type attach: bool :param spawn: force spawning of editor in a new terminal :type spawn: bool """ self.message = message self.inline = not attach self.force_spawn = spawn Command.__init__(self, **kwargs) def apply(self, ui): # get message to forward if not given in constructor if not self.message: self.message = ui.current_buffer.<API key>() mail = self.message.get_email() envelope = Envelope() if self.inline: # inline mode # set body text name, address = self.message.get_author() timestamp = self.message.get_date() qf = settings.get_hook('forward_prefix') if qf: quote = qf(name, address, timestamp, ui=ui, dbm=ui.dbman) else: quote = 'Forwarded message from %s (%s):\n' % ( name or address, timestamp) mailcontent = quote quotehook = settings.get_hook('text_quote') if quotehook: mailcontent += quotehook(self.message.accumulate_body()) else: quote_prefix = settings.get('quote_prefix') for line in self.message.accumulate_body().splitlines(): mailcontent += quote_prefix + line + '\n' envelope.body = mailcontent for a in self.message.get_attachments(): envelope.attach(a) else: # attach original mode # attach original msg original_mail = Message() original_mail.set_type('message/rfc822') original_mail['Content-Disposition'] = 'attachment' original_mail.set_payload(email_as_string(mail)) envelope.attach(Attachment(original_mail)) # copy subject subject = decode_header(mail.get('Subject', '')) subject = 'Fwd: ' + subject <API key> = settings.get_hook('forward_subject') if <API key>: subject = <API key>(subject) else: fsp = settings.get('<API key>') if not subject.startswith(('Fwd:', fsp)): subject = fsp + subject envelope.add('Subject', subject) # set From-header and sending account try: from_header, account = determine_sender(mail, 'reply') except AssertionError as e: ui.notify(e.message, priority='error') return envelope.add('From', from_header) # continue to compose ui.apply_command(ComposeCommand(envelope=envelope, spawn=self.force_spawn)) @registerCommand(MODE, 'bounce') class BounceMailCommand(Command): """directly re-send selected message""" repeatable = True def __init__(self, message=None, **kwargs): """ :param message: message to bounce (defaults to selected message) :type message: `alot.db.message.Message` """ self.message = message Command.__init__(self, **kwargs) @inlineCallbacks def apply(self, ui): # get mail to bounce if not self.message: self.message = ui.current_buffer.<API key>() mail = self.message.get_email() # look if this makes sense: do we have any accounts set up? my_accounts = settings.get_accounts() if not my_accounts: ui.notify('no accounts set', priority='error') return # remove "Resent-*" headers if already present del mail['Resent-From'] del mail['Resent-To'] del mail['Resent-Cc'] del mail['Resent-Date'] del mail['Resent-Message-ID'] # set Resent-From-header and sending account try: resent_from_header, account = determine_sender(mail, 'bounce') except AssertionError as e: ui.notify(e.message, priority='error') return mail['Resent-From'] = resent_from_header # set Reset-To allbooks = not settings.get('<API key>') logging.debug('allbooks: %s', allbooks) if account is not None: abooks = settings.get_addressbooks(order=[account], append_remaining=allbooks) logging.debug(abooks) completer = ContactsCompleter(abooks) else: completer = None to = yield ui.prompt('To', completer=completer) if to is None: raise CommandCanceled() mail['Resent-To'] = to.strip(' \t\n,') logging.debug("bouncing mail") logging.debug(mail.__class__) ui.apply_command(SendCommand(mail=mail)) @registerCommand(MODE, 'editnew', arguments=[ (['--spawn'], {'action': BooleanAction, 'default': None, 'help': 'open editor in new window'})]) class EditNewCommand(Command): """edit message in as new""" def __init__(self, message=None, spawn=None, **kwargs): """ :param message: message to reply to (defaults to selected message) :type message: `alot.db.message.Message` :param spawn: force spawning of editor in a new terminal :type spawn: bool """ self.message = message self.force_spawn = spawn Command.__init__(self, **kwargs) def apply(self, ui): if not self.message: self.message = ui.current_buffer.<API key>() mail = self.message.get_email() # set body text name, address = self.message.get_author() mailcontent = self.message.accumulate_body() envelope = Envelope(bodytext=mailcontent) # copy selected headers to_copy = ['Subject', 'From', 'To', 'Cc', 'Bcc', 'In-Reply-To', 'References'] for key in to_copy: value = decode_header(mail.get(key, '')) if value: envelope.add(key, value) # copy attachments for b in self.message.get_attachments(): envelope.attach(b) ui.apply_command(ComposeCommand(envelope=envelope, spawn=self.force_spawn, omit_signature=True)) @registerCommand(MODE, 'fold', forced={'visible': False}, arguments=[ ( ['query'], {'help': 'query used to filter messages to affect', 'nargs': '*'}), ], help='fold message(s)') @registerCommand(MODE, 'unfold', forced={'visible': True}, arguments=[ (['query'], {'help': 'query used to filter messages to affect', 'nargs': '*'}), ], help='unfold message(s)') @registerCommand(MODE, 'togglesource', forced={'raw': 'toggle'}, arguments=[ (['query'], {'help': 'query used to filter messages to affect', 'nargs': '*'}), ], help='display message source') @registerCommand(MODE, 'toggleheaders', forced={'all_headers': 'toggle'}, arguments=[ (['query'], { 'help': 'query used to filter messages to affect', 'nargs': '*'}), ], help='display all headers') class <API key>(Command): """fold or unfold messages""" repeatable = True def __init__(self, query=None, visible=None, raw=None, all_headers=None, **kwargs): """ :param query: notmuch query string used to filter messages to affect :type query: str :param visible: unfold if `True`, fold if `False`, ignore if `None` :type visible: True, False, 'toggle' or None :param raw: display raw message text. :type raw: True, False, 'toggle' or None :param all_headers: show all headers (only visible if not in raw mode) :type all_headers: True, False, 'toggle' or None """ self.query = None if query: self.query = ' '.join(query) self.visible = visible self.raw = raw self.all_headers = all_headers Command.__init__(self, **kwargs) def apply(self, ui): tbuffer = ui.current_buffer logging.debug('matching lines %s...' % (self.query)) if self.query is None: messagetrees = [tbuffer.<API key>()] else: messagetrees = tbuffer.messagetrees() if self.query != '*': def matches(msgt): msg = msgt.get_message() return msg.matches(self.query) messagetrees = filter(matches, messagetrees) for mt in messagetrees: # determine new display values for this message if self.visible == 'toggle': visible = mt.is_collapsed(mt.root) else: visible = self.visible if self.raw == 'toggle': tbuffer.<API key>() raw = not mt.display_source if self.raw == 'toggle' else self.raw all_headers = not mt.display_all_headers \ if self.all_headers == 'toggle' else self.all_headers # collapse/expand depending on new 'visible' value if visible is False: mt.collapse(mt.root) elif visible is True: # could be None mt.expand(mt.root) tbuffer.<API key>() # set new values in messagetree obj if raw is not None: mt.display_source = raw if all_headers is not None: mt.display_all_headers = all_headers mt.debug() # let the messagetree reassemble itself mt.reassemble() # refresh the buffer (clears Tree caches etc) tbuffer.refresh() @registerCommand(MODE, 'pipeto', arguments=[ (['cmd'], {'help': 'shellcommand to pipe to', 'nargs': '+'}), (['--all'], {'action': 'store_true', 'help': 'pass all messages'}), (['--format'], {'help': 'output format', 'default': 'raw', 'choices': ['raw', 'decoded', 'id', 'filepath']}), (['--separately'], {'action': 'store_true', 'help': 'call command once for each message'}), (['--background'], {'action': 'store_true', 'help': 'don\'t stop the interface'}), (['--add_tags'], {'action': 'store_true', 'help': 'add \'Tags\' header to the message'}), (['--shell'], {'action': 'store_true', 'help': 'let the shell interpret the command'}), (['--notify_stdout'], {'action': 'store_true', 'help': 'display cmd\'s stdout as notification'}), ], ) class PipeCommand(Command): """pipe message(s) to stdin of a shellcommand""" repeatable = True def __init__(self, cmd, all=False, separately=False, background=False, shell=False, notify_stdout=False, format='raw', add_tags=False, noop_msg='no command specified', confirm_msg='', done_msg=None, **kwargs): """ :param cmd: shellcommand to open :type cmd: str or list of str :param all: pipe all, not only selected message :type all: bool :param separately: call command once per message :type separately: bool :param background: do not suspend the interface :type background: bool :param notify_stdout: display command\'s stdout as notification message :type notify_stdout: bool :param shell: let the shell interpret the command :type shell: bool 'raw': message content as is, 'decoded': message content, decoded quoted printable, 'id': message ids, separated by newlines, 'filepath': paths to message files on disk :type format: str :param add_tags: add 'Tags' header to the message :type add_tags: bool :param noop_msg: error notification to show if `cmd` is empty :type noop_msg: str :param confirm_msg: confirmation question to ask (continues directly if unset) :type confirm_msg: str :param done_msg: notification message to show upon success :type done_msg: str """ Command.__init__(self, **kwargs) if isinstance(cmd, unicode): cmd = split_commandstring(cmd) self.cmd = cmd self.whole_thread = all self.separately = separately self.background = background self.shell = shell self.notify_stdout = notify_stdout self.output_format = format self.add_tags = add_tags self.noop_msg = noop_msg self.confirm_msg = confirm_msg self.done_msg = done_msg @inlineCallbacks def apply(self, ui): # abort if command unset if not self.cmd: ui.notify(self.noop_msg, priority='error') return # get messages to pipe if self.whole_thread: thread = ui.current_buffer.get_selected_thread() if not thread: return to_print = thread.get_messages().keys() else: to_print = [ui.current_buffer.<API key>()] # ask for confirmation if needed if self.confirm_msg: if (yield ui.choice(self.confirm_msg, select='yes', cancel='no')) == 'no': return # prepare message sources pipestrings = [] separator = '\n\n' logging.debug('PIPETO format') logging.debug(self.output_format) if self.output_format == 'id': pipestrings = [e.get_message_id() for e in to_print] separator = '\n' elif self.output_format == 'filepath': pipestrings = [e.get_filename() for e in to_print] separator = '\n' else: for msg in to_print: mail = msg.get_email() if self.add_tags: mail['Tags'] = encode_header('Tags', ', '.join(msg.get_tags())) if self.output_format == 'raw': pipestrings.append(mail.as_string()) elif self.output_format == 'decoded': headertext = extract_headers(mail) bodytext = extract_body(mail) msgtext = '%s\n\n%s' % (headertext, bodytext) pipestrings.append(msgtext.encode('utf-8')) if not self.separately: pipestrings = [separator.join(pipestrings)] if self.shell: self.cmd = [' '.join(self.cmd)] # do teh monkey for mail in pipestrings: if self.background: logging.debug('call in background: %s' % str(self.cmd)) proc = subprocess.Popen(self.cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate(mail) if self.notify_stdout: ui.notify(out) else: logging.debug('stop urwid screen') ui.mainloop.screen.stop() logging.debug('call: %s' % str(self.cmd)) # if proc.stdout is defined later calls to communicate # seem to be non-blocking! proc = subprocess.Popen(self.cmd, shell=True, stdin=subprocess.PIPE, # stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate(mail) logging.debug('start urwid screen') ui.mainloop.screen.start() if err: ui.notify(err, priority='error') return # display 'done' message if self.done_msg: ui.notify(self.done_msg) @registerCommand(MODE, 'remove', arguments=[ (['--all'], {'action': 'store_true', 'help': 'remove whole thread'})]) class RemoveCommand(Command): """remove message(s) from the index""" repeatable = True def __init__(self, all=False, **kwargs): """ :param all: remove all messages from thread, not just selected one :type all: bool """ Command.__init__(self, **kwargs) self.all = all @inlineCallbacks def apply(self, ui): threadbuffer = ui.current_buffer # get messages and notification strings if self.all: thread = threadbuffer.get_selected_thread() tid = thread.get_thread_id() messages = thread.get_messages().keys() confirm_msg = 'remove all messages in thread?' ok_msg = 'removed all messages in thread: %s' % tid else: msg = threadbuffer.<API key>() messages = [msg] confirm_msg = 'remove selected message?' ok_msg = 'removed message: %s' % msg.get_message_id() # ask for confirmation if (yield ui.choice(confirm_msg, select='yes', cancel='no')) == 'no': return # notify callback def callback(): threadbuffer.rebuild() ui.notify(ok_msg) # remove messages for m in messages: ui.dbman.remove_message(m, afterwards=callback) ui.apply_command(FlushCommand()) @registerCommand(MODE, 'print', arguments=[ (['--all'], {'action': 'store_true', 'help': 'print all messages'}), (['--raw'], {'action': 'store_true', 'help': 'pass raw mail string'}), (['--separately'], {'action': 'store_true', 'help': 'call print command once for each message'}), (['--add_tags'], {'action': 'store_true', 'help': 'add \'Tags\' header to the message'}), ], ) class PrintCommand(PipeCommand): """print message(s)""" repeatable = True def __init__(self, all=False, separately=False, raw=False, add_tags=False, **kwargs): """ :param all: print all, not only selected messages :type all: bool :param separately: call print command once per message :type separately: bool :param raw: pipe raw message string to print command :type raw: bool :param add_tags: add 'Tags' header to the message :type add_tags: bool """ # get print command cmd = settings.get('print_cmd') or '' # set up notification strings if all: confirm_msg = 'print all messages in thread?' ok_msg = 'printed thread using %s' % cmd else: confirm_msg = 'print selected message?' ok_msg = 'printed message using %s' % cmd # no print cmd set noop_msg = 'no print command specified. Set "print_cmd" in the '\ 'global section.' PipeCommand.__init__(self, [cmd], all=all, separately=separately, background=True, shell=False, format='raw' if raw else 'decoded', add_tags=add_tags, noop_msg=noop_msg, confirm_msg=confirm_msg, done_msg=ok_msg, **kwargs) @registerCommand(MODE, 'save', arguments=[ (['--all'], {'action': 'store_true', 'help': 'save all attachments'}), (['path'], {'nargs': '?', 'help': 'path to save to'})]) class <API key>(Command): """save attachment(s)""" def __init__(self, all=False, path=None, **kwargs): """ :param all: save all, not only selected attachment :type all: bool :param path: path to write to. if `all` is set, this must be a directory. :type path: str """ Command.__init__(self, **kwargs) self.all = all self.path = path @inlineCallbacks def apply(self, ui): pcomplete = completion.PathCompleter() savedir = settings.get('attachment_prefix', '~') if self.all: msg = ui.current_buffer.<API key>() if not self.path: self.path = yield ui.prompt('save attachments to', text=os.path.join(savedir, ''), completer=pcomplete) if self.path: if os.path.isdir(os.path.expanduser(self.path)): for a in msg.get_attachments(): dest = a.save(self.path) name = a.get_filename() if name: ui.notify('saved %s as: %s' % (name, dest)) else: ui.notify('saved attachment as: %s' % dest) else: ui.notify('not a directory: %s' % self.path, priority='error') else: raise CommandCanceled() else: # save focussed attachment focus = ui.get_deep_focus() if isinstance(focus, AttachmentWidget): attachment = focus.get_attachment() filename = attachment.get_filename() if not self.path: msg = 'save attachment (%s) to ' % filename initialtext = os.path.join(savedir, filename) self.path = yield ui.prompt(msg, completer=pcomplete, text=initialtext) if self.path: try: dest = attachment.save(self.path) ui.notify('saved attachment as: %s' % dest) except (IOError, OSError) as e: ui.notify(str(e), priority='error') else: raise CommandCanceled() class <API key>(Command): """displays an attachment according to mailcap""" def __init__(self, attachment, **kwargs): """ :param attachment: attachment to open :type attachment: :class:`~alot.db.attachment.Attachment` """ Command.__init__(self, **kwargs) self.attachment = attachment def apply(self, ui): logging.info('open attachment') mimetype = self.attachment.get_content_type() # returns pair of preliminary command string and entry dict containing # more info. We only use the dict and construct the command ourselves _, entry = settings.mailcap_find_match(mimetype) if entry: afterwards = None # callback, will rm tempfile if used handler_stdin = None tempfile_name = None <API key> = entry['view'] # read parameter part = self.attachment.<API key>() parms = tuple(map('='.join, part.get_params())) # in case the mailcap defined command contains no '%s', # we pipe the files content to the handling command via stdin if '%s' in <API key>: nametemplate = entry.get('nametemplate', '%s') prefix, suffix = <API key>(nametemplate) tmpfile = tempfile.NamedTemporaryFile(delete=False, prefix=prefix, suffix=suffix) tempfile_name = tmpfile.name self.attachment.write(tmpfile) tmpfile.close() def afterwards(): os.unlink(tempfile_name) else: handler_stdin = StringIO() self.attachment.write(handler_stdin) # create handler command list handler_cmd = mailcap.subst(<API key>, mimetype, filename=tempfile_name, plist=parms) handler_cmdlist = split_commandstring(handler_cmd) # 'needsterminal' makes handler overtake the terminal nt = entry.get('needsterminal', None) overtakes = (nt is None) ui.apply_command(ExternalCommand(handler_cmdlist, stdin=handler_stdin, on_success=afterwards, thread=overtakes)) else: ui.notify('unknown mime type') @registerCommand(MODE, 'move', help='move focus in current buffer', arguments=[(['movement'], { 'nargs': argparse.REMAINDER, 'help': 'up, down, page up, ' 'page down, first, last'})]) class MoveFocusCommand(MoveCommand): def apply(self, ui): logging.debug(self.movement) tbuffer = ui.current_buffer if self.movement == 'parent': tbuffer.focus_parent() elif self.movement == 'first reply': tbuffer.focus_first_reply() elif self.movement == 'last reply': tbuffer.focus_last_reply() elif self.movement == 'next sibling': tbuffer.focus_next_sibling() elif self.movement == 'previous sibling': tbuffer.focus_prev_sibling() elif self.movement == 'next': tbuffer.focus_next() elif self.movement == 'previous': tbuffer.focus_prev() elif self.movement == 'next unfolded': tbuffer.focus_next_unfolded() elif self.movement == 'previous unfolded': tbuffer.focus_prev_unfolded() else: MoveCommand.apply(self, ui) # TODO add 'next matching' if threadbuffer stores the original query # TODO: add next by date.. tbuffer.body.refresh() @registerCommand(MODE, 'select') class ThreadSelectCommand(Command): """select focussed element. The fired action depends on the focus: - if message summary, this toggles visibility of the message, - if attachment line, this opens the attachment""" def apply(self, ui): focus = ui.get_deep_focus() if isinstance(focus, AttachmentWidget): logging.info('open attachment') ui.apply_command(<API key>(focus.get_attachment())) else: ui.apply_command(<API key>(visible='toggle')) @registerCommand(MODE, 'tag', forced={'action': 'add'}, arguments=[ (['--all'], {'action': 'store_true', 'help': 'tag all messages in thread'}), (['--no-flush'], {'action': 'store_false', 'dest': 'flush', 'help': 'postpone a writeout to the index'}), (['tags'], {'help': 'comma separated list of tags'})], help='add tags to message(s)', ) @registerCommand(MODE, 'retag', forced={'action': 'set'}, arguments=[ (['--all'], {'action': 'store_true', 'help': 'tag all messages in thread'}), (['--no-flush'], {'action': 'store_false', 'dest': 'flush', 'help': 'postpone a writeout to the index'}), (['tags'], {'help': 'comma separated list of tags'})], help='set message(s) tags.', ) @registerCommand(MODE, 'untag', forced={'action': 'remove'}, arguments=[ (['--all'], {'action': 'store_true', 'help': 'tag all messages in thread'}), (['--no-flush'], {'action': 'store_false', 'dest': 'flush', 'help': 'postpone a writeout to the index'}), (['tags'], {'help': 'comma separated list of tags'})], help='remove tags from message(s)', ) @registerCommand(MODE, 'toggletags', forced={'action': 'toggle'}, arguments=[ (['--all'], {'action': 'store_true', 'help': 'tag all messages in thread'}), (['--no-flush'], {'action': 'store_false', 'dest': 'flush', 'help': 'postpone a writeout to the index'}), (['tags'], {'help': 'comma separated list of tags'})], help='flip presence of tags on message(s)', ) class TagCommand(Command): """manipulate message tags""" repeatable = True def __init__(self, tags=u'', action='add', all=False, flush=True, **kwargs): """ :param tags: comma separated list of tagstrings to set :type tags: str :param action: adds tags if 'add', removes them if 'remove', adds tags and removes all other if 'set' or toggle individually if 'toggle' :type action: str :param all: tag all messages in thread :type all: bool :param flush: imediately write out to the index :type flush: bool """ self.tagsstring = tags self.all = all self.action = action self.flush = flush Command.__init__(self, **kwargs) def apply(self, ui): tbuffer = ui.current_buffer if self.all: messagetrees = tbuffer.messagetrees() else: messagetrees = [tbuffer.<API key>()] def refresh_widgets(): for mt in messagetrees: mt.refresh() # put currently selected message id on a block list for the # auto-remove-unread feature. This makes sure that explicit # tag-unread commands for the current message are not undone on the # next keypress (triggering the autorm again)... mid = tbuffer.get_selected_mid() tbuffer.<API key>.add(mid) tbuffer.refresh() tags = filter(lambda x: x, self.tagsstring.split(',')) try: for mt in messagetrees: m = mt.get_message() if self.action == 'add': m.add_tags(tags, afterwards=refresh_widgets) if self.action == 'set': m.add_tags(tags, afterwards=refresh_widgets, remove_rest=True) elif self.action == 'remove': m.remove_tags(tags, afterwards=refresh_widgets) elif self.action == 'toggle': to_remove = [] to_add = [] for t in tags: if t in m.get_tags(): to_remove.append(t) else: to_add.append(t) m.remove_tags(to_remove) m.add_tags(to_add, afterwards=refresh_widgets) except DatabaseROError: ui.notify('index in read-only mode', priority='error') return # flush index if self.flush: ui.apply_command(FlushCommand())
<?php /** * Adapts select information into query parts for a particular sql query. Automatically determines count, * distinct, sums, columns and aliases. */ class <API key> { /** * Array of select clauses * @var array */ private $clauses; /** * Set to true if the select query needs to be distinct * with the same id. * @var boolean */ private $distinct = false; /** * Count of select clauses * @var integer */ private $clausesCount = 0; private $countClausePresent = false; public function __construct($distinct = false) { $this->distinct = $distinct; } protected function <API key>() { $this->clausesCount++; } public function isDistinct() { return $this->distinct; } public function getClausesCount() { return $this->clausesCount; } public function getClauses() { return $this->clauses; } public function getSelect() { if ($this->getClausesCount() == 0) { throw new <API key>(); } $selectQuery = 'select '; if ($this->distinct && !$this->countClausePresent) { $selectQuery .= 'distinct '; } foreach ($this->clauses as $clauseCount => $clause) { $selectQuery .= $clause; if ($this->getClausesCount() > 1 && ($clauseCount + 1) < $this->getClausesCount()) { $selectQuery .= ','; // Not Coding Standard } $selectQuery .= ' '; } return $selectQuery; } public function addCountClause($tableName, $columnName = 'id', $aliasName = null) { assert('is_string($tableName)'); assert('is_string($columnName)'); assert('is_string($aliasName) || $aliasName == null'); $quote = <API key>::getQuote(); $distinctPart = null; if ($this->distinct) { $distinctPart = 'distinct '; } $clause = "count({$distinctPart}{$quote}$tableName{$quote}.{$quote}$columnName{$quote})"; if ($aliasName != null) { $clause .= " $aliasName"; } $this->clauses[] = $clause; $this->countClausePresent = true; $this-><API key>(); } public function addClause($tableName, $columnName, $aliasName = null) { assert('is_string($tableName)'); assert('is_string($columnName)'); assert('is_string($aliasName) || $aliasName == null'); $quote = <API key>::getQuote(); $clause = "{$quote}$tableName{$quote}.{$quote}$columnName{$quote}"; if ($aliasName != null) { $clause .= " $aliasName"; } $this->clauses[] = $clause; $this-><API key>(); } public function <API key>($columnName, $aliasName = null) { assert('is_string($columnName)'); assert('is_string($aliasName) || $aliasName == null'); $clause = "$columnName"; if ($aliasName != null) { $clause .= " $aliasName"; } $this->clauses[] = $clause; $this-><API key>(); } public function addSummationClause($summationQueryPart, $aliasName = null) { assert('is_string($summationQueryPart)'); assert('is_string($aliasName) || $aliasName == null'); $clause = "sum({$summationQueryPart})"; if ($aliasName != null) { $clause .= " $aliasName"; } $this->clauses[] = $clause; $this-><API key>(); } } ?>
export { PromiseWrapper, Promise, PromiseCompleter } from 'angular2/src/core/facade/promise'; export declare namespace NodeJS { interface Timer { } } export declare class TimerWrapper { static setTimeout(fn: (...args: any[]) => void, millis: number): NodeJS.Timer; static clearTimeout(id: NodeJS.Timer): void; static setInterval(fn: (...args: any[]) => void, millis: number): NodeJS.Timer; static clearInterval(id: NodeJS.Timer): void; } export declare class ObservableWrapper { static subscribe<T>(emitter: Observable, onNext: (value: T) => void, onThrow?: (exception: any) => void, onReturn?: () => void): Object; static isObservable(obs: any): boolean; static dispose(subscription: any): void; static callNext(emitter: EventEmitter, value: any): void; static callThrow(emitter: EventEmitter, error: any): void; static callReturn(emitter: EventEmitter): void; } export declare class Observable { observer(generator: any): Object; } export declare class EventEmitter extends Observable { observer(generator: any): any; toRx(): any; next(value: any): void; throw(error: any): void; return(value?: any): void; }
package org.kramerius.importmets.valueobj; /** * Reprezentace digitalniho objektu * * @author xholcik */ public class FileDescriptor { private String filename; private StreamFileType fileType; public FileDescriptor(String filename, StreamFileType fileType) { super(); this.filename = filename; this.fileType = fileType; } public StreamFileType getFileType() { return fileType; } public void setFileType(StreamFileType fileType) { this.fileType = fileType; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } }
<?php define('NAVBAR_TITLE', 'Feedback'); define('HEADING_TITLE', 'Feedback'); define('TEXT_INFORMATION', ''); ?>
#ifndef <API key> #define <API key> #include <boost/context/detail/config.hpp> #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> #include <exception> #include <functional> #include <memory> #include <ostream> #include <tuple> #include <utility> #include <boost/assert.hpp> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #if defined(<API key>) #include <boost/context/detail/exchange.hpp> #endif #if defined(<API key>) #include <boost/context/detail/invoke.hpp> #endif #include <boost/context/detail/disable_overload.hpp> #include <boost/context/detail/exception.hpp> #include <boost/context/detail/fcontext.hpp> #include <boost/context/detail/tuple.hpp> #include <boost/context/fixedsize_stack.hpp> #include <boost/context/flags.hpp> #include <boost/context/preallocated.hpp> #include <boost/context/segmented_stack.hpp> #include <boost/context/stack_context.hpp> #ifdef <API key> # include BOOST_ABI_PREFIX #endif #if defined(BOOST_MSVC) # pragma warning(push) # pragma warning(disable: 4702) #endif namespace boost { namespace context { namespace detail { inline transfer_t fiber_unwind( transfer_t t) { throw forced_unwind( t.fctx); return { nullptr, nullptr }; } template< typename Rec > transfer_t fiber_exit( transfer_t t) noexcept { Rec * rec = static_cast< Rec * >( t.data); // destroy context stack rec->deallocate(); return { nullptr, nullptr }; } template< typename Rec > void fiber_entry( transfer_t t) noexcept { // transfer control structure to the context-stack Rec * rec = static_cast< Rec * >( t.data); BOOST_ASSERT( nullptr != t.fctx); BOOST_ASSERT( nullptr != rec); try { // jump back to `create_context()` t = jump_fcontext( t.fctx, nullptr); // start executing t.fctx = rec->run( t.fctx); } catch ( forced_unwind const& e) { t = { e.fctx, nullptr }; } BOOST_ASSERT( nullptr != t.fctx); // destroy context-stack of `this`context on next context ontop_fcontext( t.fctx, rec, fiber_exit< Rec >); BOOST_ASSERT_MSG( false, "context already terminated"); } template< typename Ctx, typename Fn > transfer_t fiber_ontop( transfer_t t) { auto p = static_cast< std::tuple< Fn > * >( t.data); BOOST_ASSERT( nullptr != p); typename std::decay< Fn >::type fn = std::get< 0 >( * p); t.data = nullptr; // execute function, pass fiber via reference Ctx c = fn( Ctx{ t.fctx } ); #if defined(<API key>) return { exchange( c.fctx_, nullptr), nullptr }; #else return { std::exchange( c.fctx_, nullptr), nullptr }; #endif } template< typename Ctx, typename StackAlloc, typename Fn > class fiber_record { private: stack_context sctx_; typename std::decay< StackAlloc >::type salloc_; typename std::decay< Fn >::type fn_; static void destroy( fiber_record * p) noexcept { typename std::decay< StackAlloc >::type salloc = std::move( p->salloc_); stack_context sctx = p->sctx_; // deallocate fiber_record p->~fiber_record(); // destroy stack with stack allocator salloc.deallocate( sctx); } public: fiber_record( stack_context sctx, StackAlloc && salloc, Fn && fn) noexcept : sctx_( sctx), salloc_( std::forward< StackAlloc >( salloc)), fn_( std::forward< Fn >( fn) ) { } fiber_record( fiber_record const&) = delete; fiber_record & operator=( fiber_record const&) = delete; void deallocate() noexcept { destroy( this); } fcontext_t run( fcontext_t fctx) { // invoke context-function #if defined(<API key>) Ctx c = boost::context::detail::invoke( fn_, Ctx{ fctx } ); #else Ctx c = std::invoke( fn_, Ctx{ fctx } ); #endif #if defined(<API key>) return exchange( c.fctx_, nullptr); #else return std::exchange( c.fctx_, nullptr); #endif } }; template< typename Record, typename StackAlloc, typename Fn > fcontext_t create_fiber1( StackAlloc && salloc, Fn && fn) { auto sctx = salloc.allocate(); // reserve space for control structure void * storage = reinterpret_cast< void * >( ( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sizeof( Record) ) ) & ~static_cast< uintptr_t >( 0xff) ); // placment new for control structure on context stack Record * record = new ( storage) Record{ sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) }; // 64byte gab between control structure and stack top // should be 16byte aligned void * stack_top = reinterpret_cast< void * >( reinterpret_cast< uintptr_t >( storage) - static_cast< uintptr_t >( 64) ); void * stack_bottom = reinterpret_cast< void * >( reinterpret_cast< uintptr_t >( sctx.sp) - static_cast< uintptr_t >( sctx.size) ); // create fast-context const std::size_t size = reinterpret_cast< uintptr_t >( stack_top) - reinterpret_cast< uintptr_t >( stack_bottom); const fcontext_t fctx = make_fcontext( stack_top, size, & fiber_entry< Record >); BOOST_ASSERT( nullptr != fctx); // transfer control structure to context-stack return jump_fcontext( fctx, record).fctx; } template< typename Record, typename StackAlloc, typename Fn > fcontext_t create_fiber2( preallocated palloc, StackAlloc && salloc, Fn && fn) { // reserve space for control structure void * storage = reinterpret_cast< void * >( ( reinterpret_cast< uintptr_t >( palloc.sp) - static_cast< uintptr_t >( sizeof( Record) ) ) & ~ static_cast< uintptr_t >( 0xff) ); // placment new for control structure on context-stack Record * record = new ( storage) Record{ palloc.sctx, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) }; // 64byte gab between control structure and stack top void * stack_top = reinterpret_cast< void * >( reinterpret_cast< uintptr_t >( storage) - static_cast< uintptr_t >( 64) ); void * stack_bottom = reinterpret_cast< void * >( reinterpret_cast< uintptr_t >( palloc.sctx.sp) - static_cast< uintptr_t >( palloc.sctx.size) ); // create fast-context const std::size_t size = reinterpret_cast< uintptr_t >( stack_top) - reinterpret_cast< uintptr_t >( stack_bottom); const fcontext_t fctx = make_fcontext( stack_top, size, & fiber_entry< Record >); BOOST_ASSERT( nullptr != fctx); // transfer control structure to context-stack return jump_fcontext( fctx, record).fctx; } } class fiber { private: template< typename Ctx, typename StackAlloc, typename Fn > friend class detail::fiber_record; template< typename Ctx, typename Fn > friend detail::transfer_t detail::fiber_ontop( detail::transfer_t); template< typename StackAlloc, typename Fn > friend fiber callcc( std::allocator_arg_t, StackAlloc &&, Fn &&); template< typename StackAlloc, typename Fn > friend fiber callcc( std::allocator_arg_t, preallocated, StackAlloc &&, Fn &&); detail::fcontext_t fctx_{ nullptr }; fiber( detail::fcontext_t fctx) noexcept : fctx_{ fctx } { } public: fiber() noexcept = default; template< typename Fn, typename = detail::disable_overload< fiber, Fn > > fiber( Fn && fn) : fiber{ std::allocator_arg, fixedsize_stack(), std::forward< Fn >( fn) } { } template< typename StackAlloc, typename Fn > fiber( std::allocator_arg_t, StackAlloc && salloc, Fn && fn) : fctx_{ detail::create_fiber1< detail::fiber_record< fiber, StackAlloc, Fn > >( std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } { } template< typename StackAlloc, typename Fn > fiber( std::allocator_arg_t, preallocated palloc, StackAlloc && salloc, Fn && fn) : fctx_{ detail::create_fiber2< detail::fiber_record< fiber, StackAlloc, Fn > >( palloc, std::forward< StackAlloc >( salloc), std::forward< Fn >( fn) ) } { } #if defined(<API key>) template< typename Fn > fiber( std::allocator_arg_t, segmented_stack, Fn &&); template< typename StackAlloc, typename Fn > fiber( std::allocator_arg_t, preallocated, segmented_stack, Fn &&); #endif ~fiber() { if ( BOOST_UNLIKELY( nullptr != fctx_) ) { detail::ontop_fcontext( #if defined(<API key>) detail::exchange( fctx_, nullptr), #else std::exchange( fctx_, nullptr), #endif nullptr, detail::fiber_unwind); } } fiber( fiber && other) noexcept { swap( other); } fiber & operator=( fiber && other) noexcept { if ( BOOST_LIKELY( this != & other) ) { fiber tmp = std::move( other); swap( tmp); } return * this; } fiber( fiber const& other) noexcept = delete; fiber & operator=( fiber const& other) noexcept = delete; fiber resume() && { BOOST_ASSERT( nullptr != fctx_); return { detail::jump_fcontext( #if defined(<API key>) detail::exchange( fctx_, nullptr), #else std::exchange( fctx_, nullptr), #endif nullptr).fctx }; } template< typename Fn > fiber resume_with( Fn && fn) && { BOOST_ASSERT( nullptr != fctx_); auto p = std::make_tuple( std::forward< Fn >( fn) ); return { detail::ontop_fcontext( #if defined(<API key>) detail::exchange( fctx_, nullptr), #else std::exchange( fctx_, nullptr), #endif & p, detail::fiber_ontop< fiber, Fn >).fctx }; } explicit operator bool() const noexcept { return nullptr != fctx_; } bool operator!() const noexcept { return nullptr == fctx_; } bool operator==( fiber const& other) const noexcept { return fctx_ == other.fctx_; } bool operator!=( fiber const& other) const noexcept { return fctx_ != other.fctx_; } bool operator<( fiber const& other) const noexcept { return fctx_ < other.fctx_; } bool operator>( fiber const& other) const noexcept { return other.fctx_ < fctx_; } bool operator<=( fiber const& other) const noexcept { return ! ( * this > other); } bool operator>=( fiber const& other) const noexcept { return ! ( * this < other); } template< typename charT, class traitsT > friend std::basic_ostream< charT, traitsT > & operator<<( std::basic_ostream< charT, traitsT > & os, fiber const& other) { if ( nullptr != other.fctx_) { return os << other.fctx_; } else { return os << "{not-a-context}"; } } void swap( fiber & other) noexcept { std::swap( fctx_, other.fctx_); } }; inline void swap( fiber & l, fiber & r) noexcept { l.swap( r); } }} #if defined(BOOST_MSVC) # pragma warning(pop) #endif #ifdef <API key> # include BOOST_ABI_SUFFIX #endif #endif // <API key>
#!/bin/bash # Makes a mashed up JS file containing what's needed to # run the Espruino code building pipeline # You can then just do: # Espruino.transform(js_code, { # SET_TIME_ON_WRITE : false, # PRETOKENISE : true # }).then(function(code) { # console.log(code); cd `dirname $0` cd .. echo Creating espruinotools.js cat > espruinotools.js << EOF EOF echo "// Based on EspruinoWebIDE " `sed -ne "s/.*version.*\"\(.*\)\".*/\1/p" package.json` >> espruinotools.js cat EspruinoTools/espruino.js >> espruinotools.js cat >> espruinotools.js << EOF Espruino.Core.Notifications = { success : function(e) { console.log(e); }, error : function(e) { console.error(e); }, warning : function(e) { console.warn(e); }, info : function(e) { console.log(e); }, }; Espruino.Core.Status = { setStatus : function(e,len) { console.log(e); }, hasProgress : function() { return false; }, incrementProgress : function(amt) {} }; EOF # hacks to get acorn to work despite node echo "var acorn = (function(){ var exports={};var module={};" >> espruinotools.js cat js/libs/acorn/acorn.js >> espruinotools.js echo "return exports;})();" >> espruinotools.js cat EspruinoTools/core/utils.js >> espruinotools.js cat EspruinoTools/core/config.js >> espruinotools.js # do we need this? cat EspruinoTools/core/serial.js >> espruinotools.js cat EspruinoTools/core/codeWriter.js >> espruinotools.js cat EspruinoTools/core/modules.js >> espruinotools.js cat EspruinoTools/core/env.js >> espruinotools.js #cat EspruinoTools/plugins/compiler.js >> espruinotools.js cat EspruinoTools/plugins/assembler.js >> espruinotools.js cat EspruinoTools/plugins/getGitHub.js >> espruinotools.js #cat EspruinoTools/libs/utf8.js >> espruinotools.js #cat EspruinoTools/plugins/unicode.js >> espruinotools.js #cat EspruinoTools/libs/esprima/esprima.js >> espruinotools.js #cat EspruinoTools/libs/esprima/esmangle.js >> espruinotools.js #cat EspruinoTools/libs/esprima/escodegen.js >> espruinotools.js #cat EspruinoTools/plugins/minify.js >> espruinotools.js cat EspruinoTools/plugins/pretokenise.js >> espruinotools.js cat EspruinoTools/plugins/saveOnSend.js >> espruinotools.js cat EspruinoTools/plugins/setTime.js >> espruinotools.js cat >> espruinotools.js << EOF Espruino.transform = function(code, options) { return new Promise(function(resolve,reject) { Object.keys(options).forEach(function(key) { if (key==key.toUpperCase()) Espruino.Config[key] = options[key]; }); if (options.builtinModules) { var d = Espruino.Core.Env.getData(); d.MODULES = options.builtinModules; } Espruino.callProcessor("<API key>", code, resolve); }); }; if ("undefined"==typeof document) Espruino.init(); if ("undefined"!=typeof module) module.exports = Espruino; EOF
namespace OrcaMDF.Core.MetaData.BaseTables { internal class sysallocunit : Row { private static readonly ISchema schema = new Schema(new[] { new DataColumn("auid", "bigint"), new DataColumn("type", "tinyint"), new DataColumn("ownerid", "bigint"), new DataColumn("status", "int"), new DataColumn("fgid", "smallint"), new DataColumn("pgfirst", "binary(6)"), new DataColumn("pgroot", "binary(6)"), new DataColumn("pgfirstiam", "binary(6)"), new DataColumn("pcused", "bigint"), new DataColumn("pcdata", "bigint"), new DataColumn("pcreserved", "bigint"), new DataColumn("dbfragid", "int") }); public sysallocunit() : base(schema) { } public override Row NewRow() { return new sysallocunit(); } internal long auid { get { return Field<long>("auid"); } } internal byte type { get { return Field<byte>("type"); } } internal long ownerid { get { return Field<long>("ownerid"); } } internal int status { get { return Field<int>("status"); } } internal short fgid { get { return Field<short>("fgid"); } } internal byte[] pgfirst { get { return Field<byte[]>("pgfirst"); } } internal byte[] pgroot { get { return Field<byte[]>("pgroot"); } } internal byte[] pgfirstiam { get { return Field<byte[]>("pgfirstiam"); } } internal long pcused { get { return Field<long>("pcused"); } } internal long pcdata { get { return Field<long>("pcdata"); } } internal long pcreserved { get { return Field<long>("pcreserved"); } } internal int dbfragid { get { return Field<int>("dbfragid"); } } } }
<!DOCTYPE HTML PUBLIC "- <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Move to next entry</title> </head> <body><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="splfixedarray.key.html">SplFixedArray::key</a></div> <div class="next" style="text-align: right; float: right;"><a href="splfixedarray.offsetexists.html">SplFixedArray::offsetExists</a></div> <div class="up"><a href="class.splfixedarray.html">SplFixedArray</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div><hr /><div id="splfixedarray.next" class="refentry"> <div class="refnamediv"> <h1 class="refname">SplFixedArray::next</h1> <p class="verinfo">(PHP 5 &gt;= 5.3.0)</p><p class="refpurpose"><span class="refname">SplFixedArray::next</span> &mdash; <span class="dc-title">Move to next entry</span></p> </div> <div class="refsect1 description" id="<API key>.next-description"> <h3 class="title">Description</h3> <div class="methodsynopsis dc-description"> <span class="modifier">public</span> <span class="type"><span class="type void">void</span></span> <span class="methodname"><strong>SplFixedArray::next</strong></span> ( <span class="methodparam">void</span> )</div> <p class="para rdfs-comment"> Move the iterator to the next array entry. </p> </div> <div class="refsect1 parameters" id="<API key>.next-parameters"> <h3 class="title">Parameters</h3> <p class="para">This function has no parameters.</p> </div> <div class="refsect1 returnvalues" id="<API key>.next-returnvalues"> <h3 class="title">Return Values</h3> <p class="para"> No value is returned. </p> </div> </div><hr /><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="splfixedarray.key.html">SplFixedArray::key</a></div> <div class="next" style="text-align: right; float: right;"><a href="splfixedarray.offsetexists.html">SplFixedArray::offsetExists</a></div> <div class="up"><a href="class.splfixedarray.html">SplFixedArray</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div></body></html>
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http: <head> <title>cuon.DMS.SingleDMS.SingleDMS</title> <link rel="stylesheet" href="epydoc.css" type="text/css"></link> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="center"> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="cuon-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="trees.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="indices.html">Index</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <font size="-1"><b class="breadcrumbs"> <a href="cuon-module.html">Package&nbsp;cuon</a> :: <a href="cuon.DMS-module.html">Package&nbsp;DMS</a> :: <a href="cuon.DMS.SingleDMS-module.html">Module&nbsp;SingleDMS</a> :: Class&nbsp;SingleDMS </b></font></br> </td> <td><table cellpadding="0" cellspacing="0"> <tr><td align="right"><font size="-2">[show&nbsp;private&nbsp;|&nbsp;<a href="../public/cuon.DMS.SingleDMS.SingleDMS-class.html">hide&nbsp;private</a>]</font></td></tr> <tr><td align="right"><font size="-2">[<a href="frames.html"target="_top">frames</a>&nbsp;|&nbsp;<a href="cuon.DMS.SingleDMS.SingleDMS-class.html" target="_top">no&nbsp;frames</a>]</font></td></tr> </table></td> </tr></table> <h2 class="class">Class SingleDMS</h2> <pre class="base-tree"> <a href="cuon.Logging.logs.logs-class.html"><code>logs</code></a> | <a href="../private/cuon.Databases.dumps.dumps-class.html"><code>dumps</code></a> | | <a href="../private/cuon.TypeDefs.defaultValues.defaultValues-class.html"><code>defaultValues</code></a> | | <a href="../private/cuon.Windows.gladeXml.gladeXml-class.html"><code>gladeXml</code></a> | <a href="../private/cuon.Databases.SingleData.SingleData-class.html"><code>SingleData</code></a> | <b>SingleDMS</b> </pre><br /> <hr/> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="summary"> <th colspan="2">Method Summary</th></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><a name="__init__"></a><span class="summary-sig"><span class="summary-sig-name">__init__</span>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>allTables</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><a name="createTmpFile"></a><span class="summary-sig"><span class="summary-sig-name">createTmpFile</span>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sEXT</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><a name="fillOtherEntries"></a><span class="summary-sig"><span class="summary-sig-name">fillOtherEntries</span>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>oneRecord</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><a name="loadDocument"></a><span class="summary-sig"><span class="summary-sig-name">loadDocument</span>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><a name="<API key>"></a><span class="summary-sig"><span class="summary-sig-name"><API key></span>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><a name="<API key>"></a><span class="summary-sig"><span class="summary-sig-name"><API key></span>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicValues</span>)</span></code> </td></tr> <tr bgcolor="#e8f0f8" class="group"> <th colspan="2">&nbsp;&nbsp;&nbsp;&nbsp;Inherited from SingleData</th></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#clearAllFields" class="summary-sig-name"><code>clearAllFields</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#connectTree" class="summary-sig-name"><code>connectTree</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#deleteRecord" class="summary-sig-name"><code>deleteRecord</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#disconnectTree" class="summary-sig-name"><code>disconnectTree</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#fillEntries" class="summary-sig-name"><code>fillEntries</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>id</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#fillExternalWidget" class="summary-sig-name"><code>fillExternalWidget</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>value</span>, <span class=summary-sig-arg>id</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#fillExtraEntries" class="summary-sig-name"><code>fillExtraEntries</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>oneRecord</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#fillTree" class="summary-sig-name"><code>fillTree</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>tree1</span>, <span class=summary-sig-arg>listEntries</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#findSingleId" class="summary-sig-name"><code>findSingleId</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#getEntries" class="summary-sig-name"><code>getEntries</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#getFirstListRecord" class="summary-sig-name"><code>getFirstListRecord</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#getFirstRecord" class="summary-sig-name"><code>getFirstRecord</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#getListEntries" class="summary-sig-name"><code>getListEntries</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#getStaffID" class="summary-sig-name"><code>getStaffID</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicUser</span>, <span class=summary-sig-arg>setBraces</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#getTreeModel" class="summary-sig-name"><code>getTreeModel</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>listEntries</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#isNewRecord" class="summary-sig-name"><code>isNewRecord</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#load" class="summary-sig-name"><code>load</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>record</span>, <span class=summary-sig-arg>dicDetail</span>)</span></code> <br /> Return list of records</td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#loadCompleteTable" class="summary-sig-name"><code>loadCompleteTable</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#loadTable" class="summary-sig-name"><code>loadTable</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>allTables</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#newRecord" class="summary-sig-name"><code>newRecord</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#readEntries" class="summary-sig-name"><code>readEntries</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#readExtraEntries" class="summary-sig-name"><code>readExtraEntries</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicValues</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#refreshTree" class="summary-sig-name"><code>refreshTree</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>Full</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#save" class="summary-sig-name"><code>save</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>liBigEntries</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#saveExternalData" class="summary-sig-name"><code>saveExternalData</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicValues</span>, <span class=summary-sig-arg>liBigEntries</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#saveTable" class="summary-sig-name"><code>saveTable</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#saveValues" class="summary-sig-name"><code>saveValues</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicValues</span>, <span class=summary-sig-arg>liBigEntries</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setEmptyEntries" class="summary-sig-name"><code>setEmptyEntries</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setEntries" class="summary-sig-name"><code>setEntries</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicEntries01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setGladeXml" class="summary-sig-name"><code>setGladeXml</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>xml01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setListHeader" class="summary-sig-name"><code>setListHeader</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>liNames01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setStore" class="summary-sig-name"><code>setStore</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>store01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setTree" class="summary-sig-name"><code>setTree</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>tree01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setTreeFields" class="summary-sig-name"><code>setTreeFields</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>liFields01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#setTreeOrder" class="summary-sig-name"><code>setTreeOrder</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sSort01</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>treeSelection</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#treeSelectRow" class="summary-sig-name"><code>treeSelectRow</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#treeSelectRowById" class="summary-sig-name"><code>treeSelectRowById</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#treeSelectRowByIter" class="summary-sig-name"><code>treeSelectRowByIter</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.SingleData.SingleData-class.html#verifyValues" class="summary-sig-name"><code>verifyValues</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dicValues</span>)</span></code> </td></tr> <tr bgcolor="#e8f0f8" class="group"> <th colspan="2">&nbsp;&nbsp;&nbsp;&nbsp;Inherited from gladeXml</th></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#add2Textbuffer" class="summary-sig-name"><code>add2Textbuffer</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>widget</span>, <span class=summary-sig-arg>text</span>, <span class=summary-sig-arg>direction</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#addEnabledMenuItems" class="summary-sig-name"><code>addEnabledMenuItems</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>, <span class=summary-sig-arg>sMenuItem</span>, <span class=summary-sig-arg>cKey</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#addKeyToItem" class="summary-sig-name"><code>addKeyToItem</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>, <span class=summary-sig-arg>item</span>, <span class=summary-sig-arg>cKey</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#addMenuItem" class="summary-sig-name"><code>addMenuItem</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>item</span>, <span class=summary-sig-arg>sMenue</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#disableAllMenuItems" class="summary-sig-name"><code>disableAllMenuItems</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#disableMenuItem" class="summary-sig-name"><code>disableMenuItem</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#enableAllMenuItems" class="summary-sig-name"><code>enableAllMenuItems</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#enableMenuItem" class="summary-sig-name"><code>enableMenuItem</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>, <span class=summary-sig-arg>sAccel</span>, <span class=summary-sig-arg>sMenuItem</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#getActiveText" class="summary-sig-name"><code>getActiveText</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>combobox</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#getWidget" class="summary-sig-name"><code>getWidget</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#getWidgets" class="summary-sig-name"><code>getWidgets</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sPrefix</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#initMenuItems" class="summary-sig-name"><code>initMenuItems</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#loadGlade" class="summary-sig-name"><code>loadGlade</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>gladeName</span>, <span class=summary-sig-arg>sMainWindow</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#loadGladeComplete" class="summary-sig-name"><code>loadGladeComplete</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>gladeName</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#loadGladeFile" class="summary-sig-name"><code>loadGladeFile</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>gladeName</span>, <span class=summary-sig-arg>sMainWindow</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#readTextBuffer" class="summary-sig-name"><code>readTextBuffer</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>widget</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#setText2Widget" class="summary-sig-name"><code>setText2Widget</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sText</span>, <span class=summary-sig-arg>sWidget</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#setTextbuffer" class="summary-sig-name"><code>setTextbuffer</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>widget</span>, <span class=summary-sig-arg>liField</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#setTitle" class="summary-sig-name"><code>setTitle</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sName</span>, <span class=summary-sig-arg>sTitle</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#setWinAccelGroup" class="summary-sig-name"><code>setWinAccelGroup</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#setXml" class="summary-sig-name"><code>setXml</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>xml</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#setXmlAutoconnect" class="summary-sig-name"><code>setXmlAutoconnect</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#writeAllGladeFiles" class="summary-sig-name"><code>writeAllGladeFiles</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Windows.gladeXml.gladeXml-class.html#writeGlade" class="summary-sig-name"><code>writeGlade</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>fname</span>)</span></code> </td></tr> <tr bgcolor="#e8f0f8" class="group"> <th colspan="2">&nbsp;&nbsp;&nbsp;&nbsp;Inherited from dumps</th></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#closeDB" class="summary-sig-name"><code>closeDB</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#doCompress" class="summary-sig-name"><code>doCompress</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#doDecode" class="summary-sig-name"><code>doDecode</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#doEncode" class="summary-sig-name"><code>doEncode</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#doUncompress" class="summary-sig-name"><code>doUncompress</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#formatDate" class="summary-sig-name"><code>formatDate</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dtDateTime</span>, <span class=summary-sig-arg>strFormat</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getActualDateTime" class="summary-sig-name"><code>getActualDateTime</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getCheckedValue" class="summary-sig-name"><code>getCheckedValue</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>value</span>, <span class=summary-sig-arg>type</span>, <span class=summary-sig-arg>min</span>, <span class=summary-sig-arg>max</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getDateTime" class="summary-sig-name"><code>getDateTime</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dateString</span>, <span class=summary-sig-arg>strFormat</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getFirstDayOfMonth" class="summary-sig-name"><code>getFirstDayOfMonth</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sdate</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sdate</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sdate</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getFirstOfMonth" class="summary-sig-name"><code>getFirstOfMonth</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dtDateTime</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getFirstOfMonth2" class="summary-sig-name"><code>getFirstOfMonth2</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dtDateTime</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getFirstOfYear" class="summary-sig-name"><code>getFirstOfYear</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dtDateTime</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getLastDayOfMonth" class="summary-sig-name"><code>getLastDayOfMonth</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sdate</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#<API key>" class="summary-sig-name"><code><API key></code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sdate</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getLastOfMonth" class="summary-sig-name"><code>getLastOfMonth</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dtDateTime</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getLastOfYear" class="summary-sig-name"><code>getLastOfYear</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dtDateTime</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getSeconds" class="summary-sig-name"><code>getSeconds</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>dt</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getTime" class="summary-sig-name"><code>getTime</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#getTimeString" class="summary-sig-name"><code>getTimeString</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#loadObject" class="summary-sig-name"><code>loadObject</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>key</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#openDB" class="summary-sig-name"><code>openDB</code></a>(<span class=summary-sig-arg>self</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#pickleObject" class="summary-sig-name"><code>pickleObject</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>key</span>, <span class=summary-sig-arg>obj</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#saveObject" class="summary-sig-name"><code>saveObject</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>key</span>, <span class=summary-sig-arg>oValue</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#saveTmpData" class="summary-sig-name"><code>saveTmpData</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>data</span>, <span class=summary-sig-arg>typ</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#showPdf" class="summary-sig-name"><code>showPdf</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>Pdf</span>, <span class=summary-sig-arg>dicUser</span>, <span class=summary-sig-arg>cDoc</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="../private/cuon.Databases.dumps.dumps-class.html#unpickleObject" class="summary-sig-name"><code>unpickleObject</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>key</span>)</span></code> </td></tr> <tr bgcolor="#e8f0f8" class="group"> <th colspan="2">&nbsp;&nbsp;&nbsp;&nbsp;Inherited from logs</th></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="cuon.Logging.logs.logs-class.html#out" class="summary-sig-name"><code>out</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>sLog</span>, <span class=summary-sig-arg>iLogLevel</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="cuon.Logging.logs.logs-class.html#printOut" class="summary-sig-name"><code>printOut</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>s1</span>, <span class=summary-sig-arg>s2</span>, <span class=summary-sig-arg>ok</span>)</span></code> </td></tr> <tr><td align="right" valign="top" width="15%"><font size="-1">&nbsp;</font></td> <td><code><span class="summary-sig"><a href="cuon.Logging.logs.logs-class.html#setLogLevel" class="summary-sig-name"><code>setLogLevel</code></a>(<span class=summary-sig-arg>self</span>, <span class=summary-sig-arg>iLevel</span>)</span></code> </td></tr> </table><br /> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="center"> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="cuon-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="trees.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="indices.html">Index</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar">&nbsp;&nbsp;&nbsp;<a class="navbar" href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <th class="navbar" width="100%"></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left"><font size="-2">Generated by Epydoc 2.1 on Sat Jul 7 09:54:34 2007</font></td> <td align="right"><a href="http://epydoc.sourceforge.net" ><font size="-2">http://epydoc.sf.net</font></a></td> </tr> </table> </body> </html>
-- TE4 - T-Engine 4 -- This program is free software: you can redistribute it and/or modify -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- along with this program. If not, see <http: -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Map = require "engine.Map" require "engine.Generator" module(..., package.seeall, class.inherit(engine.Generator)) function _M:init(zone, map, level, data) engine.Generator.init(self, zone, map, level) self.grid_list = zone.grid_list self.floor = self:resolve("floor") self.wall = self:resolve("wall") self.up = self:resolve("up") end function _M:generate() for i = 0, self.map.w - 1 do for j = 0, self.map.h - 1 do if rng.percent(45) then self.map(i, j, Map.TERRAIN, self.floor) else self.map(i, j, Map.TERRAIN, self.wall) end end end self:evolve() self:evolve() self:evolve() -- self:evolve() -- Always starts at 1, 1 self.map(1, 1, Map.TERRAIN, self.up) self.map.room_map[1][1].special = "exit" return 1, 1 end function _M:evolve() for i = 0, self.map.w - 1 do for j = 0, self.map.h - 1 do self:liveOrDie(i, j) end end end function _M:liveOrDie(x, y) local nb = 0 for _, coord in pairs(util.adjacentCoords(x, y)) do if self.map:isBound(coord[1], coord[2]) then local g = self.map(coord[1], coord[2], Map.TERRAIN) if g and g == self.wall then nb = nb + 1 end end end if nb < 4 or nb > 7 then self.map(x, y, Map.TERRAIN, self.floor) elseif nb == 5 or nb == 6 then self.map(x, y, Map.TERRAIN, self.wall) end end
using System.Collections.Generic; using TouchScript.Hit; using UnityEngine; namespace TouchScript.Layers { <summary> Touch layer which works with Unity 4.3+ 2d physics. Can pick 2d objects hit by touches in right order. </summary> [AddComponentMenu("TouchScript/Layers/Camera Layer 2D")] [HelpURL("http://touchscript.github.io/docs/html/<API key>.htm")] public class CameraLayer2D : CameraLayerBase { #region Private variables [SerializeField] [HideInInspector] private int[] layerIds = new int[0]; private Dictionary<int, int> layerById = new Dictionary<int, int>(); private List<RaycastHit2D> sortedHits = new List<RaycastHit2D>(20); private List<HitTest> tmpHitTestList = new List<HitTest>(10); #endregion #region Unity methods <summary> Unity OnEnable callback. </summary> protected virtual void OnEnable() { if (!Application.isPlaying) return; layerById.Clear(); for (var i = 0; i < layerIds.Length; i++) { var value = layerIds[i]; if (layerById.ContainsKey(value)) continue; layerById.Add(value, i); } } #endregion #region Protected functions <inheritdoc /> protected override LayerHitResult castRay(Ray ray, out TouchHit hit) { hit = default(TouchHit); var raycastHits = Physics2D.<API key>(ray, float.PositiveInfinity, LayerMask); if (raycastHits.Length == 0) return LayerHitResult.Miss; if (raycastHits.Length > 1) { sortHits(raycastHits); RaycastHit2D raycastHit = default(RaycastHit2D); var i = 0; while (i < sortedHits.Count) { raycastHit = sortedHits[i]; switch (doHit(raycastHit, out hit)) { case HitTest.ObjectHitResult.Hit: return LayerHitResult.Hit; case HitTest.ObjectHitResult.Discard: return LayerHitResult.Miss; } i++; } } else { switch (doHit(raycastHits[0], out hit)) { case HitTest.ObjectHitResult.Hit: return LayerHitResult.Hit; case HitTest.ObjectHitResult.Error: return LayerHitResult.Error; default: return LayerHitResult.Miss; } } return LayerHitResult.Miss; } private HitTest.ObjectHitResult doHit(RaycastHit2D raycastHit, out TouchHit hit) { hit = new TouchHit(raycastHit); raycastHit.transform.GetComponents(tmpHitTestList); var count = tmpHitTestList.Count; if (count == 0) return HitTest.ObjectHitResult.Hit; var hitResult = HitTest.ObjectHitResult.Hit; for (var i = 0; i < count; i++) { var test = tmpHitTestList[i]; if (!test.enabled) continue; hitResult = test.IsHit(hit); if (hitResult == HitTest.ObjectHitResult.Miss || hitResult == HitTest.ObjectHitResult.Discard) break; } return hitResult; } private void sortHits(RaycastHit2D[] hits) { sortedHits.Clear(); sortedHits.AddRange(hits); sortedHits.Sort((a, b) => { if (a.collider.transform == b.collider.transform) return 0; var sprite1 = a.transform.GetComponent<SpriteRenderer>(); var sprite2 = b.transform.GetComponent<SpriteRenderer>(); if (sprite1 != null && sprite2 != null) { int s1Id, s2Id; if (!layerById.TryGetValue(sprite1.sortingLayerID, out s1Id)) s1Id = 0; if (!layerById.TryGetValue(sprite2.sortingLayerID, out s2Id)) s2Id = 0; if (s1Id < s2Id) return 1; if (s1Id > s2Id) return -1; if (sprite1.sortingOrder < sprite2.sortingOrder) return 1; if (sprite1.sortingOrder > sprite2.sortingOrder) return -1; } return a.distance < b.distance ? -1 : 1; }); } #endregion } }
#ifndef Yarr_h #define Yarr_h #include <limits.h> #include "YarrInterpreter.h" #include "YarrPattern.h" namespace JSC { namespace Yarr { #define <API key> 1 // Only for !fixed quantifiers. #define <API key> 1 // Only for !fixed quantifiers. #define <API key> 2 #define <API key> 1 // One per alternative. #define <API key> 1 #define <API key> 1 // Only for !fixed quantifiers. #define <API key> 1 #define <API key> 2 static const unsigned quantifyInfinite = UINT_MAX; // The below limit restricts the number of "recursive" match calls in order to // avoid spending exponential time on complex regular expressions. static const unsigned matchLimit = 1000000; enum JSRegExpResult { JSRegExpMatch = 1, JSRegExpNoMatch = 0, <API key> = -1, <API key> = -2, <API key> = -3, <API key> = -4 }; PassOwnPtr<BytecodePattern> byteCompile(YarrPattern&, <API key>*); int interpret(BytecodePattern*, const UChar* input, unsigned start, unsigned length, int* output); } } // namespace JSC::Yarr #endif // Yarr_h
namespace BullsAndCows.Services { using System.Web; using System.Web.Optimization; public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); // Set EnableOptimizations to false for debugging. For more information, BundleTable.EnableOptimizations = true; } } }
<!DOCTYPE html> <html> <link rel='stylesheet' type='text/css' href='reference-style.css'> <style> body > button:nth-child(1) { -moz-transform: matrix(1, -0.2, 0, 1, 0, 0); } body > button:nth-child(2) { -moz-transform: translateX(15em) matrix(1, 0, 0.6, 1, 0, 0); } body > button:nth-child(3) { -moz-transform: rotate(30deg); } body > button:nth-child(4) { -moz-transform: scale(2, 4); } body > button:nth-child(5) { -moz-transform: scale(0.1, 0.4); } body > button:nth-child(6) { -moz-transform: scale(1, 0.4); } body > button:nth-child(7) { -moz-transform: scale(0.1, 1); } body > button:nth-child(8) { -moz-transform: skew(30deg, -10deg); } body > button:nth-child(9) { -moz-transform: skew(-30deg, 10deg); } body > button:nth-child(10) { -moz-transform: translate(10px, 30px); } body > button:nth-child(11) { -moz-transform: translate(30px, 10px); } body > button:nth-child(12) { -moz-transform: translate(-10px, 30px); } body > button:nth-child(13) { -moz-transform: translate(30px, -10px); } body > button:nth-child(14) { -moz-transform: scale(0, 0); } </style> <body> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> <button class="input-color"> <div class="input-color-swatch"> </div> </button> </body> </html>
package com.ludei.inapptest; import android.content.Context; import com.ludei.inapps.InAppService; import com.ludei.inapps.amazon.AmazonInAppService; public class InAppServiceCreator { public static InAppService create(Context ctx) { return new AmazonInAppService(ctx); } }
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use dom::bindings::codegen::Bindings::<API key>::<API key>; use dom::bindings::codegen::Bindings::<API key>; use dom::bindings::codegen::Bindings::<API key>::<API key>; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::UnionTypes::{<API key>, HTMLElementOrLong}; use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{document_from_node, Node}; use dom::window::Window; #[dom_struct] pub struct <API key> { collection: HTMLCollection, } impl <API key> { fn new_inherited(root: &Node, filter: Box<CollectionFilter + 'static>) -> <API key> { <API key> { collection: HTMLCollection::new_inherited(root, filter), } } pub fn new(window: &Window, root: &Node, filter: Box<CollectionFilter + 'static>) -> Root<<API key>> { reflect_dom_object(box <API key>::new_inherited(root, filter), window, <API key>::Wrap) } fn add_new_elements(&self, count: u32) -> ErrorResult { let root = self.upcast().root_node(); let document = document_from_node(root.r()); for _ in 0..count { let element = HTMLOptionElement::new(atom!("option"), None, document.r()); let node = element.upcast::<Node>(); try!(root.AppendChild(node)); }; Ok(()) } } impl <API key> for <API key> { // FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of // <API key>) implements NamedGetter. // https://dom.spec.whatwg.org/#<API key> fn NamedGetter(&self, name: DOMString) -> Option<Root<Element>> { self.upcast().NamedItem(name) } // https://heycam.github.io/webidl/#<API key> fn <API key>(&self) -> Vec<DOMString> { self.upcast().<API key>() } // FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of // <API key>) implements IndexedGetter. // https://dom.spec.whatwg.org/#<API key> fn IndexedGetter(&self, index: u32) -> Option<Root<Element>> { self.upcast().IndexedGetter(index) } // https://html.spec.whatwg.org/multipage/#<API key> fn IndexedSetter(&self, index: u32, value: Option<&HTMLOptionElement>) -> ErrorResult { if let Some(value) = value { // Step 2 let length = self.upcast().Length(); // Step 3 let n = index as i32 - length as i32; // Step 4 if n > 0 { try!(self.add_new_elements(n as u32)); } // Step 5 let node = value.upcast::<Node>(); let root = self.upcast().root_node(); if n >= 0 { Node::pre_insert(node, root.r(), None).map(|_| ()) } else { let child = self.upcast().IndexedGetter(index).unwrap(); let child_node = child.r().upcast::<Node>(); root.r().ReplaceChild(node, child_node).map(|_| ()) } } else { // Step 1 self.Remove(index as i32); Ok(()) } } // https://html.spec.whatwg.org/multipage/#<API key> fn Length(&self) -> u32 { self.upcast().Length() } // https://html.spec.whatwg.org/multipage/#<API key> fn SetLength(&self, length: u32) { let current_length = self.upcast().Length(); let delta = length as i32 - current_length as i32; if delta < 0 { // new length is lower - deleting last option elements for index in (length..current_length).rev() { self.Remove(index as i32) } } else if delta > 0 { // new length is higher - adding new option elements self.add_new_elements(delta as u32).unwrap(); } } // https://html.spec.whatwg.org/multipage/#<API key> fn Add(&self, element: <API key>, before: Option<HTMLElementOrLong>) -> ErrorResult { let root = self.upcast().root_node(); let node: &Node = match element { <API key>::HTMLOptionElement(ref element) => element.upcast(), <API key>::HTMLOptGroupElement(ref element) => element.upcast(), }; // Step 1 if node.is_ancestor_of(root.r()) { return Err(Error::HierarchyRequest); } if let Some(HTMLElementOrLong::HTMLElement(ref before_element)) = before { // Step 2 let before_node = before_element.upcast::<Node>(); if !root.r().is_ancestor_of(before_node) { return Err(Error::NotFound); } // Step 3 if node == before_node { return Ok(()); } } // Step 4 let reference_node = before.and_then(|before| { match before { HTMLElementOrLong::HTMLElement(element) => Some(Root::upcast::<Node>(element)), HTMLElementOrLong::Long(index) => { self.upcast().IndexedGetter(index as u32).map(Root::upcast::<Node>) } } }); // Step 5 let parent = if let Some(reference_node) = reference_node.r() { reference_node.GetParentNode().unwrap() } else { root }; // Step 6 Node::pre_insert(node, parent.r(), reference_node.r()).map(|_| ()) } // https://html.spec.whatwg.org/multipage/#<API key> fn Remove(&self, index: i32) { if let Some(element) = self.upcast().IndexedGetter(index as u32) { element.r().Remove(); } } }
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ var UBound = 0; var BUGNUMBER = 203841; var summary = 'Testing merged if-clauses'; var status = ''; var statusitems = []; var actual = ''; var actualvalues = []; var expect= ''; var expectedvalues = []; status = inSection(1); var a = 0; var b = 0; var c = 0; if (a == 5, b == 6) { c = 1; } actual = c; expect = 0; addThis(); status = inSection(2); a = 5; b = 0; c = 0; if (a == 5, b == 6) { c = 1; } actual = c; expect = 0; addThis(); status = inSection(3); a = 5; b = 6; c = 0; if (a == 5, b == 6) { c = 1; } actual = c; expect = 1; addThis(); /* * Now get tricky and use the = operator inside the if-clause */ status = inSection(4); a = 0; b = 6; c = 0; if (a = 5, b == 6) { c = 1; } actual = c; expect = 1; addThis(); status = inSection(5); c = 0; if (1, 1 == 6) { c = 1; } actual = c; expect = 0; addThis(); /* * Now some tests involving arrays */ var x=[]; status = inSection(6); // get element case c = 0; if (x[1==2]) { c = 1; } actual = c; expect = 0; addThis(); status = inSection(7); // set element case c = 0; if (x[1==2]=1) { c = 1; } actual = c; expect = 1; addThis(); status = inSection(8); // delete element case c = 0; if (delete x[1==2]) { c = 1; } actual = c; expect = 1; addThis(); test(); function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function test() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++) { reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); } exitFunc ('test'); }
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/datastore/v1/query.proto package datastore // import "google.golang.org/genproto/googleapis/datastore/v1" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import wrappers "github.com/golang/protobuf/ptypes/wrappers" import _ "google.golang.org/genproto/googleapis/api/annotations" import _ "google.golang.org/genproto/googleapis/type/latlng" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.<API key> // please upgrade the proto package // Specifies what data the 'entity' field contains. // A `ResultType` is either implied (for example, in `LookupResponse.missing` // from `datastore.proto`, it is always `KEY_ONLY`) or specified by context // (for example, in message `QueryResultBatch`, field `entity_result_type` // specifies a `ResultType` for all the values in field `entity_results`). type <API key> int32 const ( // Unspecified. This value is never used. <API key> <API key> = 0 // The key and properties. EntityResult_FULL <API key> = 1 // A projected subset of properties. The entity may have no key. <API key> <API key> = 2 // Only the key. <API key> <API key> = 3 ) var <API key> = map[int32]string{ 0: "<API key>", 1: "FULL", 2: "PROJECTION", 3: "KEY_ONLY", } var <API key> = map[string]int32{ "<API key>": 0, "FULL": 1, "PROJECTION": 2, "KEY_ONLY": 3, } func (x <API key>) String() string { return proto.EnumName(<API key>, int32(x)) } func (<API key>) EnumDescriptor() ([]byte, []int) { return <API key>, []int{0, 0} } // The sort direction. type <API key> int32 const ( // Unspecified. This value must not be used. <API key> <API key> = 0 // Ascending. <API key> <API key> = 1 // Descending. <API key> <API key> = 2 ) var <API key> = map[int32]string{ 0: "<API key>", 1: "ASCENDING", 2: "DESCENDING", } var <API key> = map[string]int32{ "<API key>": 0, "ASCENDING": 1, "DESCENDING": 2, } func (x <API key>) String() string { return proto.EnumName(<API key>, int32(x)) } func (<API key>) EnumDescriptor() ([]byte, []int) { return <API key>, []int{5, 0} } // A composite filter operator. type <API key> int32 const ( // Unspecified. This value must not be used. <API key> <API key> = 0 // The results are required to satisfy each of the combined filters. CompositeFilter_AND <API key> = 1 ) var <API key> = map[int32]string{ 0: "<API key>", 1: "AND", } var <API key> = map[string]int32{ "<API key>": 0, "AND": 1, } func (x <API key>) String() string { return proto.EnumName(<API key>, int32(x)) } func (<API key>) EnumDescriptor() ([]byte, []int) { return <API key>, []int{7, 0} } // A property filter operator. type <API key> int32 const ( // Unspecified. This value must not be used. <API key> <API key> = 0 // Less than. <API key> <API key> = 1 // Less than or equal. <API key> <API key> = 2 // Greater than. <API key> <API key> = 3 // Greater than or equal. <API key> <API key> = 4 // Equal. <API key> <API key> = 5 // Has ancestor. <API key> <API key> = 11 ) var <API key> = map[int32]string{ 0: "<API key>", 1: "LESS_THAN", 2: "LESS_THAN_OR_EQUAL", 3: "GREATER_THAN", 4: "<API key>", 5: "EQUAL", 11: "HAS_ANCESTOR", } var <API key> = map[string]int32{ "<API key>": 0, "LESS_THAN": 1, "LESS_THAN_OR_EQUAL": 2, "GREATER_THAN": 3, "<API key>": 4, "EQUAL": 5, "HAS_ANCESTOR": 11, } func (x <API key>) String() string { return proto.EnumName(<API key>, int32(x)) } func (<API key>) EnumDescriptor() ([]byte, []int) { return <API key>, []int{8, 0} } // The possible values for the `more_results` field. type <API key> int32 const ( // Unspecified. This value is never used. <API key> <API key> = 0 // There may be additional batches to fetch from this query. <API key> <API key> = 1 // The query is finished, but there may be more results after the limit. <API key> <API key> = 2 // The query is finished, but there may be more results after the end // cursor. <API key> <API key> = 4 // The query is finished, and there are no more results. <API key> <API key> = 3 ) var <API key> = map[int32]string{ 0: "<API key>", 1: "NOT_FINISHED", 2: "<API key>", 4: "<API key>", 3: "NO_MORE_RESULTS", } var <API key> = map[string]int32{ "<API key>": 0, "NOT_FINISHED": 1, "<API key>": 2, "<API key>": 4, "NO_MORE_RESULTS": 3, } func (x <API key>) String() string { return proto.EnumName(<API key>, int32(x)) } func (<API key>) EnumDescriptor() ([]byte, []int) { return <API key>, []int{11, 0} } // The result of fetching an entity from Datastore. type EntityResult struct { // The resulting entity. Entity *Entity `protobuf:"bytes,1,opt,name=entity,proto3" json:"entity,omitempty"` // The version of the entity, a strictly positive number that monotonically // increases with changes to the entity. // This field is set for [`FULL`][google.datastore.v1.EntityResult.ResultType.FULL] entity // results. // For [missing][google.datastore.v1.LookupResponse.missing] entities in `LookupResponse`, this // is the version of the snapshot that was used to look up the entity, and it // is always set except for eventually consistent reads. Version int64 `protobuf:"varint,4,opt,name=version,proto3" json:"version,omitempty"` // A cursor that points to the position after the result entity. // Set only when the `EntityResult` is part of a `QueryResultBatch` message. Cursor []byte `protobuf:"bytes,3,opt,name=cursor,proto3" json:"cursor,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *EntityResult) Reset() { *m = EntityResult{} } func (m *EntityResult) String() string { return proto.CompactTextString(m) } func (*EntityResult) ProtoMessage() {} func (*EntityResult) Descriptor() ([]byte, []int) { return <API key>, []int{0} } func (m *EntityResult) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *EntityResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *EntityResult) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *EntityResult) XXX_Size() int { return <API key>.Size(m) } func (m *EntityResult) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *EntityResult) GetEntity() *Entity { if m != nil { return m.Entity } return nil } func (m *EntityResult) GetVersion() int64 { if m != nil { return m.Version } return 0 } func (m *EntityResult) GetCursor() []byte { if m != nil { return m.Cursor } return nil } // A query for entities. type Query struct { // The projection to return. Defaults to returning all properties. Projection []*Projection `protobuf:"bytes,2,rep,name=projection,proto3" json:"projection,omitempty"` // The kinds to query (if empty, returns entities of all kinds). // Currently at most 1 kind may be specified. Kind []*KindExpression `protobuf:"bytes,3,rep,name=kind,proto3" json:"kind,omitempty"` // The filter to apply. Filter *Filter `protobuf:"bytes,4,opt,name=filter,proto3" json:"filter,omitempty"` // The order to apply to the query results (if empty, order is unspecified). Order []*PropertyOrder `protobuf:"bytes,5,rep,name=order,proto3" json:"order,omitempty"` // The properties to make distinct. The query results will contain the first // result for each distinct combination of values for the given properties // (if empty, all results are returned). DistinctOn []*PropertyReference `protobuf:"bytes,6,rep,name=distinct_on,json=distinctOn,proto3" json:"distinct_on,omitempty"` // A starting point for the query results. Query cursors are // returned in query result batches and // [can only be used to continue the same query](https://cloud.google.com/datastore/docs/concepts/queries#<API key>). StartCursor []byte `protobuf:"bytes,7,opt,name=start_cursor,json=startCursor,proto3" json:"start_cursor,omitempty"` // An ending point for the query results. Query cursors are // returned in query result batches and // [can only be used to limit the same query](https://cloud.google.com/datastore/docs/concepts/queries#<API key>). EndCursor []byte `protobuf:"bytes,8,opt,name=end_cursor,json=endCursor,proto3" json:"end_cursor,omitempty"` // The number of results to skip. Applies before limit, but after all other // constraints. Optional. Must be >= 0 if specified. Offset int32 `protobuf:"varint,10,opt,name=offset,proto3" json:"offset,omitempty"` // The maximum number of results to return. Applies after all other // constraints. Optional. // Unspecified is interpreted as no limit. // Must be >= 0 if specified. Limit *wrappers.Int32Value `protobuf:"bytes,12,opt,name=limit,proto3" json:"limit,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Query) Reset() { *m = Query{} } func (m *Query) String() string { return proto.CompactTextString(m) } func (*Query) ProtoMessage() {} func (*Query) Descriptor() ([]byte, []int) { return <API key>, []int{1} } func (m *Query) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *Query) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *Query) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *Query) XXX_Size() int { return <API key>.Size(m) } func (m *Query) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *Query) GetProjection() []*Projection { if m != nil { return m.Projection } return nil } func (m *Query) GetKind() []*KindExpression { if m != nil { return m.Kind } return nil } func (m *Query) GetFilter() *Filter { if m != nil { return m.Filter } return nil } func (m *Query) GetOrder() []*PropertyOrder { if m != nil { return m.Order } return nil } func (m *Query) GetDistinctOn() []*PropertyReference { if m != nil { return m.DistinctOn } return nil } func (m *Query) GetStartCursor() []byte { if m != nil { return m.StartCursor } return nil } func (m *Query) GetEndCursor() []byte { if m != nil { return m.EndCursor } return nil } func (m *Query) GetOffset() int32 { if m != nil { return m.Offset } return 0 } func (m *Query) GetLimit() *wrappers.Int32Value { if m != nil { return m.Limit } return nil } // A representation of a kind. type KindExpression struct { // The name of the kind. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KindExpression) Reset() { *m = KindExpression{} } func (m *KindExpression) String() string { return proto.CompactTextString(m) } func (*KindExpression) ProtoMessage() {} func (*KindExpression) Descriptor() ([]byte, []int) { return <API key>, []int{2} } func (m *KindExpression) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *KindExpression) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *KindExpression) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *KindExpression) XXX_Size() int { return <API key>.Size(m) } func (m *KindExpression) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *KindExpression) GetName() string { if m != nil { return m.Name } return "" } // A reference to a property relative to the kind expressions. type PropertyReference struct { // The name of the property. // If name includes "."s, it may be interpreted as a property name path. Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PropertyReference) Reset() { *m = PropertyReference{} } func (m *PropertyReference) String() string { return proto.CompactTextString(m) } func (*PropertyReference) ProtoMessage() {} func (*PropertyReference) Descriptor() ([]byte, []int) { return <API key>, []int{3} } func (m *PropertyReference) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *PropertyReference) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *PropertyReference) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *PropertyReference) XXX_Size() int { return <API key>.Size(m) } func (m *PropertyReference) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *PropertyReference) GetName() string { if m != nil { return m.Name } return "" } // A representation of a property in a projection. type Projection struct { // The property to project. Property *PropertyReference `protobuf:"bytes,1,opt,name=property,proto3" json:"property,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Projection) Reset() { *m = Projection{} } func (m *Projection) String() string { return proto.CompactTextString(m) } func (*Projection) ProtoMessage() {} func (*Projection) Descriptor() ([]byte, []int) { return <API key>, []int{4} } func (m *Projection) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *Projection) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *Projection) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *Projection) XXX_Size() int { return <API key>.Size(m) } func (m *Projection) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *Projection) GetProperty() *PropertyReference { if m != nil { return m.Property } return nil } // The desired order for a specific property. type PropertyOrder struct { // The property to order by. Property *PropertyReference `protobuf:"bytes,1,opt,name=property,proto3" json:"property,omitempty"` // The direction to order by. Defaults to `ASCENDING`. Direction <API key> `protobuf:"varint,2,opt,name=direction,proto3,enum=google.datastore.v1.<API key>" json:"direction,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PropertyOrder) Reset() { *m = PropertyOrder{} } func (m *PropertyOrder) String() string { return proto.CompactTextString(m) } func (*PropertyOrder) ProtoMessage() {} func (*PropertyOrder) Descriptor() ([]byte, []int) { return <API key>, []int{5} } func (m *PropertyOrder) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *PropertyOrder) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *PropertyOrder) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *PropertyOrder) XXX_Size() int { return <API key>.Size(m) } func (m *PropertyOrder) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *PropertyOrder) GetProperty() *PropertyReference { if m != nil { return m.Property } return nil } func (m *PropertyOrder) GetDirection() <API key> { if m != nil { return m.Direction } return <API key> } // A holder for any type of filter. type Filter struct { // The type of filter. // Types that are valid to be assigned to FilterType: // *<API key> // *<API key> FilterType isFilter_FilterType `protobuf_oneof:"filter_type"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Filter) Reset() { *m = Filter{} } func (m *Filter) String() string { return proto.CompactTextString(m) } func (*Filter) ProtoMessage() {} func (*Filter) Descriptor() ([]byte, []int) { return <API key>, []int{6} } func (m *Filter) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *Filter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *Filter) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *Filter) XXX_Size() int { return <API key>.Size(m) } func (m *Filter) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo type isFilter_FilterType interface { isFilter_FilterType() } type <API key> struct { CompositeFilter *CompositeFilter `protobuf:"bytes,1,opt,name=composite_filter,json=compositeFilter,proto3,oneof"` } type <API key> struct { PropertyFilter *PropertyFilter `protobuf:"bytes,2,opt,name=property_filter,json=propertyFilter,proto3,oneof"` } func (*<API key>) isFilter_FilterType() {} func (*<API key>) isFilter_FilterType() {} func (m *Filter) GetFilterType() isFilter_FilterType { if m != nil { return m.FilterType } return nil } func (m *Filter) GetCompositeFilter() *CompositeFilter { if x, ok := m.GetFilterType().(*<API key>); ok { return x.CompositeFilter } return nil } func (m *Filter) GetPropertyFilter() *PropertyFilter { if x, ok := m.GetFilterType().(*<API key>); ok { return x.PropertyFilter } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Filter) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return <API key>, <API key>, _Filter_OneofSizer, []interface{}{ (*<API key>)(nil), (*<API key>)(nil), } } func <API key>(msg proto.Message, b *proto.Buffer) error { m := msg.(*Filter) // filter_type switch x := m.FilterType.(type) { case *<API key>: b.EncodeVarint(1<<3 | proto.WireBytes) if err := b.EncodeMessage(x.CompositeFilter); err != nil { return err } case *<API key>: b.EncodeVarint(2<<3 | proto.WireBytes) if err := b.EncodeMessage(x.PropertyFilter); err != nil { return err } case nil: default: return fmt.Errorf("Filter.FilterType has unexpected type %T", x) } return nil } func <API key>(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Filter) switch tag { case 1: // filter_type.composite_filter if wire != proto.WireBytes { return true, proto.<API key> } msg := new(CompositeFilter) err := b.DecodeMessage(msg) m.FilterType = &<API key>{msg} return true, err case 2: // filter_type.property_filter if wire != proto.WireBytes { return true, proto.<API key> } msg := new(PropertyFilter) err := b.DecodeMessage(msg) m.FilterType = &<API key>{msg} return true, err default: return false, nil } } func _Filter_OneofSizer(msg proto.Message) (n int) { m := msg.(*Filter) // filter_type switch x := m.FilterType.(type) { case *<API key>: s := proto.Size(x.CompositeFilter) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *<API key>: s := proto.Size(x.PropertyFilter) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // A filter that merges multiple other filters using the given operator. type CompositeFilter struct { // The operator for combining multiple filters. Op <API key> `protobuf:"varint,1,opt,name=op,proto3,enum=google.datastore.v1.<API key>" json:"op,omitempty"` // The list of filters to combine. // Must contain at least one filter. Filters []*Filter `protobuf:"bytes,2,rep,name=filters,proto3" json:"filters,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CompositeFilter) Reset() { *m = CompositeFilter{} } func (m *CompositeFilter) String() string { return proto.CompactTextString(m) } func (*CompositeFilter) ProtoMessage() {} func (*CompositeFilter) Descriptor() ([]byte, []int) { return <API key>, []int{7} } func (m *CompositeFilter) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *CompositeFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *CompositeFilter) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *CompositeFilter) XXX_Size() int { return <API key>.Size(m) } func (m *CompositeFilter) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *CompositeFilter) GetOp() <API key> { if m != nil { return m.Op } return <API key> } func (m *CompositeFilter) GetFilters() []*Filter { if m != nil { return m.Filters } return nil } // A filter on a specific property. type PropertyFilter struct { // The property to filter by. Property *PropertyReference `protobuf:"bytes,1,opt,name=property,proto3" json:"property,omitempty"` // The operator to filter by. Op <API key> `protobuf:"varint,2,opt,name=op,proto3,enum=google.datastore.v1.<API key>" json:"op,omitempty"` // The value to compare the property to. Value *Value `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *PropertyFilter) Reset() { *m = PropertyFilter{} } func (m *PropertyFilter) String() string { return proto.CompactTextString(m) } func (*PropertyFilter) ProtoMessage() {} func (*PropertyFilter) Descriptor() ([]byte, []int) { return <API key>, []int{8} } func (m *PropertyFilter) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *PropertyFilter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *PropertyFilter) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *PropertyFilter) XXX_Size() int { return <API key>.Size(m) } func (m *PropertyFilter) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *PropertyFilter) GetProperty() *PropertyReference { if m != nil { return m.Property } return nil } func (m *PropertyFilter) GetOp() <API key> { if m != nil { return m.Op } return <API key> } func (m *PropertyFilter) GetValue() *Value { if m != nil { return m.Value } return nil } type GqlQuery struct { // A string of the format described QueryString string `protobuf:"bytes,1,opt,name=query_string,json=queryString,proto3" json:"query_string,omitempty"` // When false, the query string must not contain any literals and instead must // bind all values. For example, // `SELECT * FROM Kind WHERE a = 'string literal'` is not allowed, while // `SELECT * FROM Kind WHERE a = @value` is. AllowLiterals bool `protobuf:"varint,2,opt,name=allow_literals,json=allowLiterals,proto3" json:"allow_literals,omitempty"` // For each non-reserved named binding site in the query string, there must be // a named parameter with that name, but not necessarily the inverse. // Key must match regex `[A-Za-z_$][A-Za-z_$0-9]*`, must not match regex // `__.*__`, and must not be `""`. NamedBindings map[string]*GqlQueryParameter `protobuf:"bytes,5,rep,name=named_bindings,json=namedBindings,proto3" json:"named_bindings,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Numbered binding site @1 references the first numbered parameter, // effectively using 1-based indexing, rather than the usual 0. // For each binding site numbered i in `query_string`, there must be an i-th // numbered parameter. The inverse must also be true. PositionalBindings []*GqlQueryParameter `protobuf:"bytes,4,rep,name=positional_bindings,json=positionalBindings,proto3" json:"positional_bindings,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GqlQuery) Reset() { *m = GqlQuery{} } func (m *GqlQuery) String() string { return proto.CompactTextString(m) } func (*GqlQuery) ProtoMessage() {} func (*GqlQuery) Descriptor() ([]byte, []int) { return <API key>, []int{9} } func (m *GqlQuery) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *GqlQuery) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *GqlQuery) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *GqlQuery) XXX_Size() int { return <API key>.Size(m) } func (m *GqlQuery) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *GqlQuery) GetQueryString() string { if m != nil { return m.QueryString } return "" } func (m *GqlQuery) GetAllowLiterals() bool { if m != nil { return m.AllowLiterals } return false } func (m *GqlQuery) GetNamedBindings() map[string]*GqlQueryParameter { if m != nil { return m.NamedBindings } return nil } func (m *GqlQuery) <API key>() []*GqlQueryParameter { if m != nil { return m.PositionalBindings } return nil } // A binding parameter for a GQL query. type GqlQueryParameter struct { // The type of parameter. // Types that are valid to be assigned to ParameterType: // *<API key> // *<API key> ParameterType <API key> `protobuf_oneof:"parameter_type"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *GqlQueryParameter) Reset() { *m = GqlQueryParameter{} } func (m *GqlQueryParameter) String() string { return proto.CompactTextString(m) } func (*GqlQueryParameter) ProtoMessage() {} func (*GqlQueryParameter) Descriptor() ([]byte, []int) { return <API key>, []int{10} } func (m *GqlQueryParameter) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *GqlQueryParameter) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *GqlQueryParameter) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *GqlQueryParameter) XXX_Size() int { return <API key>.Size(m) } func (m *GqlQueryParameter) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo type <API key> interface { <API key>() } type <API key> struct { Value *Value `protobuf:"bytes,2,opt,name=value,proto3,oneof"` } type <API key> struct { Cursor []byte `protobuf:"bytes,3,opt,name=cursor,proto3,oneof"` } func (*<API key>) <API key>() {} func (*<API key>) <API key>() {} func (m *GqlQueryParameter) GetParameterType() <API key> { if m != nil { return m.ParameterType } return nil } func (m *GqlQueryParameter) GetValue() *Value { if x, ok := m.GetParameterType().(*<API key>); ok { return x.Value } return nil } func (m *GqlQueryParameter) GetCursor() []byte { if x, ok := m.GetParameterType().(*<API key>); ok { return x.Cursor } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*GqlQueryParameter) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return <API key>, <API key>, <API key>, []interface{}{ (*<API key>)(nil), (*<API key>)(nil), } } func <API key>(msg proto.Message, b *proto.Buffer) error { m := msg.(*GqlQueryParameter) // parameter_type switch x := m.ParameterType.(type) { case *<API key>: b.EncodeVarint(2<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Value); err != nil { return err } case *<API key>: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeRawBytes(x.Cursor) case nil: default: return fmt.Errorf("GqlQueryParameter.ParameterType has unexpected type %T", x) } return nil } func <API key>(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*GqlQueryParameter) switch tag { case 2: // parameter_type.value if wire != proto.WireBytes { return true, proto.<API key> } msg := new(Value) err := b.DecodeMessage(msg) m.ParameterType = &<API key>{msg} return true, err case 3: // parameter_type.cursor if wire != proto.WireBytes { return true, proto.<API key> } x, err := b.DecodeRawBytes(true) m.ParameterType = &<API key>{x} return true, err default: return false, nil } } func <API key>(msg proto.Message) (n int) { m := msg.(*GqlQueryParameter) // parameter_type switch x := m.ParameterType.(type) { case *<API key>: s := proto.Size(x.Value) n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *<API key>: n += 1 // tag and wire n += proto.SizeVarint(uint64(len(x.Cursor))) n += len(x.Cursor) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // A batch of results produced by a query. type QueryResultBatch struct { // The number of results skipped, typically because of an offset. SkippedResults int32 `protobuf:"varint,6,opt,name=skipped_results,json=skippedResults,proto3" json:"skipped_results,omitempty"` // A cursor that points to the position after the last skipped result. // Will be set when `skipped_results` != 0. SkippedCursor []byte `protobuf:"bytes,3,opt,name=skipped_cursor,json=skippedCursor,proto3" json:"skipped_cursor,omitempty"` // The result type for every entity in `entity_results`. EntityResultType <API key> `protobuf:"varint,1,opt,name=entity_result_type,json=entityResultType,proto3,enum=google.datastore.v1.<API key>" json:"entity_result_type,omitempty"` // The results for this batch. EntityResults []*EntityResult `protobuf:"bytes,2,rep,name=entity_results,json=entityResults,proto3" json:"entity_results,omitempty"` // A cursor that points to the position after the last result in the batch. EndCursor []byte `protobuf:"bytes,4,opt,name=end_cursor,json=endCursor,proto3" json:"end_cursor,omitempty"` // The state of the query after the current batch. MoreResults <API key> `protobuf:"varint,5,opt,name=more_results,json=moreResults,proto3,enum=google.datastore.v1.<API key>" json:"more_results,omitempty"` // The version number of the snapshot this batch was returned from. // This applies to the range of results from the query's `start_cursor` (or // the beginning of the query if no cursor was given) to this batch's // `end_cursor` (not the query's `end_cursor`). // In a single transaction, subsequent query result batches for the same query // can have a greater snapshot version number. Each batch's snapshot version // is valid for all preceding batches. // The value will be zero for eventually consistent queries. SnapshotVersion int64 `protobuf:"varint,7,opt,name=snapshot_version,json=snapshotVersion,proto3" json:"snapshot_version,omitempty"` <API key> struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *QueryResultBatch) Reset() { *m = QueryResultBatch{} } func (m *QueryResultBatch) String() string { return proto.CompactTextString(m) } func (*QueryResultBatch) ProtoMessage() {} func (*QueryResultBatch) Descriptor() ([]byte, []int) { return <API key>, []int{11} } func (m *QueryResultBatch) XXX_Unmarshal(b []byte) error { return <API key>.Unmarshal(m, b) } func (m *QueryResultBatch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return <API key>.Marshal(b, m, deterministic) } func (dst *QueryResultBatch) XXX_Merge(src proto.Message) { <API key>.Merge(dst, src) } func (m *QueryResultBatch) XXX_Size() int { return <API key>.Size(m) } func (m *QueryResultBatch) XXX_DiscardUnknown() { <API key>.DiscardUnknown(m) } var <API key> proto.InternalMessageInfo func (m *QueryResultBatch) GetSkippedResults() int32 { if m != nil { return m.SkippedResults } return 0 } func (m *QueryResultBatch) GetSkippedCursor() []byte { if m != nil { return m.SkippedCursor } return nil } func (m *QueryResultBatch) GetEntityResultType() <API key> { if m != nil { return m.EntityResultType } return <API key> } func (m *QueryResultBatch) GetEntityResults() []*EntityResult { if m != nil { return m.EntityResults } return nil } func (m *QueryResultBatch) GetEndCursor() []byte { if m != nil { return m.EndCursor } return nil } func (m *QueryResultBatch) GetMoreResults() <API key> { if m != nil { return m.MoreResults } return <API key> } func (m *QueryResultBatch) GetSnapshotVersion() int64 { if m != nil { return m.SnapshotVersion } return 0 } func init() { proto.RegisterType((*EntityResult)(nil), "google.datastore.v1.EntityResult") proto.RegisterType((*Query)(nil), "google.datastore.v1.Query") proto.RegisterType((*KindExpression)(nil), "google.datastore.v1.KindExpression") proto.RegisterType((*PropertyReference)(nil), "google.datastore.v1.PropertyReference") proto.RegisterType((*Projection)(nil), "google.datastore.v1.Projection") proto.RegisterType((*PropertyOrder)(nil), "google.datastore.v1.PropertyOrder") proto.RegisterType((*Filter)(nil), "google.datastore.v1.Filter") proto.RegisterType((*CompositeFilter)(nil), "google.datastore.v1.CompositeFilter") proto.RegisterType((*PropertyFilter)(nil), "google.datastore.v1.PropertyFilter") proto.RegisterType((*GqlQuery)(nil), "google.datastore.v1.GqlQuery") proto.RegisterMapType((map[string]*GqlQueryParameter)(nil), "google.datastore.v1.GqlQuery.NamedBindingsEntry") proto.RegisterType((*GqlQueryParameter)(nil), "google.datastore.v1.GqlQueryParameter") proto.RegisterType((*QueryResultBatch)(nil), "google.datastore.v1.QueryResultBatch") proto.RegisterEnum("google.datastore.v1.<API key>", <API key>, <API key>) proto.RegisterEnum("google.datastore.v1.<API key>", <API key>, <API key>) proto.RegisterEnum("google.datastore.v1.<API key>", <API key>, <API key>) proto.RegisterEnum("google.datastore.v1.<API key>", <API key>, <API key>) proto.RegisterEnum("google.datastore.v1.<API key>", <API key>, <API key>) } func init() { proto.RegisterFile("google/datastore/v1/query.proto", <API key>) } var <API key> = []byte{ // 1313 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0xdd, 0x72, 0xd3, 0x46, 0x14, 0x8e, 0x64, 0x3b, 0x89, 0x8f, 0xff, 0xc4, 0xd2, 0x82, 0x08, 0x50, 0x12, 0x41, 0x4b, 0x3a, 0x03, 0x36, 0x31, 0xc3, 0x94, 0x69, 0xe9, 0x74, 0xfc, 0xa3, 0xc4, 0x06, 0x63, 0x39, 0x6b, 0x27, 0x14, 0x86, 0x19, 0x8d, 0xb0, 0x37, 0x46, 0x45, 0x96, 0xc4, 0x4a, 0x09, 0xcd, 0x83, 0x74, 0xa6, 0x37, 0x7d, 0x81, 0x3e, 0x40, 0x2f, 0xfa, 0x00, 0x6d, 0xa7, 0xcf, 0xd0, 0xeb, 0x5e, 0xf7, 0x11, 0x3a, 0xda, 0x5d, 0xf9, 0x2f, 0xc6, 0xe4, 0x82, 0x3b, 0xed, 0xd9, 0xef, 0xfb, 0xce, 0x9e, 0xb3, 0x67, 0x8f, 0x0e, 0xdc, 0x18, 0x7a, 0xde, 0xd0, 0x21, 0xa5, 0x81, 0x15, 0x5a, 0x41, 0xe8, 0x51, 0x52, 0x3a, 0xd9, 0x29, 0xbd, 0x3d, 0x26, 0xf4, 0xb4, 0xe8, 0x53, 0x2f, 0xf4, 0xd0, 0x45, 0x0e, 0x28, 0x8e, 0x01, 0xc5, 0x93, 0x9d, 0x8d, 0x6b, 0x82, 0x65, 0xf9, 0x76, 0xc9, 0x72, 0x5d, 0x2f, 0xb4, 0x42, 0xdb, 0x73, 0x03, 0x4e, 0xd9, 0xd8, 0x5c, 0xa4, 0x49, 0xdc, 0xd0, 0x0e, 0x85, 0xe8, 0xc6, 0x67, 0x02, 0xc1, 0x56, 0xaf, 0x8e, 0x8f, 0x4a, 0xef, 0xa8, 0xe5, 0xfb, 0x84, 0xc6, 0x0a, 0xaa, 0xd8, 0x0f, 0x4f, 0x7d, 0x52, 0x72, 0xac, 0xd0, 0x71, 0x87, 0x7c, 0x47, 0xfb, 0x4b, 0x82, 0xac, 0xce, 0xa4, 0x30, 0x09, 0x8e, 0x9d, 0x10, 0xdd, 0x87, 0x55, 0x2e, 0xad, 0x4a, 0x9b, 0xd2, 0x76, 0xa6, 0x7c, 0xb5, 0xb8, 0xe0, 0xc0, 0x45, 0x41, 0x11, 0x50, 0xa4, 0xc2, 0xda, 0x09, 0xa1, 0x81, 0xed, 0xb9, 0x6a, 0x72, 0x53, 0xda, 0x4e, 0xe0, 0x78, 0x89, 0x2e, 0xc1, 0x6a, 0xff, 0x98, 0x06, 0x1e, 0x55, 0x13, 0x9b, 0xd2, 0x76, 0x16, 0x8b, 0x95, 0xb6, 0x0f, 0xc0, 0x1d, 0xf6, 0x4e, 0x7d, 0x82, 0xae, 0xc2, 0x65, 0xac, 0x77, 0x0f, 0x5a, 0x3d, 0xb3, 0xf7, 0xbc, 0xa3, 0x9b, 0x07, 0xed, 0x6e, 0x47, 0xaf, 0x35, 0x77, 0x9b, 0x7a, 0x5d, 0x59, 0x41, 0xeb, 0x90, 0xdc, 0x3d, 0x68, 0xb5, 0x14, 0x09, 0xe5, 0x01, 0x3a, 0xd8, 0x78, 0xac, 0xd7, 0x7a, 0x4d, 0xa3, 0xad, 0xc8, 0x28, 0x0b, 0xeb, 0x4f, 0xf4, 0xe7, 0xa6, 0xd1, 0x6e, 0x3d, 0x57, 0x12, 0xda, 0x1f, 0x09, 0x48, 0xed, 0x47, 0x99, 0x46, 0xdf, 0x01, 0xf8, 0xd4, 0xfb, 0x81, 0xf4, 0xa3, 0x2c, 0xaa, 0xf2, 0x66, 0x62, 0x3b, 0x53, 0xbe, 0xb1, 0x30, 0x8e, 0xce, 0x18, 0x86, 0xa7, 0x28, 0xe8, 0x2b, 0x48, 0xbe, 0xb1, 0xdd, 0x81, 0x9a, 0x60, 0xd4, 0x9b, 0x0b, 0xa9, 0x4f, 0x6c, 0x77, 0xa0, 0xff, 0xe8, 0x53, 0x12, 0x44, 0x81, 0x62, 0x46, 0x88, 0xb2, 0x77, 0x64, 0x3b, 0x21, 0xa1, 0x2c, 0x0f, 0xef, 0xcb, 0xde, 0x2e, 0x83, 0x60, 0x01, 0x45, 0x0f, 0x21, 0xe5, 0xd1, 0x01, 0xa1, 0x6a, 0x8a, 0xb9, 0xd3, 0xde, 0x77, 0x52, 0x9f, 0xd0, 0xf0, 0xd4, 0x88, 0x90, 0x98, 0x13, 0xd0, 0x1e, 0x64, 0x06, 0x76, 0x10, 0xda, 0x6e, 0x3f, 0x34, 0x3d, 0x57, 0x5d, 0x65, 0xfc, 0x2f, 0x96, 0xf2, 0x31, 0x39, 0x22, 0x94, 0xb8, 0x7d, 0x82, 0x21, 0xa6, 0x1a, 0x2e, 0xda, 0x82, 0x6c, 0x10, 0x5a, 0x34, 0x34, 0xc5, 0x65, 0xad, 0xb1, 0xcb, 0xca, 0x30, 0x5b, 0x8d, 0x99, 0xd0, 0x75, 0x00, 0xe2, 0x0e, 0x62, 0xc0, 0x3a, 0x03, 0xa4, 0x89, 0x3b, 0x10, 0xdb, 0x97, 0x60, 0xd5, 0x3b, 0x3a, 0x0a, 0x48, 0xa8, 0xc2, 0xa6, 0xb4, 0x9d, 0xc2, 0x62, 0x85, 0x76, 0x20, 0xe5, 0xd8, 0x23, 0x3b, 0x54, 0xb3, 0xb3, 0x09, 0x89, 0x4b, 0xb5, 0xd8, 0x74, 0xc3, 0xfb, 0xe5, 0x43, 0xcb, 0x39, 0x26, 0x98, 0x23, 0xb5, 0x5b, 0x90, 0x9f, 0x4d, 0x2e, 0x42, 0x90, 0x74, 0xad, 0x11, 0x61, 0x25, 0x99, 0xc6, 0xec, 0x5b, 0xbb, 0x0d, 0x17, 0xce, 0xc4, 0x34, 0x06, 0xca, 0x53, 0xc0, 0x0e, 0xc0, 0xe4, 0x9a, 0x51, 0x15, 0xd6, 0x7d, 0x41, 0x13, 0x15, 0x7e, 0xde, 0x7c, 0x8d, 0x79, 0xda, 0xbf, 0x12, 0xe4, 0x66, 0xee, 0xe3, 0x63, 0xa8, 0xa2, 0xc7, 0x90, 0x1e, 0xd8, 0x74, 0x5c, 0xb4, 0xd2, 0x76, 0xbe, 0x7c, 0xe7, 0xc3, 0xa5, 0x50, 0xac, 0xc7, 0x1c, 0x3c, 0xa1, 0x6b, 0x3a, 0xa4, 0xc7, 0x76, 0x74, 0x05, 0x3e, 0xad, 0x37, 0x31, 0x7f, 0x35, 0x73, 0x6f, 0x2b, 0x07, 0xe9, 0x4a, 0xb7, 0xa6, 0xb7, 0xeb, 0xcd, 0xf6, 0x1e, 0x7f, 0x60, 0x75, 0x7d, 0xbc, 0x96, 0xb5, 0xdf, 0x25, 0x58, 0xe5, 0xc5, 0x8a, 0xf6, 0x41, 0xe9, 0x7b, 0x23, 0xdf, 0x0b, 0xec, 0x90, 0x98, 0xa2, 0xc6, 0x79, 0xa4, 0xb7, 0x16, 0x1e, 0xb2, 0x16, 0x83, 0x39, 0xbf, 0xb1, 0x82, 0x0b, 0xfd, 0x59, 0x13, 0x6a, 0x43, 0x21, 0x0e, 0x3e, 0x56, 0x94, 0x99, 0xe2, 0xcd, 0xa5, 0x61, 0x8f, 0x05, 0xf3, 0xfe, 0x8c, 0xa5, 0x9a, 0x83, 0x0c, 0x97, 0x31, 0xa3, 0x3e, 0xa7, 0xfd, 0x26, 0x41, 0x61, 0xee, 0x14, 0xe8, 0x5b, 0x90, 0x3d, 0x9f, 0x9d, 0x3b, 0x5f, 0xbe, 0x7b, 0x9e, 0x73, 0x17, 0x0d, 0x9f, 0x50, 0x2b, 0xf4, 0x28, 0x96, 0x3d, 0x1f, 0x3d, 0x80, 0x35, 0xee, 0x21, 0x10, 0x5d, 0x65, 0xe9, 0xfb, 0x8e, 0xb1, 0xda, 0x5d, 0x58, 0x8f, 0x65, 0x90, 0x0a, 0x9f, 0x18, 0x1d, 0x1d, 0x57, 0x7a, 0x06, 0x9e, 0xbb, 0x8b, 0x35, 0x48, 0x54, 0xda, 0x75, 0x45, 0xd2, 0xfe, 0x91, 0x21, 0x3f, 0x1b, 0xec, 0x47, 0xa9, 0xaf, 0x47, 0x2c, 0xf6, 0xf3, 0x14, 0xd6, 0xa2, 0xd0, 0xef, 0x41, 0xea, 0x24, 0x7a, 0xa4, 0xac, 0x8f, 0x67, 0xca, 0x1b, 0x0b, 0x05, 0xc4, 0x33, 0x66, 0x40, 0xed, 0x27, 0xe9, 0x5c, 0x61, 0xe7, 0x20, 0xdd, 0xd2, 0xbb, 0x5d, 0xb3, 0xd7, 0xa8, 0xb4, 0x15, 0x09, 0x5d, 0x02, 0x34, 0x5e, 0x9a, 0x06, 0x36, 0xf5, 0xfd, 0x83, 0x4a, 0x4b, 0x91, 0x91, 0x02, 0xd9, 0x3d, 0xac, 0x57, 0x7a, 0x3a, 0xe6, 0xc8, 0x44, 0x54, 0xd6, 0xd3, 0x96, 0x09, 0x38, 0x89, 0xd2, 0x90, 0xe2, 0x9f, 0xa9, 0x88, 0xd7, 0xa8, 0x74, 0xcd, 0x4a, 0xbb, 0xa6, 0x77, 0x7b, 0x06, 0x56, 0x32, 0xda, 0x7f, 0x32, 0xac, 0xef, 0xbd, 0x75, 0xf8, 0xaf, 0x62, 0x0b, 0xb2, 0xec, 0xef, 0x6c, 0x06, 0x21, 0xb5, 0xdd, 0xa1, 0xe8, 0x30, 0x19, 0x66, 0xeb, 0x32, 0x13, 0xfa, 0x1c, 0xf2, 0x96, 0xe3, 0x78, 0xef, 0x4c, 0xc7, 0x0e, 0x09, 0xb5, 0x9c, 0x80, 0xe5, 0x70, 0x1d, 0xe7, 0x98, 0xb5, 0x25, 0x8c, 0xe8, 0x19, 0xe4, 0xa3, 0x76, 0x33, 0x30, 0x5f, 0xd9, 0xee, 0xc0, 0x76, 0x87, 0x81, 0x68, 0xe7, 0xf7, 0x16, 0x66, 0x2a, 0x3e, 0x40, 0xb1, 0x1d, 0x71, 0xaa, 0x82, 0xa2, 0xbb, 0x21, 0x3d, 0xc5, 0x39, 0x77, 0xda, 0x86, 0x9e, 0xc1, 0x45, 0x56, 0x91, 0xb6, 0xe7, 0x5a, 0xce, 0x44, 0x3d, 0xb9, 0xa4, 0xd9, 0xc7, 0xea, 0x1d, 0x8b, 0x5a, 0x23, 0x12, 0xd5, 0x22, 0x9a, 0x48, 0xc4, 0xc2, 0x1b, 0xaf, 0x01, 0x9d, 0xf5, 0x8e, 0x14, 0x48, 0xbc, 0x21, 0xa7, 0x22, 0x11, 0xd1, 0x27, 0x7a, 0x14, 0x5f, 0xbd, 0xbc, 0xa4, 0xf2, 0xce, 0xba, 0xe4, 0xa4, 0xaf, 0xe5, 0x87, 0x92, 0x16, 0xc0, 0x85, 0x33, 0xfb, 0xa8, 0x3c, 0x2b, 0xbb, 0xa4, 0xa2, 0x1a, 0x2b, 0x42, 0x0c, 0xa9, 0xb3, 0xe3, 0x44, 0x63, 0x25, 0x1e, 0x28, 0xaa, 0x0a, 0xe4, 0xfd, 0x58, 0x9a, 0xbf, 0xff, 0x3f, 0x93, 0xa0, 0x30, 0x97, 0x7c, 0xd0, 0xa8, 0x5a, 0x61, 0xff, 0x35, 0xba, 0x0d, 0x85, 0xe0, 0x8d, 0xed, 0xfb, 0x64, 0x60, 0x52, 0x66, 0x0e, 0xd4, 0x55, 0xf6, 0xbf, 0xca, 0x0b, 0x33, 0x07, 0x07, 0xd1, 0xad, 0xc7, 0xc0, 0x99, 0x01, 0x26, 0x27, 0xac, 0xe2, 0xb7, 0xf7, 0x02, 0x10, 0x9f, 0x81, 0x84, 0x1c, 0x73, 0x2d, 0x1a, 0xcc, 0x9d, 0x65, 0xa3, 0x13, 0x43, 0x17, 0x27, 0x33, 0x10, 0x56, 0xc8, 0xd4, 0x06, 0x9b, 0x8a, 0x1a, 0x90, 0x9f, 0xd1, 0x8e, 0x9b, 0xce, 0xd6, 0x07, 0x75, 0x71, 0x6e, 0x5a, 0x2c, 0x98, 0xfb, 0x77, 0x27, 0xe7, 0xff, 0xdd, 0xdf, 0x43, 0x76, 0xe4, 0x51, 0x32, 0x76, 0x93, 0x62, 0xc7, 0x7f, 0xb0, 0xd0, 0xcd, 0x7c, 0x46, 0x8b, 0x4f, 0x3d, 0x4a, 0x84, 0x1f, 0x16, 0x47, 0x66, 0x34, 0x31, 0xa0, 0x2f, 0x41, 0x09, 0x5c, 0xcb, 0x0f, 0x5e, 0x7b, 0xa1, 0x19, 0x4f, 0x88, 0x6b, 0x6c, 0x42, 0x2c, 0xc4, 0xf6, 0x43, 0x6e, 0xd6, 0x7e, 0x96, 0xa0, 0x30, 0xa7, 0x85, 0xb6, 0xe0, 0xfa, 0x53, 0x03, 0xeb, 0x26, 0x1f, 0x0e, 0xbb, 0x8b, 0xa6, 0x43, 0x05, 0xb2, 0x6d, 0xa3, 0x67, 0xee, 0x36, 0xdb, 0xcd, 0x6e, 0x43, 0xaf, 0x2b, 0x12, 0xba, 0x06, 0xea, 0x0c, 0xa9, 0xb2, 0x1b, 0xb5, 0x88, 0x56, 0xf3, 0x69, 0xb3, 0xa7, 0xc8, 0xe8, 0x3a, 0x5c, 0x59, 0xb0, 0x5b, 0x3b, 0xc0, 0x5d, 0x03, 0x2b, 0x49, 0x74, 0x11, 0x0a, 0x6d, 0xc3, 0x9c, 0x46, 0x28, 0x89, 0xea, 0x2f, 0x12, 0x5c, 0xee, 0x7b, 0xa3, 0x45, 0xf9, 0xa8, 0x02, 0xaf, 0xea, 0x68, 0x9a, 0xe9, 0x48, 0x2f, 0x1e, 0x09, 0xc8, 0xd0, 0x73, 0x2c, 0x77, 0x58, 0xf4, 0xe8, 0xb0, 0x34, 0x24, 0x2e, 0x9b, 0x75, 0x4a, 0x7c, 0xcb, 0xf2, 0xed, 0x60, 0x66, 0x92, 0xff, 0x66, 0xbc, 0xf8, 0x55, 0xbe, 0xb2, 0xc7, 0xe9, 0x35, 0xc7, 0x3b, 0x1e, 0x14, 0xeb, 0x63, 0x3f, 0x87, 0x3b, 0x7f, 0xc7, 0x7b, 0x2f, 0xd9, 0xde, 0xcb, 0xf1, 0xde, 0xcb, 0xc3, 0x9d, 0x57, 0xab, 0xcc, 0xc1, 0xfd, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0xcd, 0x38, 0x05, 0xaa, 0x7d, 0x0c, 0x00, 0x00, }
package lz4 import ( "encoding/binary" "fmt" "math/bits" ) // blockHash hashes the lower 6 bytes into a value < htSize. func blockHash(x uint64) uint32 { const prime6bytes = 227718039650203 return uint32(((x << (64 - 48)) * prime6bytes) >> (64 - hashLog)) } // CompressBlockBound returns the maximum size of a given buffer of size n, when not compressible. func CompressBlockBound(n int) int { return n + n/255 + 16 } // UncompressBlock uncompresses the source buffer into the destination one, // and returns the uncompressed size. // The destination buffer must be sized appropriately. // An error is returned if the source data is invalid or the destination buffer is too small. func UncompressBlock(src, dst []byte) (int, error) { if len(src) == 0 { return 0, nil } if di := decodeBlock(dst, src); di >= 0 { return di, nil } return 0, <API key> } // CompressBlock compresses the source buffer into the destination one. // This is the fast version of LZ4 compression and also the default one. // The size of hashTable must be at least 64Kb. // The size of the compressed data is returned. If it is 0 and no error, then the data is incompressible. // An error is returned if the destination buffer is too small. func CompressBlock(src, dst []byte, hashTable []int) (di int, err error) { defer recoverBlock(&err) // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible. // This significantly speeds up incompressible data and usually has very small impact on compresssion. // bytes to skip = 1 + (bytes since last match >> adaptSkipLog) const adaptSkipLog = 7 sn, dn := len(src)-mfLimit, len(dst) if sn <= 0 || dn == 0 { return 0, nil } if len(hashTable) < htSize { return 0, fmt.Errorf("hash table too small, should be at least %d in size", htSize) } // Prove to the compiler the table has at least htSize elements. // The compiler can see that "uint32() >> hashShift" cannot be out of bounds. hashTable = hashTable[:htSize] // si: Current position of the search. // anchor: Position of the current literals. var si, anchor int // Fast scan strategy: the hash table only stores the last 4 bytes sequences. for si < sn { // Hash the next 6 bytes (sequence)... match := binary.LittleEndian.Uint64(src[si:]) h := blockHash(match) h2 := blockHash(match >> 8) // We check a match at s, s+1 and s+2 and pick the first one we get. // Checking 3 only requires us to load the source one. ref := hashTable[h] ref2 := hashTable[h2] hashTable[h] = si hashTable[h2] = si + 1 offset := si - ref // If offset <= 0 we got an old entry in the hash table. if offset <= 0 || offset >= winSize || // Out of window. uint32(match) != binary.LittleEndian.Uint32(src[ref:]) { // Hash collision on different matches. // No match. Start calculating another hash. // The processor can usually do this out-of-order. h = blockHash(match >> 16) ref = hashTable[h] // Check the second match at si+1 si += 1 offset = si - ref2 if offset <= 0 || offset >= winSize || uint32(match>>8) != binary.LittleEndian.Uint32(src[ref2:]) { // No match. Check the third match at si+2 si += 1 offset = si - ref hashTable[h] = si if offset <= 0 || offset >= winSize || uint32(match>>16) != binary.LittleEndian.Uint32(src[ref:]) { // Skip one extra byte (at si+3) before we check 3 matches again. si += 2 + (si-anchor)>>adaptSkipLog continue } } } // Match found. lLen := si - anchor // Literal length. // We already matched 4 bytes. mLen := 4 // Extend backwards if we can, reducing literals. tOff := si - offset - 1 for lLen > 0 && tOff >= 0 && src[si-1] == src[tOff] { si tOff lLen mLen++ } // Add the match length, so we continue search at the end. // Use mLen to store the offset base. si, mLen = si+mLen, si+minMatch // Find the longest match by looking by batches of 8 bytes. for si < sn { x := binary.LittleEndian.Uint64(src[si:]) ^ binary.LittleEndian.Uint64(src[si-offset:]) if x == 0 { si += 8 } else { // Stop is first non-zero byte. si += bits.TrailingZeros64(x) >> 3 break } } mLen = si - mLen if mLen < 0xF { dst[di] = byte(mLen) } else { dst[di] = 0xF } // Encode literals length. if lLen < 0xF { dst[di] |= byte(lLen << 4) } else { dst[di] |= 0xF0 di++ l := lLen - 0xF for ; l >= 0xFF; l -= 0xFF { dst[di] = 0xFF di++ } dst[di] = byte(l) } di++ // Literals. copy(dst[di:di+lLen], src[anchor:anchor+lLen]) di += lLen + 2 anchor = si // Encode offset. _ = dst[di] // Bound check elimination. dst[di-2], dst[di-1] = byte(offset), byte(offset>>8) // Encode match length part 2. if mLen >= 0xF { for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF { dst[di] = 0xFF di++ } dst[di] = byte(mLen) di++ } // Check if we can load next values. if si >= sn { break } // Hash match end-2 h = blockHash(binary.LittleEndian.Uint64(src[si-2:])) hashTable[h] = si - 2 } if anchor == 0 { // Incompressible. return 0, nil } // Last literals. lLen := len(src) - anchor if lLen < 0xF { dst[di] = byte(lLen << 4) } else { dst[di] = 0xF0 di++ for lLen -= 0xF; lLen >= 0xFF; lLen -= 0xFF { dst[di] = 0xFF di++ } dst[di] = byte(lLen) } di++ // Write the last literals. if di >= anchor { // Incompressible. return 0, nil } di += copy(dst[di:di+len(src)-anchor], src[anchor:]) return di, nil } // blockHash hashes 4 bytes into a value < winSize. func blockHashHC(x uint32) uint32 { const hasher uint32 = 2654435761 // Knuth multiplicative hash. return x * hasher >> (32 - winSizeLog) } // CompressBlockHC compresses the source buffer src into the destination dst // with max search depth (use 0 or negative value for no max). // CompressBlockHC compression ratio is better than CompressBlock but it is also slower. // The size of the compressed data is returned. If it is 0 and no error, then the data is not compressible. // An error is returned if the destination buffer is too small. func CompressBlockHC(src, dst []byte, depth int) (di int, err error) { defer recoverBlock(&err) // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible. // This significantly speeds up incompressible data and usually has very small impact on compresssion. // bytes to skip = 1 + (bytes since last match >> adaptSkipLog) const adaptSkipLog = 7 sn, dn := len(src)-mfLimit, len(dst) if sn <= 0 || dn == 0 { return 0, nil } var si int // hashTable: stores the last position found for a given hash // chainTable: stores previous positions for a given hash var hashTable, chainTable [winSize]int if depth <= 0 { depth = winSize } anchor := si for si < sn { // Hash the next 4 bytes (sequence). match := binary.LittleEndian.Uint32(src[si:]) h := blockHashHC(match) // Follow the chain until out of window and give the longest match. mLen := 0 offset := 0 for next, try := hashTable[h], depth; try > 0 && next > 0 && si-next < winSize; next = chainTable[next&winMask] { // The first (mLen==0) or next byte (mLen>=minMatch) at current match length // must match to improve on the match length. if src[next+mLen] != src[si+mLen] { continue } ml := 0 // Compare the current position with a previous with the same hash. for ml < sn-si { x := binary.LittleEndian.Uint64(src[next+ml:]) ^ binary.LittleEndian.Uint64(src[si+ml:]) if x == 0 { ml += 8 } else { // Stop is first non-zero byte. ml += bits.TrailingZeros64(x) >> 3 break } } if ml < minMatch || ml <= mLen { // Match too small (<minMath) or smaller than the current match. continue } // Found a longer match, keep its position and length. mLen = ml offset = si - next // Try another previous position with the same hash. try } chainTable[si&winMask] = hashTable[h] hashTable[h] = si // No match found. if mLen == 0 { si += 1 + (si-anchor)>>adaptSkipLog continue } // Match found. // Update hash/chain tables with overlapping bytes: // si already hashed, add everything from si+1 up to the match length. winStart := si + 1 if ws := si + mLen - winSize; ws > winStart { winStart = ws } for si, ml := winStart, si+mLen; si < ml; { match >>= 8 match |= uint32(src[si+3]) << 24 h := blockHashHC(match) chainTable[si&winMask] = hashTable[h] hashTable[h] = si si++ } lLen := si - anchor si += mLen mLen -= minMatch // Match length does not include minMatch. if mLen < 0xF { dst[di] = byte(mLen) } else { dst[di] = 0xF } // Encode literals length. if lLen < 0xF { dst[di] |= byte(lLen << 4) } else { dst[di] |= 0xF0 di++ l := lLen - 0xF for ; l >= 0xFF; l -= 0xFF { dst[di] = 0xFF di++ } dst[di] = byte(l) } di++ // Literals. copy(dst[di:di+lLen], src[anchor:anchor+lLen]) di += lLen anchor = si // Encode offset. di += 2 dst[di-2], dst[di-1] = byte(offset), byte(offset>>8) // Encode match length part 2. if mLen >= 0xF { for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF { dst[di] = 0xFF di++ } dst[di] = byte(mLen) di++ } } if anchor == 0 { // Incompressible. return 0, nil } // Last literals. lLen := len(src) - anchor if lLen < 0xF { dst[di] = byte(lLen << 4) } else { dst[di] = 0xF0 di++ lLen -= 0xF for ; lLen >= 0xFF; lLen -= 0xFF { dst[di] = 0xFF di++ } dst[di] = byte(lLen) } di++ // Write the last literals. if di >= anchor { // Incompressible. return 0, nil } di += copy(dst[di:di+len(src)-anchor], src[anchor:]) return di, nil }
<?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } require_once('include/MVC/View/views/view.detail.php'); class FP_eventsViewDetail extends ViewDetail { public $currSymbol; public function __construct() { parent::__construct(); } /** * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead */ public function FP_eventsViewDetail() { $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code'; if (isset($GLOBALS['log'])) { $GLOBALS['log']->deprecated($deprecatedMessage); } else { trigger_error($deprecatedMessage, E_USER_DEPRECATED); } self::__construct(); } public function display() { $this->bean->email_templates(); parent::display(); } }
import gevent import itertools from inbox.config import config from inbox.ignition import engine_manager from inbox.models.session import <API key> from inbox.models import Account from inbox.util.concurrency import retry_with_logging from inbox.util.stats import statsd_client from nylas.logging import get_logger from redis import StrictRedis log = get_logger() <API key> = 5 SOCKET_TIMEOUT = 5 class QueueClient(object): """Interface to a Redis queue/hashmap combo for managing account sync allocation. """ # Lua scripts for atomic assignment and conflict-free unassignment. ASSIGN = ''' local k = redis.call('RPOP', KEYS[1]) if k then local s = redis.call('HSETNX', KEYS[2], k, ARGV[1]) if s then return k end end''' UNASSIGN = ''' if redis.call('HGET', KEYS[1], KEYS[2]) == ARGV[1] then return redis.call('HDEL', KEYS[1], KEYS[2]) else return 0 end ''' def __init__(self, zone): self.zone = zone redis_host = config['<API key>'] redis_db = config['<API key>'] self.redis = StrictRedis(host=redis_host, db=redis_db, <API key>=<API key>, socket_timeout=SOCKET_TIMEOUT) def all(self): """ Returns all keys being tracked (either pending in the queue, or already assigned). """ p = self.redis.pipeline(transaction=True) p.hgetall(self._hash) p.lrange(self._queue, 0, -1) unassigned, assigned = p.execute() return {int(k) for k in itertools.chain(unassigned, assigned)} def assigned(self): """ Returns a dictionary of all currently assigned key/value pairs (keys are coerced to integers). """ return {int(k): v for k, v in self.redis.hgetall(self._hash).items()} def enqueue(self, key): """ Adds a new key onto the pending queue. """ self.redis.lpush(self._queue, key) def claim_next(self, value): """ Pulls the next key off of the pending queue (if any exists), and sets it to `value` in the hash. Returns None if the queue is empty or if the key is already present in the hash; otherwise returns the key. """ s = self.redis.register_script(self.ASSIGN) return s(keys=[self._queue, self._hash], args=[value]) def unassign(self, key, value): """ Removes `key` from the hash, if and only if it is present and set to `value` (to prevent removing a key actually assigned to someone else). """ s = self.redis.register_script(self.UNASSIGN) return s(keys=[self._hash, key], args=[value]) def qsize(self): """ Returns current length of the queue. """ return self.redis.llen(self._queue) @property def _queue(self): return 'unassigned_{}'.format(self.zone) @property def _hash(self): return 'assigned_{}'.format(self.zone) class QueuePopulator(object): """ Polls the database for account ids to sync and queues them. Run one of these per zone. """ def __init__(self, zone, poll_interval=1): self.zone = zone self.poll_interval = poll_interval self.queue_client = QueueClient(zone) self.shards = [] for database in config['DATABASE_HOSTS']: if database.get('ZONE') == self.zone: shard_ids = [shard['ID'] for shard in database['SHARDS']] self.shards.extend(shard_id for shard_id in shard_ids if shard_id in engine_manager.engines) def run(self): log.info('Queueing accounts', zone=self.zone, shards=self.shards) while True: retry_with_logging(self._run_impl) def _run_impl(self): self.<API key>() self.<API key>() statsd_client.gauge('syncqueue.queue.{}.length'.format(self.zone), self.queue_client.qsize()) statsd_client.incr('syncqueue.service.{}.heartbeat'. format(self.zone)) gevent.sleep(self.poll_interval) def <API key>(self): """ Finds any account ids that should sync, but are not currently being tracked by the QueueClient. Enqueue them. (Note: it's okay to enqueue the same id twice. QueueClient.claim_next will identify and discard duplicates.) """ new_accounts = self.runnable_accounts() - self.queue_client.all() for account_id in new_accounts: log.info('Enqueuing new account', account_id=account_id) self.queue_client.enqueue(account_id) def <API key>(self): runnable_accounts = self.runnable_accounts() disabled_accounts = { k: v for k, v in self.queue_client.assigned().items() if k not in runnable_accounts } for account_id, sync_host in disabled_accounts.items(): log.info('Removing disabled account', account_id=account_id) self.queue_client.unassign(account_id, sync_host) def runnable_accounts(self): accounts = set() for key in self.shards: with <API key>(key) as db_session: accounts.update( id_ for id_, in db_session.query(Account.id).filter( Account.sync_should_run)) return accounts
window.ASC.Files.Folders = (function () { var tasksTimeout = null; var bulkStatuses = false; var isFirstLoad = true; var currentFolder = {}; var folderContainer = ""; var eventAfter = null; var typeNewDoc = ""; var isCopyTo = false; /* Methods*/ var getFolderItems = function (isAppend, countAppend) { var filterSettings = ASC.Files.Filter.getFilterSettings(ASC.Files.Folders.currentFolder.id); ASC.Files.ServiceManager.getFolderItems(ASC.Files.ServiceManager.events.GetFolderItems, { folderId: ASC.Files.Folders.currentFolder.id, from: (isAppend ? jq("#filesMainContent .file-row[name!=\"addRow\"]").length : 0), count: countAppend || ASC.Files.Constants.COUNT_ON_PAGE, append: isAppend === true, filter: filterSettings.filter, subject: filterSettings.subject, text: filterSettings.text, orderBy: filterSettings.sorter }, { orderBy: filterSettings.sorter }); }; var getItems = function (dataIds, folderToId) { var data = { entry: jq(typeof dataIds == "object" ? dataIds : [dataIds]).map(function (i, id) { return Encoder.htmlEncode(id); }).toArray() }; var filterSettings = ASC.Files.Filter.getFilterSettings(ASC.Files.Folders.currentFolder.id); ASC.Files.ServiceManager.getItems(ASC.Files.ServiceManager.events.GetItems, { parentFolderID: folderToId, filter: filterSettings.filter, subject: filterSettings.subject, text: filterSettings.text, }, { stringList: data }); }; var clickOnFolder = function (folderId) { if (ASC.Files.Folders.folderContainer == "trash") { return; } if (folderId == ASC.Files.Constants.FOLDER_ID_PROJECT && ASC.Files.Tree.folderIdCurrentRoot && ASC.Files.Tree.folderIdCurrentRoot != ASC.Files.Constants.FOLDER_ID_PROJECT) { location.href = "tmdocs.aspx"; return false; } ASC.Files.Anchor.navigationSet(folderId); }; var clickOnFile = function (fileData, forEdit, version) { var fileObj = fileData.entryObject; if (ASC.Files.Folders.folderContainer == "trash" && jq("#filesMainContent").find(fileObj).is(":visible")) { return false; } var fileId = fileData.id; var fileTitle = fileData.title || ASC.Files.UI.getEntryTitle("file", fileId); version = version || fileData.version || -1; if (ASC.Files.Utility.CanWebView(fileTitle) || ASC.Files.Utility.CanWebEdit(fileTitle)) { return ASC.Files.Converter.checkCanOpenEditor(fileId, fileTitle, version, forEdit != false); } if (typeof ASC.Files.ImageViewer != "undefined" && ASC.Files.Utility.CanImageView(fileTitle)) { var hash = ASC.Files.ImageViewer.getPreviewHash(fileId); ASC.Files.Anchor.move(hash); return true; } if (jq.browser.mobile) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.<API key>, true); return true; } var url = ASC.Files.Utility.GetFileViewUrl(fileId, version); window.open(url, "_blank"); return ASC.Files.Marker.removeNewIcon("file", fileId); }; var updateIfExist = function (target) { var value = jq(target).prop("checked"); ASC.Files.ServiceManager.updateIfExist(ASC.Files.ServiceManager.events.UpdateIfExist, { value: value }); }; var download = function (entryType, entryId, version) { var list = new Array(); if (!ASC.Files.Common.isCorrectId(entryId)) { list = jq("#filesMainContent .file-row:has(.checkbox input:checked)"); if (list.length == 0) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.<API key>, true); return; } if (list.length == 1) { var itemData = ASC.Files.UI.getObjectData(list[0]); entryId = itemData.entryId; entryType = itemData.entryType; } } if (entryType === "file") { if (jq.browser.mobile) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.<API key>, true); return; } ASC.Files.Marker.removeNewIcon(entryType, entryId); window.open(ASC.Files.Utility.GetFileDownloadUrl(entryId, version), "_blank"); return; } if (ASC.Files.Folders.bulkStatuses == true) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.<API key>, true); return; } var data = new Array(); if (ASC.Files.Common.isCorrectId(entryId)) { data.push( { Key: Encoder.htmlEncode(entryType + "_" + entryId), Value: "" }); ASC.Files.Marker.removeNewIcon(entryType, entryId); } else { list.each(function () { var curItemData = ASC.Files.UI.getObjectData(this); data.push( { Key: Encoder.htmlEncode(curItemData.entryType + "_" + curItemData.entryId), Value: "" }); ASC.Files.Marker.removeNewIcon(curItemData.entryType, curItemData.entryId); }); } ASC.Files.Folders.bulkDownload(data); }; var bulkDownload = function (data) { ASC.Files.Folders.bulkStatuses = true; ASC.Files.ServiceManager.download(ASC.Files.ServiceManager.events.Download, { doNow: true }, data); }; var getActionHtml = function () { return "" + "<div class=\"rename-action\">" + "<div class=\"button gray btn-action __apply name-aplly\" title=" + ASC.Files.FilesJSResources.TitleCreate + "></div>" + "<div class=\"button gray btn-action __reset name-cancel\" title=" + ASC.Files.FilesJSResources.TitleCancel + "></div>" + "</div>"; }; var cancelEnter = function (event, cancelButton) { var entryObject = jq(cancelButton || this).closest(".file-row"); if (!entryObject.attr("name")) { entryObject .removeClass("row-rename") .find("#promptRename, .rename-action").remove(); } else { entryObject.remove(); if (jq("#filesMainContent .file-row").length == 0) { ASC.Files.EmptyScreen.displayEmptyScreen(); } } }; var createFolder = function () { if (ASC.Files.ImageViewer && ASC.Files.ImageViewer.isView()) { return; } if (!ASC.Files.UI.accessEdit() || ASC.Files.UI.isSettingsPanel()) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.<API key>, true); return; } jq(document).scrollTop(0); var newFolderObj = ASC.Files.UI.getEntryObject("folder", "0"); if (newFolderObj.length != 0) { return; } var emptyFolder = { folder: { id: "0", title: ASC.Files.FilesJSResources.TitleNewFolder, access: 0, shared: false, isnew: 0, shareable: false } }; var stringData = ASC.Files.Common.jsonToXml(emptyFolder); var htmlXML = ASC.Files.TemplateManager.translateFromString(stringData); ASC.Files.EmptyScreen.hideEmptyScreen(); var mainContent = jq("#filesMainContent"); mainContent.prepend(htmlXML); jq("#filesMainContent .new-folder").yellowFade().removeClass("new-folder"); newFolderObj = ASC.Files.UI.getEntryObject("folder", "0"); newFolderObj.addClass("row-rename"); var obj = newFolderObj.find(".entry-title .name a"); var ftClass = ASC.Files.Utility.getFolderCssClass(); newFolderObj.find(".thumb-folder").addClass(ftClass); var newContainer = document.createElement("input"); newContainer.id = "promptCreateFolder"; newContainer.type = "text"; newContainer.style.display = "none"; document.body.appendChild(newContainer); newContainer = jq("#promptCreateFolder"); newContainer.attr("maxlength", ASC.Files.Constants.MAX_NAME_LENGTH); newContainer.addClass("textEdit input-rename"); newContainer.val(ASC.Files.FilesJSResources.TitleNewFolder); newContainer.insertAfter(obj); newContainer.show(); obj.hide(); newContainer.focus(); if (!jq.browser.mobile) { newContainer.select(); } ASC.Files.UI.checkCharacter(newContainer); var saveFolder = function (event, saveButton) { var newFolderSaveObj = jq(saveButton || this).closest(".file-row"); var newName = ASC.Files.Common.<API key>(jq("#promptCreateFolder").val().trim()); if (newName == "" || newName == null) { newName = ASC.Files.FilesJSResources.TitleNewFolder; } newFolderSaveObj.find(".entry-title .name a").show().text(newName); newFolderSaveObj.removeClass("row-rename"); jq("#promptCreateFolder").remove(); newFolderSaveObj.find(".rename-action").remove(); var params = { parentFolderID: ASC.Files.Folders.currentFolder.id, title: newName }; ASC.Files.UI.blockObject(newFolderSaveObj, true, ASC.Files.FilesJSResources.DescriptCreate); ASC.Files.ServiceManager.createFolder(ASC.Files.ServiceManager.events.CreateFolder, params); }; newFolderObj.append(getActionHtml()); newFolderObj.find(".name-aplly").click(saveFolder); jq("#promptCreateFolder").bind(jq.browser.webkit || jq.browser.msie ? "keydown" : "keypress", function (event) { if (jq("#promptCreateFolder").length == 0) { return; } if (!e) { var e = event; } var code = e.keyCode || e.which; switch (code) { case ASC.Files.Common.keyCode.esc: ASC.Files.Folders.cancelEnter(e, this); break; case ASC.Files.Common.keyCode.enter: saveFolder(e, this); break; } }); }; var createNewDoc = function () { if (ASC.Files.ImageViewer && ASC.Files.ImageViewer.isView()) { return; } if (!ASC.Resources.Master.<API key>) { ASC.Files.UI.<API key>(); return; } if (ASC.Files.UI.<API key>()) { return; } if (!ASC.Files.UI.accessEdit() || ASC.Files.UI.isSettingsPanel()) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.<API key>, true); return; } jq(document).scrollTop(0); var newFileObj = ASC.Files.UI.getEntryObject("file", "0"); newFileObj.remove(); var titleNewDoc; switch (ASC.Files.Folders.typeNewDoc) { case "document": titleNewDoc = ASC.Files.FilesJSResources.TitleNewFileText + ASC.Files.Utility.Resource.InternalFormats.Document; break; case "spreadsheet": titleNewDoc = ASC.Files.FilesJSResources.<API key> + ASC.Files.Utility.Resource.InternalFormats.Spreadsheet; break; case "presentation": titleNewDoc = ASC.Files.FilesJSResources.<API key> + ASC.Files.Utility.Resource.InternalFormats.Presentation; break; default: return; } if (!ASC.Files.Utility.CanWebEdit(titleNewDoc)) { return; } var emptyFile = { file: { id: "0", title: titleNewDoc, access: 0, shared: false, version: 0, version_group: 0 } }; var stringData = ASC.Files.Common.jsonToXml(emptyFile); var htmlXML = ASC.Files.TemplateManager.translateFromString(stringData); ASC.Files.EmptyScreen.hideEmptyScreen(); var mainContent = jq("#filesMainContent"); mainContent.prepend(htmlXML); jq("#filesMainContent .new-file").show().yellowFade().removeClass("new-file"); newFileObj = ASC.Files.UI.getEntryObject("file", "0"); newFileObj.addClass("row-rename"); var obj = newFileObj.find(".entry-title .name a"); var ftClass = ASC.Files.Utility.<API key>(titleNewDoc); newFileObj.find(".thumb-file").addClass(ftClass); var lenExt = ASC.Files.Utility.GetFileExtension(titleNewDoc).length; titleNewDoc = titleNewDoc.substring(0, titleNewDoc.length - lenExt); var newContainer = document.createElement("input"); newContainer.id = "promptCreateFile"; newContainer.type = "text"; newContainer.style.display = "none"; document.body.appendChild(newContainer); newContainer = jq("#promptCreateFile"); newContainer.attr("maxlength", ASC.Files.Constants.MAX_NAME_LENGTH - lenExt); newContainer.addClass("textEdit input-rename"); newContainer.val(titleNewDoc); newContainer.insertAfter(obj); newContainer.show().focus(); if (!jq.browser.mobile) { newContainer.select(); } ASC.Files.UI.checkCharacter(newContainer); var saveFile = function (event, saveButton) { var newFileSaveObj = jq(saveButton || this).closest(".file-row"); var newName = ASC.Files.Common.<API key>(jq("#promptCreateFile").val().trim()); var oldName = ASC.Files.UI.getObjectTitle(newFileSaveObj); if (newName == "" || newName == null) { newName = oldName; } else { var curLenExt = ASC.Files.Utility.GetFileExtension(oldName).length; newName += oldName.substring(oldName.length - curLenExt); } newFileSaveObj.removeClass("row-rename"); jq("#promptCreateFile").remove(); newFileSaveObj.find(".rename-action").remove(); newFileSaveObj.find(".entry-title .name a").show().text(newName); var rowLink = newFileSaveObj.find(".entry-title .name a"); ASC.Files.UI.highlightExtension(rowLink, newName); var params = { folderID: ASC.Files.Folders.currentFolder.id, fileTitle: newName, winEditor: window.open("") }; ASC.Files.UI.blockObject(newFileObj, true, ASC.Files.FilesJSResources.DescriptCreate); ASC.Files.ServiceManager.createNewFile(ASC.Files.ServiceManager.events.CreateNewFile, params); }; newFileObj.append(getActionHtml()); newFileObj.find(".name-aplly").click(saveFile); jq("#promptCreateFile").bind(jq.browser.webkit || jq.browser.msie ? "keydown" : "keypress", function (event) { if (jq("#promptCreateFile").length == 0) { return; } if (!e) { var e = event; } var code = e.keyCode || e.which; switch (code) { case ASC.Files.Common.keyCode.esc: ASC.Files.Folders.cancelEnter(e, this); break; case ASC.Files.Common.keyCode.enter: saveFile(e, this); break; } }); }; var rename = function (entryType, entryId) { var entryObj = ASC.Files.UI.getEntryObject(entryType, entryId); var lenExt = 0; if (jq("#promptRename").length != 0) { jq("#filesMainContent .file-row.row-rename .name-cancel").click(); } if (entryObj.find("#contentVersions").length) { ASC.Files.Folders.closeVersions(); } entryObj.addClass("row-rename"); ASC.Files.UI.selectRow(entryObj, false); ASC.Files.UI.<API key>(); var entryTitle = ASC.Files.UI.getObjectTitle(entryObj); if (entryType == "file") { lenExt = ASC.Files.Utility.GetFileExtension(entryTitle).length; entryTitle = entryTitle.substring(0, entryTitle.length - lenExt); } var newContainer = document.createElement("input"); newContainer.id = "promptRename"; newContainer.type = "text"; newContainer.style.display = "none"; document.body.appendChild(newContainer); newContainer = jq("#promptRename"); newContainer.attr("maxlength", ASC.Files.Constants.MAX_NAME_LENGTH - lenExt); newContainer.addClass("textEdit input-rename"); newContainer.val(entryTitle); newContainer.insertAfter(entryObj.find(".entry-title .name a")); newContainer.show().focus(); if (!jq.browser.mobile) { newContainer.select(); } ASC.Files.UI.checkCharacter(newContainer); var saveRename = function () { var entryRenameData = ASC.Files.UI.getObjectData(jq("#promptRename")); var entryRenameObj = entryRenameData.entryObject; var entryRenameType = entryRenameData.entryType; var entryRenameId = entryRenameData.entryId; var oldName = ASC.Files.UI.getObjectTitle(entryRenameObj); var newName = ASC.Files.Common.<API key>(jq("#promptRename").val().trim()); if (newName == "" || newName == null) { return; } entryRenameObj.removeClass("row-rename"); entryRenameObj.find(".rename-action").remove(); jq("#promptRename").remove(); if (entryRenameType == "file") { var lenExtRename = ASC.Files.Utility.GetFileExtension(oldName).length; newName += oldName.substring(oldName.length - lenExtRename); } if (newName != oldName) { entryRenameObj.find(".entry-title .name a").show().text(newName); if (entryRenameType == "file") { var rowLink = entryRenameObj.find(".entry-title .name a"); ASC.Files.UI.highlightExtension(rowLink, newName); } ASC.Files.UI.blockObject(entryRenameObj, true, ASC.Files.FilesJSResources.DescriptRename); if (entryRenameType == "file") { ASC.Files.ServiceManager.renameFile(ASC.Files.ServiceManager.events.FileRename, { fileId: entryRenameId, name: oldName, newname: newName, show: true }); } else { ASC.Files.ServiceManager.renameFolder(ASC.Files.ServiceManager.events.FolderRename, { parentFolderID: ASC.Files.Folders.currentFolder.id, folderId: entryRenameId, name: oldName, newname: newName }); } } }; entryObj.append(getActionHtml()); entryObj.find(".name-aplly").click(saveRename); entryObj.removeClass("row-selected"); jq("#promptRename").bind(jq.browser.webkit || jq.browser.msie ? "keydown" : "keypress", function (event) { if (jq(" return; } if (!e) { var e = event; } var code = e.keyCode || e.which; if ((code == ASC.Files.Common.keyCode.esc || code == ASC.Files.Common.keyCode.enter) && jq("#promptRename").length != 0) { switch (code) { case ASC.Files.Common.keyCode.esc: ASC.Files.Folders.cancelEnter(e, this); break; case ASC.Files.Common.keyCode.enter: saveRename(); break; } } }); }; var lockFile = function (fileObj, fileId) { if (ASC.Files.Folders.folderContainer == "trash") { return; } fileObj = jq(fileObj); if (!fileObj.is(".file-row")) { fileObj = fileObj.closest(".file-row"); } if (ASC.Files.UI.lockedForMe(fileObj) && !ASC.Files.Constants.ADMIN) { return; } var locked = fileObj.hasClass("file-locked"); fileObj.toggleClass("file-locked", !locked); fileId = fileId || ASC.Files.UI.getObjectData(fileObj).entryId; ASC.Files.ServiceManager.lockFile(ASC.Files.ServiceManager.events.LockFile, { fileId: fileId, lock: !locked, fileObj: fileObj }); }; var showVersions = function (fileObj, fileId) { if (ASC.Files.Folders.folderContainer == "trash") { return; } fileObj = jq(fileObj); if (!fileObj.is(".file-row")) { fileObj = fileObj.closest(".file-row"); } if (fileObj.hasClass("folder-row")) { return; } if (fileObj.find(".version").length == 0) { return; } if (jq("#contentVersions:visible").length != 0) { var close = fileObj.find("#contentVersions").length != 0; ASC.Files.Folders.closeVersions(); if (close) { return; } } ASC.Files.UI.blockObject(fileObj, true, ASC.Files.FilesJSResources.DescriptLoadVersion); fileId = fileId || ASC.Files.UI.getObjectData(fileObj).entryId; ASC.Files.ServiceManager.getFileHistory(ASC.Files.ServiceManager.events.GetFileHistory, { fileId: fileId }); }; var <API key> = function (versionGroup) { ASC.Files.Actions.hideAllActionPanels(); jq("#contentVersions .version-row[data-version-group='" + versionGroup + "']:not(.version-group-head)").toggle(); }; var makeCurrentVersion = function (fileId, version) { jq(".version-operation").css("visibility", "hidden"); ASC.Files.UI.blockObjectById("file", fileId, true, ASC.Files.FilesJSResources.DescriptSetVersion); ASC.Files.ServiceManager.setCurrentVersion(ASC.Files.ServiceManager.events.SetCurrentVersion, { fileId: fileId, version: version }); }; var versionComplete = function (fileId, version, continueVersion) { ASC.Files.Actions.hideAllActionPanels(); jq(".version-operation").css("visibility", "hidden"); ASC.Files.UI.blockObjectById("file", fileId, true, ASC.Files.FilesJSResources.<API key>); ASC.Files.ServiceManager.completeVersion(ASC.Files.ServiceManager.events.CompleteVersion, { fileId: fileId, version: version, continueVersion: continueVersion }); return false; }; var enterComment = function () { ASC.Files.Actions.hideAllActionPanels(); var fileObj = jq(this).closest(".file-row"); if (!ASC.Files.UI.accessEdit(null, fileObj) || ASC.Files.UI.editingFile(fileObj) || ASC.Files.UI.lockedForMe(fileObj)) { return true; } var versionObj = jq(this).closest(".version-row"); var commentObj = versionObj.find(".version-comment"); var comment = commentObj.attr("data-comment"); ASC.Files.Folders.eraseComment(); commentObj.empty(); versionObj.addClass("version-row-comment"); commentObj.attr("colspan", 4); var newContainer = document.createElement("input"); newContainer.id = "<API key>"; newContainer.type = "text"; newContainer.style.display = "none"; document.body.appendChild(newContainer); newContainer = jq("#<API key>"); newContainer.attr("maxlength", 255); newContainer.attr("placeholder", ASC.Files.FilesJSResources.EnterComment); newContainer.addClass("textEdit input-rename"); newContainer.val(comment); commentObj.append(newContainer); newContainer.show(); newContainer.focus(); if (!jq.browser.mobile) { newContainer.select(); } var saveComment = function () { var editor = jq("#<API key>"); commentObj = editor.closest(".version-comment"); comment = commentObj.attr("data-comment"); var fileId = ASC.Files.UI.getObjectData(commentObj).id; var version = commentObj.closest(".version-row").attr("data-version"); var newComment = editor.val().trim(); if (newComment != comment) { ASC.Files.ServiceManager.updateComment(ASC.Files.ServiceManager.events.UpdateComment, { fileId: fileId, version: version, comment: newComment }); } ASC.Files.Folders.eraseComment(); }; commentObj.append(getActionHtml()); commentObj.find(".name-aplly").click(saveComment); jq("#<API key>").bind(jq.browser.webkit || jq.browser.msie ? "keydown" : "keypress", function (event) { if (jq("#<API key>").length == 0) { return; } if (!e) { var e = event; } var code = e.keyCode || e.which; switch (code) { case ASC.Files.Common.keyCode.esc: ASC.Files.Folders.eraseComment(); break; case ASC.Files.Common.keyCode.enter: saveComment(); break; } }); jq(document).on("click.Comment", function (e) { e = ASC.Files.Common.fixEvent(e); if (!jq(e.target || e.srcElement).is(".version-comment:has(#<API key>) *")) { ASC.Files.Folders.eraseComment(); jq(document).off("click.Comment"); } }); return false; }; var eraseComment = function () { var oldComment = jq(".version-row-comment .version-comment").attr("data-comment"); jq(".version-row-comment .version-comment").html("<div class=\"version-comment-fix\">" + Encoder.htmlEncode(oldComment) + "</div>").removeAttr("colspan"); jq(".version-row-comment").removeClass("version-row-comment"); }; var closeVersions = function () { jq("#contentVersions").remove(); jq(".file-row-fix").removeClass("file-row-fix"); }; var replaceVersion = function (fileId, show) { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.ServiceManager.getFile(ASC.Files.ServiceManager.events.ReplaceVersion, { fileId: fileId, show: show, isStringXml: false }); }; var <API key> = function (listData, folderId, folderToTitle, isCopyOperation, data) { var folderTitle = ASC.Files.UI.getEntryTitle("folder", folderId) || (ASC.Files.Tree ? ASC.Files.Tree.getFolderTitle(folderId) : ""); var message; if (data.length > 1) { var files = ""; for (var i = 0; i < data.length; i++) { files += "<li title=\"{0}\">{0}</li>".format(data[i].Value); } message = "<b>" + ASC.Files.FilesJSResources.FilesAlreadyExist.format(data.length, folderTitle) + "</b>"; jq("#overwriteList").html(files).show(); } else { jq("#overwriteList").hide(); message = ASC.Files.FilesJSResources.FileAlreadyExist.format("<span title=\"" + data[0].Value + "\">" + data[0].Value + "</span>", "<b>" + folderTitle + "</b>"); } jq("#overwriteMessage").html(message); jq("#buttonOverwrite").unbind("click").click(function () { <API key>.CloseDialogAction = ""; <API key>.CloseDialog(); ASC.Files.ServiceManager.moveItems(ASC.Files.ServiceManager.events.MoveItems, { folderToId: folderId, resolve: 1, isCopyOperation: (isCopyOperation == true), doNow: true }, { stringList: listData }); }); jq("#buttonSkipOverwrite").unbind("click").click(function () { for (i = 0; i < data.length; i++) { ASC.Files.UI.blockObjectById("file", data[i].Key, false, null, true); var pos = jq.inArray("file_" + data[i].Key, listData.entry); if (pos != -1) { listData.entry.splice(pos, 1); } } ASC.Files.UI.<API key>(); <API key>.CloseDialogAction = ""; <API key>.CloseDialog(); ASC.Files.ServiceManager.moveItems(ASC.Files.ServiceManager.events.MoveItems, { folderToId: folderId, resolve: 0, isCopyOperation: (isCopyOperation == true), doNow: true }, { stringList: listData }); }); jq("#<API key>").unbind("click").click(function () { for (i = 0; i < listData.entry.length; i++) { var itemId = ASC.Files.UI.parseItemId(listData.entry[i]); ASC.Files.UI.blockObjectById(itemId.entryType, itemId.entryId, false, null, true); } ASC.Files.UI.<API key>(); <API key>.CloseDialogAction = ""; <API key>.CloseDialog(); }); ASC.Files.UI.blockUI("#<API key>", 420, 300); <API key>.EnterAction = "jq(\"#buttonOverwrite\").click();"; <API key>.CloseDialogAction = "jq(\"#<API key>\").click();"; }; var curItemFolderMoveTo = function (folderToId, folderToTitle, pathDest) { if (folderToId === ASC.Files.Folders.currentFolder.entryId) { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.isCopyTo = false; return; } var thirdParty = typeof ASC.Files.ThirdParty != "undefined"; var takeThirdParty = thirdParty && (ASC.Files.Folders.isCopyTo == true || ASC.Files.ThirdParty.isThirdParty()); var moveAccessDeny = false; var data = {}; data.entry = new Array(); Encoder.EncodeType = "!entity"; jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):has(.checkbox input:checked)").each(function () { var entryData = ASC.Files.UI.getObjectData(this); var entryType = entryData.entryType; var entryObj = entryData.entryObject; var entryId = entryData.entryId; if (ASC.Files.Folders.isCopyTo == true || (!ASC.Files.UI.editingFile(entryObj) && !ASC.Files.UI.lockedForMe(entryObj))) { if (ASC.Files.Folders.isCopyTo == false && !ASC.Files.UI.accessDelete(entryObj)) { moveAccessDeny = true; } else { if (jq.inArray(entryId, pathDest) != -1) { ASC.Files.UI.displayInfoPanel(((ASC.Files.Folders.isCopyTo == true) ? ASC.Files.FilesJSResources.InfoFolderCopyError : ASC.Files.FilesJSResources.InfoFolderMoveError), true); } else { if (takeThirdParty || !thirdParty || !ASC.Files.ThirdParty.isThirdParty(entryData)) { ASC.Files.UI.blockObject(entryObj, true, (ASC.Files.Folders.isCopyTo == true) ? ASC.Files.FilesJSResources.DescriptCopy : ASC.Files.FilesJSResources.DescriptMove, true); data.entry.push(Encoder.htmlEncode(entryType + "_" + entryId)); } } } } }); Encoder.EncodeType = "entity"; if (moveAccessDeny) { ASC.Files.UI.displayInfoPanel(ASC.Files.FilesJSResources.InfoMoveAccessError, true); } ASC.Files.UI.<API key>(); ASC.Files.Actions.hideAllActionPanels(); if (data.entry && data.entry.length != 0) { ASC.Files.ServiceManager.moveFilesCheck(ASC.Files.ServiceManager.events.MoveFilesCheck, { folderToTitle: folderToTitle, folderToId: folderToId, list: data, isCopyOperation: (ASC.Files.Folders.isCopyTo == true) }, { stringList: data }); } ASC.Files.Folders.isCopyTo = false; }; var createDuplicate = function (listEntries) { var listData = {}; listData.entry = new Array(); jq(listEntries).each(function (i, e) { listData.entry.push(e.entryType + "_" + e.id); }); ASC.Files.ServiceManager.moveItems(ASC.Files.ServiceManager.events.MoveItems, { folderToId: ASC.Files.Folders.currentFolder.entryId, resolve: 2, isCopyOperation: true, doNow: true }, { stringList: listData }); }; var showMore = function () { if (jq("#pageNavigatorHolder:visible").length == 0 || jq("#pageNavigatorHolder a").text() == ASC.Files.FilesJSResources.ButtonShowMoreLoad) { return; } jq("#pageNavigatorHolder a").text(ASC.Files.FilesJSResources.ButtonShowMoreLoad); ASC.Files.Folders.getFolderItems(true); }; var emptyTrash = function () { if (ASC.Files.Folders.folderContainer != "trash") { return; } ASC.Files.Actions.hideAllActionPanels(); ASC.Files.UI.checkSelectAll(true); jq("#confirmRemoveText").html("<b>" + ASC.Files.FilesJSResources.ConfirmEmptyTrash + "</b>"); jq("#confirmRemoveList").hide(); jq("#<API key>").show(); jq("#removeConfirmBtn").unbind("click").click(function () { <API key>.CloseDialog(); ASC.Files.ServiceManager.emptyTrash(ASC.Files.ServiceManager.events.EmptyTrash, { doNow: true }); }); ASC.Files.UI.blockUI("#confirmRemove", 420, 0, -150); <API key>.EnterAction = "jq(\"#removeConfirmBtn\").click();"; }; var deleteItem = function (entryType, entryId) { ASC.Files.Actions.hideAllActionPanels(); var caption = ASC.Files.FilesJSResources.ConfirmRemoveList; var list = new Array(); if (entryType && entryId) { var entryObj = ASC.Files.UI.getEntryObject(entryType, entryId); if (!ASC.Files.UI.accessDelete(entryObj) || ASC.Files.UI.editingFile(entryObj) || ASC.Files.UI.lockedForMe(entryObj)) { return; } list.push({ entryType: entryType, entryId: entryId }); } else { jq("#filesMainContent .file-row:not(.checkloading):not(.new-folder):not(.new-file):not(.error-entry):has(.checkbox input:checked)").each(function () { var entryRowData = ASC.Files.UI.getObjectData(this); var entryRowObj = entryRowData.entryObject; var entryRowType = entryRowData.entryType; var entryRowId = entryRowData.entryId; if (ASC.Files.ThirdParty && !ASC.Files.ThirdParty.isThirdParty() && ASC.Files.ThirdParty.isThirdParty(entryRowData)) { return true; } if (ASC.Files.UI.accessDelete(entryRowObj) && !ASC.Files.UI.editingFile(entryRowObj) && !ASC.Files.UI.lockedForMe(entryRowObj)) { list.push({ entryType: entryRowType, entryId: entryRowId }); } }); } if (list.length == 0) { return; } if (list.length == 1) { if (list[0].entryType == "file") { caption = ASC.Files.FilesJSResources.ConfirmRemoveFile; } else { caption = ASC.Files.FilesJSResources.ConfirmRemoveFolder; } } var textFolder = ""; var textFile = ""; var strHtml = "<label title=\"{0}\"><input type=\"checkbox\" class=\"checkbox\" entryType=\"{1}\" entryId=\"{2}\" checked=\"checked\">{0}</label>"; for (var i = 0; i < list.length; i++) { var entryRowTitle = ASC.Files.UI.getEntryTitle(list[i].entryType, list[i].entryId); if (list[i].entryType == "file") { textFile += strHtml.format(entryRowTitle, list[i].entryType, list[i].entryId); } else { textFolder += strHtml.format(entryRowTitle, list[i].entryType, list[i].entryId); } } jq("#confirmRemoveText").html("<b>" + caption + "</b>"); jq("#confirmRemoveList dd.<API key>").html(textFile); jq("#confirmRemoveList dd.<API key>").html(textFolder); jq("#confirmRemoveList .<API key>, #confirmRemoveList .<API key>").show(); if (textFolder == "") { jq("#confirmRemoveList .<API key>").hide(); } if (textFile == "") { jq("#confirmRemoveList .<API key>").hide(); } var checkRemoveItem = function () { jq("#confirmRemoveList .<API key>").text(jq("#confirmRemoveList dd.<API key> :checked").length); jq("#confirmRemoveList .<API key>").text(jq("#confirmRemoveList dd.<API key> :checked").length); }; checkRemoveItem(); jq("#confirmRemoveList dd [type='checkbox']").change(checkRemoveItem); if (ASC.Files.ThirdParty && ASC.Files.ThirdParty.isThirdParty()) { jq("#<API key>").show(); } else { jq("#<API key>").hide(); } if (ASC.Files.Folders.folderContainer == "trash") { jq("#<API key>").show(); } else { jq("#<API key>").hide(); } jq("#removeConfirmBtn").unbind("click").click(function () { <API key>.CloseDialog(); var data = {}; var listChecked = jq("#confirmRemoveList input:checked"); if (listChecked.length == 0) { return; } Encoder.EncodeType = "!entity"; data.entry = jq(listChecked).map(function (j, item) { var entryConfirmType = jq(item).attr("entryType"); var entryConfirmId = jq(item).attr("entryId"); var entryConfirmObj = ASC.Files.UI.getEntryObject(entryConfirmType, entryConfirmId); ASC.Files.UI.blockObject(entryConfirmObj, true, ASC.Files.FilesJSResources.DescriptRemove, true); return Encoder.htmlEncode(entryConfirmType + "_" + entryConfirmId); }).toArray(); Encoder.EncodeType = "entity"; ASC.Files.UI.<API key>(); ASC.Files.ServiceManager.deleteItem(ASC.Files.ServiceManager.events.DeleteItem, { list: data.entry, doNow: true }, { stringList: data }); }); ASC.Files.UI.blockUI("#confirmRemove", 420, 0, -150); <API key>.EnterAction = "jq(\"#removeConfirmBtn\").click();"; }; var cancelTasksStatuses = function () { ASC.Files.Folders.bulkStatuses = false; ASC.Files.UI.setProgressValue("#tasksProgress", 0); jq("#tasksProgress .<API key>").text("0%"); jq("#tasksProgress .<API key> span").text(""); jq("#tasksProgress").hide(); }; var terminateTasks = function () { clearTimeout(ASC.Files.Folders.tasksTimeout); ASC.Files.ServiceManager.terminateTasks(ASC.Files.ServiceManager.events.TerminateTasks, { isTerminate: true, doNow: true }); }; var getTasksStatuses = function (doNow) { clearTimeout(ASC.Files.Folders.tasksTimeout); ASC.Files.Folders.tasksTimeout = setTimeout( function () { ASC.Files.ServiceManager.getTasksStatuses(ASC.Files.ServiceManager.events.GetTasksStatuses, { doNow: false }); }, ASC.Files.Constants.<API key> / (doNow === true ? 8 : 1)); }; return { eventAfter: eventAfter, currentFolder: currentFolder, folderContainer: folderContainer, isCopyTo: isCopyTo, cancelEnter: cancelEnter, createFolder: createFolder, replaceVersion: replaceVersion, lockFile: lockFile, showVersions: showVersions, closeVersions: closeVersions, <API key>: <API key>, makeCurrentVersion: makeCurrentVersion, enterComment: enterComment, eraseComment: eraseComment, versionComplete: versionComplete, <API key>: <API key>, curItemFolderMoveTo: curItemFolderMoveTo, createDuplicate: createDuplicate, rename: rename, deleteItem: deleteItem, emptyTrash: emptyTrash, getFolderItems: getFolderItems, getItems: getItems, clickOnFolder: clickOnFolder, clickOnFile: clickOnFile, updateIfExist: updateIfExist, showMore: showMore, createNewDoc: createNewDoc, typeNewDoc: typeNewDoc, download: download, bulkDownload: bulkDownload, getTasksStatuses: getTasksStatuses, cancelTasksStatuses: cancelTasksStatuses, terminateTasks: terminateTasks, tasksTimeout: tasksTimeout, bulkStatuses: bulkStatuses, isFirstLoad: isFirstLoad }; })(); (function ($) { $(function () { jq("#pageNavigatorHolder a").click(function () { ASC.Files.Folders.showMore(); return false; }); jq("#topNewFolder a").click(function () { ASC.Files.Folders.createFolder(); }); jq("#buttonDelete, #mainDelete").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.deleteItem(); }); jq("#buttonEmptyTrash, #mainEmptyTrash").click(function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.emptyTrash(); }); jq("#studioPageContent").on("click", "#buttonDownload, #mainDownload.unlockAction", function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.download(); }); jq("#filesSelectAllCheck").click(function () { ASC.Files.UI.checkSelectAll(jq("#filesSelectAllCheck").prop("checked") == true); jq(this).blur(); }); jq("#filesMainContent").on("click", ".file-lock", function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.lockFile(this); return false; }); jq("#filesMainContent").on("click", ".version", function () { ASC.Files.Actions.hideAllActionPanels(); ASC.Files.Folders.showVersions(this); return false; }); jq("#filesMainContent").on("click", ".folder-row:not(.error-entry) .entry-title .name a, .folder-row:not(.error-entry) .thumb-folder", function () { var folderId = ASC.Files.UI.getObjectData(this).id; if (folderId != 0) { ASC.Files.Folders.clickOnFolder(folderId); } return false; }); jq(".to-parent-folder, .<API key>").on("click", function () { var folderId = jq(this).attr("data-id"); ASC.Files.Folders.clickOnFolder(folderId); return false; }); jq("#filesMainContent").on("click", ".file-row:not(.folder-row):not(.error-entry) .entry-title .name a, .file-row:not(.folder-row):not(.error-entry) .thumb-file", function () { ASC.Files.Actions.hideAllActionPanels(); var fileData = ASC.Files.UI.getObjectData(this); if (fileData.id != 0) { var fileObj = fileData.entryObject; ASC.Files.Folders.clickOnFile(fileData); fileObj.removeClass("isNewForWebEditor"); } return false; }); jq("#filesMainContent").on("mouseup", ".file-row:not(.folder-row):not(.error-entry) .entry-title .name a, .file-row:not(.folder-row):not(.error-entry) .thumb-file", function (event) { if (event.which == 2) { var fileData = ASC.Files.UI.getObjectData(this); if (fileData.id != 0) { var fileTitle = fileData.title || ASC.Files.UI.getEntryTitle("file", fileId); if (!ASC.Files.Utility.MustConvert(fileTitle) && (ASC.Files.Utility.CanWebView(fileTitle) || ASC.Files.Utility.CanWebEdit(fileTitle))) { var fileObj = fileData.entryObject; ASC.Files.UI.lockEditFile(fileObj, true); setTimeout(ASC.Files.UI.checkEditing, 5000); ASC.Files.Actions.hideAllActionPanels(); fileObj.removeClass("isNewForWebEditor"); } } } return true; }); jq("#filesMainContent").on("click", "#contentVersions", function () { return false; }); jq("#filesMainContent").on("click", ".version-comment:not(:has(input)):not(:has(.version-comment-fix:empty)), .<API key>", ASC.Files.Folders.enterComment); jq("#filesMainContent").on("click", ".version-complete, .version-continue", function () { var fileId = ASC.Files.UI.getObjectData(this).id; var version = jq(this).closest(".version-row").attr("data-version"); var continueVersion = jq(this).hasClass("version-continue"); ASC.Files.Folders.versionComplete(fileId, version, continueVersion); }); jq("#filesMainContent").on("click", ".version-group-head .version-sublist span", function () { var versionGroup = jq(this).closest(".version-row").attr("data-version-group"); ASC.Files.Folders.<API key>(versionGroup); return false; }); jq("#filesMainContent").on("click", ".version-preview", function () { ASC.Files.Actions.hideAllActionPanels(); var fileData = ASC.Files.UI.getObjectData(this); var version = jq(this).closest(".version-row").attr("data-version"); ASC.Files.Folders.clickOnFile(fileData, false, version); return false; }); jq("#filesMainContent").on("click", ".version-download", function () { var fileId = ASC.Files.UI.getObjectData(this).id; var version = jq(this).closest(".version-row").attr("data-version"); ASC.Files.Folders.download("file", fileId, version); return false; }); jq("#filesMainContent").on("click", ".version-restore span", function () { var fileId = ASC.Files.UI.getObjectData(this).id; var version = jq(this).closest(".version-row").attr("data-version"); ASC.Files.Folders.makeCurrentVersion(fileId, version); return false; }); jq("#filesMainContent").on("click", ".version-comment .name-cancel", ASC.Files.Folders.eraseComment); jq("#filesMainContent").on("click", ".file-row > .rename-action > .name-cancel", ASC.Files.Folders.cancelEnter); jq(".update-if-exist").change(function () { ASC.Files.Folders.updateIfExist(this); }); if (typeof ASC.Files.Share == "undefined") { jq("#<API key>, #filesShareAccess,\ #filesUnsubscribe, #foldersUnsubscribe").remove(); } jq(window).scroll(function () { ASC.Files.UI.stickContentHeader(); if (jq(document).height() - jq(window).height() <= jq(window).scrollTop() + 350) { ASC.Files.Folders.showMore(); } return true; }); ASC.Files.Folders.eventAfter = function () { if (ASC.Files.Folders.isFirstLoad) { ASC.Files.Folders.isFirstLoad = false; if (!jq("#emptyContainer").is(":visible")) { jq('.advansed-filter').advansedFilter("resize"); } } else { LoadingBanner.hideLoading(); } }; if (!ASC.Files.Folders.isFirstLoad) { LoadingBanner.displayLoading(true); } if (jq.browser.msie) { //fix Flash & IE URL hash problem setInterval(function () { ASC.Files.UI.setDocumentTitle(ASC.Files.Folders.currentFolder.title); }, 200); } }); })(jQuery);
import requests import urllib from bountyfunding.core.config import config from bountyfunding.core.models import db, Payment from bountyfunding.core.const import PaymentGateway from bountyfunding.core.errors import Error from bountyfunding.core.payment import get_paypal_url class <API key>: def create_payment(self, project_id, sponsorship, return_url): """ Returns authorization URL """ if not return_url: raise Error('return_url cannot be blank') receiver_email = config[project_id].<API key> args = { "cmd": "_donations", "business": receiver_email, "item_name": "Bounty", "amount": sponsorship.amount, "currency_code": "EUR", "no_note": 1, "no_shipping": 1, "return": return_url, "cancel_return": return_url } redirect_url = get_paypal_url(project_id) + "?" + urllib.urlencode(args) payment = Payment(sponsorship.project_id, sponsorship.sponsorship_id, PaymentGateway.PAYPAL_STANDARD) payment.url = redirect_url return payment def process_payment(self, project_id, sponsorship, payment, details): """ Validates payment """ transaction_id = details["tx"] payload = { "cmd": "_notify-synch", "at": config[project_id].<API key>, "tx": transaction_id } # Check for reused transaction ID if db.session.query(db.exists().where(Payment.gateway_id==transaction_id)).scalar(): return False r = requests.post(get_paypal_url(project_id), data=payload) lines = r.text.strip().splitlines() if len(lines) == 0: return False # Check for SUCCESS word if not lines.pop(0).strip() == "SUCCESS": return False # Payment validation retrieved_payment = {} for line in lines: key, value = line.strip().split('=') retrieved_payment[key] = urllib.unquote_plus(value) receiver_email = config[project_id].<API key> # Check recipient email if retrieved_payment['business'] != receiver_email: return False # Check currency if retrieved_payment['mc_currency'] != "EUR": return False # Check amount if float(retrieved_payment['mc_gross']) != sponsorship.amount: return False # Store transaction ID payment.gateway_id = transaction_id return True
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /** * Base database driver implementation * @api */ abstract class DBManager { /** * Name of database * @var resource */ public $database = null; /** * Indicates whether we should die when we get an error from the DB */ protected $dieOnError = false; /** * Indicates whether we should html encode the results from a query by default */ protected $encode = true; /** * Records the execution time of the last query */ protected $query_time = 0; /** * Last error message from the DB backend */ protected $last_error = false; /** * Registry of available result sets */ protected $lastResult; /** * Current query count */ private static $queryCount = 0; /** * Query threshold limit */ private static $queryLimit = 0; /** * Array of prepared statements and their correspoding parsed tokens */ protected $preparedTokens = array(); /** * TimeDate instance * @var TimeDate */ protected $timedate; /** * PHP Logger * @var Logger */ protected $log; /** * Table descriptions * @var array */ protected static $table_descriptions = array(); /** * Index descriptions * @var array */ protected static $index_descriptions = array(); /** * Maximum length of identifiers * @abstract * @var array */ protected $maxNameLengths = array( 'table' => 64, 'column' => 64, 'index' => 64, 'alias' => 64 ); /** * DB driver priority * Higher priority drivers override lower priority ones * @var int */ public $priority = 0; /** * Driver name label, for install * @absrtact * @var string */ public $label = ''; /** * Type names map * @abstract * @var array */ protected $type_map = array(); /** * Type classification into: * - int * - bool * - float * - date * @abstract * @var array */ protected $type_class = array( 'int' => 'int', 'double' => 'float', 'float' => 'float', 'uint' => 'int', 'ulong' => 'bigint', 'long' => 'bigint', 'short' => 'int', 'date' => 'date', 'datetime' => 'date', 'datetimecombo' => 'date', 'time' => 'time', 'bool' => 'bool', 'tinyint' => 'int', 'currency' => 'float', 'decimal' => 'float', 'decimal2' => 'float', ); /** * Capabilities this DB supports. Supported list: * affected_rows Can report query affected rows for UPDATE/DELETE * implement getAffectedRowCount() * select_rows Can report row count for SELECT * implement getRowCount() * case_sensitive Supports case-sensitive text columns * fulltext Supports fulltext search indexes * inline_keys Supports defining keys together with the table * <API key> Autoincrement support implemented as sequence * limit_subquery Supports LIMIT clauses in subqueries * create_user Can create users for Sugar * create_db Can create databases * collation Supports setting collations * disable_keys Supports temporarily disabling keys (for upgrades, etc.) * * @abstract * Special cases: * fix:expandDatabase - needs expandDatabase fix, see expandDatabase.php * TODO: verify if we need these cases */ protected $capabilities = array(); /** * Database options * @var array */ protected $options = array(); /** * Create DB Driver */ public function __construct() { $this->timedate = TimeDate::getInstance(); $this->log = $GLOBALS['log']; $this->helper = $this; // compatibility } /** * Wrapper for those trying to access the private and protected class members directly * @param string $p var name * @return mixed */ public function __get($p) { $this->log->info('Call to DBManager::$'.$p.' is deprecated'); return $this->$p; } /** * Returns the current database handle * @return resource */ public function getDatabase() { $this->checkConnection(); return $this->database; } /** * Returns this instance's DBHelper * Actually now returns $this * @deprecated * @return DBManager */ public function getHelper() { return $this; } /** * Checks for error happening in the database * * @param string $msg message to prepend to the error message * @param bool $dieOnError true if we want to die immediately on error * @return bool True if there was an error */ public function checkError($msg = '', $dieOnError = false) { if (empty($this->database)) { $this->registerError($msg, "Database Is Not Connected", $dieOnError); return true; } $dberror = $this->lastDbError(); if($dberror === false) { $this->last_error = false; return false; } $this->registerError($msg, $dberror, $dieOnError); return true; } /** * Register database error * If die-on-error flag is set, logs the message and dies, * otherwise sets last_error to the message * @param string $userMessage Message from function user * @param string $message Message from SQL driver * @param bool $dieOnError */ protected function registerError($userMessage, $message, $dieOnError = false) { if(!empty($message)) { if(!empty($userMessage)) { $message = "$userMessage: $message"; } if(empty($message)) { $message = "Database error"; } $this->log->fatal($message); if ($dieOnError || $this->dieOnError) { if(isset($GLOBALS['app_strings']['ERR_DB_FAIL'])) { sugar_die($GLOBALS['app_strings']['ERR_DB_FAIL']); } else { sugar_die("Database error. Please check sugarcrm.log for details."); } } else { $this->last_error = $message; } } } /** * Return DB error message for the last query executed * @return string Last error message */ public function lastError() { return $this->last_error; } /** * This method is called by every method that runs a query. * If slow query dumping is turned on and the query time is beyond * the time limit, we will log the query. This function may do * additional reporting or log in a different area in the future. * * @param string $query query to log * @return boolean true if the query was logged, false otherwise */ protected function dump_slow_queries($query) { global $sugar_config; $do_the_dump = isset($sugar_config['dump_slow_queries']) ? $sugar_config['dump_slow_queries'] : false; $<API key> = isset($sugar_config['<API key>']) ? $sugar_config['<API key>'] : 5000; if($do_the_dump) { if($<API key> < ($this->query_time * 1000)) { // Then log both the query and the query time $this->log->fatal('Slow Query (time:'.$this->query_time."\n".$query); return true; } } return false; } /** * Scans order by to ensure that any field being ordered by is. * * It will throw a warning error to the log file - fatal if slow query logging is enabled * * @param string $sql query to be run * @param bool $object_name optional, object to look up indices in * @return bool true if an index is found false otherwise */ protected function checkQuery($sql, $object_name = false) { $match = array(); preg_match_all("'.* FROM ([^ ]*).* ORDER BY (.*)'is", $sql, $match); $indices = false; if (!empty($match[1][0])) $table = $match[1][0]; else return false; if (!empty($object_name) && !empty($GLOBALS['dictionary'][$object_name])) $indices = $GLOBALS['dictionary'][$object_name]['indices']; if (empty($indices)) { foreach ( $GLOBALS['dictionary'] as $current ) { if ($current['table'] == $table){ $indices = $current['indices']; break; } } } if (empty($indices)) { $this->log->warn('CHECK QUERY: Could not find index definitions for table ' . $table); return false; } if (!empty($match[2][0])) { $orderBys = explode(' ', $match[2][0]); foreach ($orderBys as $orderBy){ $orderBy = trim($orderBy); if (empty($orderBy)) continue; $orderBy = strtolower($orderBy); if ($orderBy == 'asc' || $orderBy == 'desc') continue; $orderBy = str_replace(array($table . '.', ','), '', $orderBy); foreach ($indices as $index) if (empty($index['db']) || $index['db'] == $this->dbType) foreach ($index['fields'] as $field) if ($field == $orderBy) return true; $warning = 'Missing Index For Order By Table: ' . $table . ' Order By:' . $orderBy ; if (!empty($GLOBALS['sugar_config']['dump_slow_queries'])) $this->log->fatal('CHECK QUERY:' .$warning); else $this->log->warn('CHECK QUERY:' .$warning); } } return false; } /** * Returns the time the last query took to execute * * @return int */ public function getQueryTime() { return $this->query_time; } /** * Checks the current connection; if it is not connected then reconnect */ public function checkConnection() { $this->last_error = ''; if (!isset($this->database)) $this->connect(); } /** * Sets the dieOnError value * * @param bool $value */ public function setDieOnError($value) { $this->dieOnError = $value; } /** * Implements a generic insert for any bean. * * @param SugarBean $bean SugarBean instance * @return bool query result * */ public function insert(SugarBean $bean) { $sql = $this->insertSQL($bean); $tablename = $bean->getTableName(); $msg = "Error inserting into table: $tablename:"; return $this->query($sql,true,$msg); } /** * Insert data into table by parameter definition * @param string $table Table name * @param array $field_defs Definitions in vardef-like format * @param array $data Key/value to insert * @param array $field_map Fields map from SugarBean * @param bool $execute Execute or return query? * @return bool query result */ public function insertParams($table, $field_defs, $data, $field_map = null, $execute = true) { $values = array(); foreach ($field_defs as $field => $fieldDef) { if (isset($fieldDef['source']) && $fieldDef['source'] != 'db') continue; //custom fields handle there save seperatley if(!empty($field_map) && !empty($field_map[$field]['custom_type'])) continue; if(isset($data[$field])) { // clean the incoming value.. $val = from_html($data[$field]); } else { if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) { $val = $fieldDef['default']; } else { $val = null; } } //handle auto increment values here - we may have to do something like nextval for oracle if (!empty($fieldDef['auto_increment'])) { $auto = $this->getAutoIncrementSQL($table, $fieldDef['name']); if(!empty($auto)) { $values[$field] = $auto; } } elseif ($fieldDef['name'] == 'deleted') { $values['deleted'] = (int)$val; } else { // need to do some thing about types of values if(!is_null($val) || !empty($fieldDef['required'])) { $values[$field] = $this->massageValue($val, $fieldDef); } } } if (empty($values)) return $execute?true:''; // no columns set // get the entire sql $query = "INSERT INTO $table (".implode(",", array_keys($values)).") VALUES (".implode(",", $values).")"; return $execute?$this->query($query):$query; } /** * Implements a generic update for any bean * * @param SugarBean $bean Sugarbean instance * @param array $where values with the keys as names of fields. * If we want to pass multiple values for a name, pass it as an array * If where is not passed, it defaults to id of table * @return bool query result * */ public function update(SugarBean $bean, array $where = array()) { $sql = $this->updateSQL($bean, $where); $tablename = $bean->getTableName(); $msg = "Error updating table: $tablename:"; return $this->query($sql,true,$msg); } /** * Implements a generic delete for any bean identified by id * * @param SugarBean $bean Sugarbean instance * @param array $where values with the keys as names of fields. * If we want to pass multiple values for a name, pass it as an array * If where is not passed, it defaults to id of table * @return bool query result */ public function delete(SugarBean $bean, array $where = array()) { $sql = $this->deleteSQL($bean, $where); $tableName = $bean->getTableName(); $msg = "Error deleting from table: ".$tableName. ":"; return $this->query($sql,true,$msg); } /** * Implements a generic retrieve for any bean identified by id * * If we want to pass multiple values for a name, pass it as an array * If where is not passed, it defaults to id of table * * @param SugarBean $bean Sugarbean instance * @param array $where values with the keys as names of fields. * @return resource result from the query */ public function retrieve(SugarBean $bean, array $where = array()) { $sql = $this->retrieveSQL($bean, $where); $tableName = $bean->getTableName(); $msg = "Error retriving values from table:".$tableName. ":"; return $this->query($sql,true,$msg); } /** * Implements a generic retrieve for a collection of beans. * * These beans will be joined in the sql by the key attribute of field defs. * Currently, this function does support outer joins. * * @param array $beans Sugarbean instance(s) * @param array $cols columns to be returned with the keys as names of bean as identified by * get_class of bean. Values of this array is the array of fieldDefs to be returned for a bean. * If an empty array is passed, all columns are selected. * @param array $where values with the keys as names of bean as identified by get_class of bean * Each value at the first level is an array of values for that bean identified by name of fields. * If we want to pass multiple values for a name, pass it as an array * If where is not passed, all the rows will be returned. * @return resource */ public function retrieveView(array $beans, array $cols = array(), array $where = array()) { $sql = $this->retrieveViewSQL($beans, $cols, $where); $msg = "Error retriving values from View Collection:"; return $this->query($sql,true,$msg); } /** * Implements creation of a db table for a bean. * * NOTE: does not handle out-of-table constraints, use createConstraintSQL for that * @param SugarBean $bean Sugarbean instance */ public function createTable(SugarBean $bean) { $sql = $this->createTableSQL($bean); $tablename = $bean->getTableName(); $msg = "Error creating table: $tablename:"; $this->query($sql,true,$msg); if(!$this->supports("inline_keys")) { // handle constraints and indices $indicesArr = $this->createConstraintSql($bean); if (count($indicesArr) > 0) foreach ($indicesArr as $indexSql) $this->query($indexSql, true, $msg); } } /** * returns SQL to create constraints or indices * * @param SugarBean $bean SugarBean instance * @return array list of SQL statements */ protected function createConstraintSql(SugarBean $bean) { return $this->getConstraintSql($bean->getIndices(), $bean->getTableName()); } /** * Implements creation of a db table * * @param string $tablename * @param array $fieldDefs Field definitions, in vardef format * @param array $indices Index definitions, in vardef format * @param string $engine Engine parameter, used for MySQL engine so far * @todo: refactor engine param to be more generic * @return bool success value */ public function createTableParams($tablename, $fieldDefs, $indices, $engine = null) { if (!empty($fieldDefs)) { $sql = $this-><API key>($tablename, $fieldDefs, $indices, $engine); $res = true; if ($sql) { $msg = "Error creating table: $tablename"; $res = ($res and $this->query($sql,true,$msg)); } if(!$this->supports("inline_keys")) { // handle constraints and indices $indicesArr = $this->getConstraintSql($indices, $tablename); if (count($indicesArr) > 0) foreach ($indicesArr as $indexSql) $res = ($res and $this->query($indexSql, true, "Error creating indexes")); } return $res; } return false; } /** * Implements repair of a db table for a bean. * * @param SugarBean $bean SugarBean instance * @param bool $execute true if we want the action to take place, false if we just want the sql returned * @return string SQL statement or empty string, depending upon $execute */ public function repairTable(SugarBean $bean, $execute = true) { $indices = $bean->getIndices(); $fielddefs = $bean->getFieldDefinitions(); $tablename = $bean->getTableName(); //Clean the indexes to prevent duplicate definitions $new_index = array(); foreach($indices as $ind_def){ $new_index[$ind_def['name']] = $ind_def; } //jc: added this for beans that do not actually have a table, namely //<API key> if($tablename == 'does_not_exist' || $tablename == '') return ''; global $dictionary; $engine=null; if (isset($dictionary[$bean->getObjectName()]['engine']) && !empty($dictionary[$bean->getObjectName()]['engine']) ) $engine = $dictionary[$bean->getObjectName()]['engine']; return $this->repairTableParams($tablename, $fielddefs,$new_index,$execute,$engine); } /** * Can this field be null? * Auto-increment and ID fields can not be null * @param array $vardef * @return bool */ protected function isNullable($vardef) { if(isset($vardef['isnull']) && (strtolower($vardef['isnull']) == 'false' || $vardef['isnull'] === false) && !empty($vardef['required'])) { /* required + is_null=false => not null */ return false; } if(empty($vardef['auto_increment']) && (empty($vardef['type']) || $vardef['type'] != 'id') && (empty($vardef['dbType']) || $vardef['dbType'] != 'id') && (empty($vardef['name']) || ($vardef['name'] != 'id' && $vardef['name'] != 'deleted')) ) { return true; } return false; } /** * Builds the SQL commands that repair a table structure * * @param string $tablename * @param array $fielddefs Field definitions, in vardef format * @param array $indices Index definitions, in vardef format * @param bool $execute optional, true if we want the queries executed instead of returned * @param string $engine optional, MySQL engine * @todo: refactor engine param to be more generic * @return string */ public function repairTableParams($tablename, $fielddefs, $indices, $execute = true, $engine = null) { //jc: had a bug when running the repair if the tablename is blank the repair will //fail when it tries to create a repair table if ($tablename == '' || empty($fielddefs)) return ''; //if the table does not exist create it and we are done $sql = "/* Table : $tablename */\n"; if (!$this->tableExists($tablename)) { $createtablesql = $this-><API key>($tablename,$fielddefs,$indices,$engine); if($execute && $createtablesql){ $this->createTableParams($tablename,$fielddefs,$indices,$engine); } $sql .= "/* MISSING TABLE: {$tablename} */\n"; $sql .= $createtablesql . "\n"; return $sql; } $compareFieldDefs = $this->get_columns($tablename); $compareIndices = $this->get_indices($tablename); $take_action = false; // do column comparisons $sql .= "/*COLUMNS*/\n"; foreach ($fielddefs as $name => $value) { if (isset($value['source']) && $value['source'] != 'db') continue; // Bug #42406. Skipping breaked vardef without type or name if (isset($value['name']) == false || $value['name'] == false) { $sql .= "/* NAME IS MISSING IN VARDEF $tablename::$name */\n"; continue; } else if (isset($value['type']) == false || $value['type'] == false) { $sql .= "/* TYPE IS MISSING IN VARDEF $tablename::$name */\n"; continue; } $name = strtolower($value['name']); // add or fix the field defs per what the DB is expected to give us back $this->massageFieldDef($value,$tablename); $ignorerequired=false; //Do not track requiredness in the DB, auto_increment, ID, // and deleted fields are always required in the DB, so don't force those if ($this->isNullable($value)) { $value['required'] = false; } //Should match the conditions in DBManager::oneColumnSQLRep for DB required fields, type='id' fields will sometimes //come into this function as 'type' = 'char', 'dbType' = 'id' without required set in $value. Assume they are correct and leave them alone. else if (($name == 'id' || $value['type'] == 'id' || (isset($value['dbType']) && $value['dbType'] == 'id')) && (!isset($value['required']) && isset($compareFieldDefs[$name]['required']))) { $value['required'] = $compareFieldDefs[$name]['required']; } if ( !isset($compareFieldDefs[$name]) ) { // ok we need this field lets create it $sql .= "/*MISSING IN DATABASE - $name - ROW*/\n"; $sql .= $this->addColumnSQL($tablename, $value) . "\n"; if ($execute) $this->addColumn($tablename, $value); $take_action = true; } elseif ( !$this->compareVarDefs($compareFieldDefs[$name],$value)) { //fields are different lets alter it $sql .= "/*MISMATCH WITH DATABASE - $name - ROW "; foreach($compareFieldDefs[$name] as $rKey => $rValue) { $sql .= "[$rKey] => '$rValue' "; } $sql .= "*/\n"; $sql .= "/* VARDEF - $name - ROW"; foreach($value as $rKey => $rValue) { $sql .= "[$rKey] => '$rValue' "; } $sql .= "*/\n"; //jc: oracle will complain if you try to execute a statement that sets a column to (not) null //when it is already (not) null if ( isset($value['isnull']) && isset($compareFieldDefs[$name]['isnull']) && $value['isnull'] === $compareFieldDefs[$name]['isnull']) { unset($value['required']); $ignorerequired=true; } //dwheeler: Once a column has been defined as null, we cannot try to force it back to !null if ((isset($value['required']) && ($value['required'] === true || $value['required'] == 'true' || $value['required'] === 1)) && (empty($compareFieldDefs[$name]['required']) || $compareFieldDefs[$name]['required'] != 'true')) { $ignorerequired = true; } $altersql = $this->alterColumnSQL($tablename, $value,$ignorerequired); if(is_array($altersql)) { $altersql = join("\n", $altersql); } $sql .= $altersql . "\n"; if($execute){ $this->alterColumn($tablename, $value, $ignorerequired); } $take_action = true; } } // do index comparisons $sql .= "/* INDEXES */\n"; $correctedIndexs = array(); $<API key> = array(); // do indices comparisons case-insensitive foreach($compareIndices as $k => $value){ $value['name'] = strtolower($value['name']); $<API key>[strtolower($k)] = $value; } $compareIndices = $<API key>; unset($<API key>); foreach ($indices as $value) { if (isset($value['source']) && $value['source'] != 'db') continue; $validDBName = $this->getValidDBName($value['name'], true, 'index', true); if (isset($compareIndices[$validDBName])) { $value['name'] = $validDBName; } $name = strtolower($value['name']); //Don't attempt to fix the same index twice in one pass; if (isset($correctedIndexs[$name])) continue; //don't bother checking primary nothing we can do about them if (isset($value['type']) && $value['type'] == 'primary') continue; //database helpers do not know how to handle full text indices if ($value['type']=='fulltext') continue; if ( in_array($value['type'],array('alternate_key','foreign')) ) $value['type'] = 'index'; if ( !isset($compareIndices[$name]) ) { //First check if an index exists that doesn't match our name, if so, try to rename it $found = false; foreach ($compareIndices as $ex_name => $ex_value) { if($this->compareVarDefs($ex_value, $value, true)) { $found = $ex_name; break; } } if ($found) { $sql .= "/*MISSNAMED INDEX IN DATABASE - $name - $ex_name */\n"; $rename = $this->renameIndexDefs($ex_value, $value, $tablename); if($execute) { $this->query($rename, true, "Cannot rename index"); } $sql .= is_array($rename)?join("\n", $rename). "\n":$rename."\n"; } else { // ok we need this field lets create it $sql .= "/*MISSING INDEX IN DATABASE - $name -{$value['type']} ROW */\n"; $sql .= $this->addIndexes($tablename,array($value), $execute) . "\n"; } $take_action = true; $correctedIndexs[$name] = true; } elseif ( !$this->compareVarDefs($compareIndices[$name],$value) ) { // fields are different lets alter it $sql .= "/*INDEX MISMATCH WITH DATABASE - $name - ROW "; foreach ($compareIndices[$name] as $n1 => $t1) { $sql .= "<$n1>"; if ( $n1 == 'fields' ) foreach($t1 as $rKey => $rValue) $sql .= "[$rKey] => '$rValue' "; else $sql .= " $t1 "; } $sql .= "*/\n"; $sql .= "/* VARDEF - $name - ROW"; foreach ($value as $n1 => $t1) { $sql .= "<$n1>"; if ( $n1 == 'fields' ) foreach ($t1 as $rKey => $rValue) $sql .= "[$rKey] => '$rValue' "; else $sql .= " $t1 "; } $sql .= "*/\n"; $sql .= $this->modifyIndexes($tablename,array($value), $execute) . "\n"; $take_action = true; $correctedIndexs[$name] = true; } } return ($take_action === true) ? $sql : ''; } /** * Compares two vardefs * * @param array $fielddef1 This is from the database * @param array $fielddef2 This is from the vardef * @param bool $ignoreName Ignore name-only differences? * @return bool true if they match, false if they don't */ public function compareVarDefs($fielddef1, $fielddef2, $ignoreName = false) { foreach ( $fielddef1 as $key => $value ) { if ( $key == 'name' && ( strtolower($fielddef1[$key]) == strtolower($fielddef2[$key]) || $ignoreName) ) continue; if ( isset($fielddef2[$key]) && $fielddef1[$key] == $fielddef2[$key] ) continue; //Ignore len if its not set in the vardef if ($key == 'len' && empty($fielddef2[$key])) continue; // if the length in db is greather than the vardef, ignore it if ($key == 'len' && ($fielddef1[$key] >= $fielddef2[$key])) { continue; } return false; } return true; } /** * Compare a field in two tables * @deprecated * @param string $name field name * @param string $table1 * @param string $table2 * @return array array with keys 'msg','table1','table2' */ public function <API key>($name, $table1, $table2) { $row1 = $this->describeField($name, $table1); $row2 = $this->describeField($name, $table2); $returnArray = array( 'table1' => $row1, 'table2' => $row2, 'msg' => 'error', ); $ignore_filter = array('Key'=>1); if ($row1) { if (!$row2) { // Exists on table1 but not table2 $returnArray['msg'] = 'not_exists_table2'; } else { if (sizeof($row1) != sizeof($row2)) { $returnArray['msg'] = 'no_match'; } else { $returnArray['msg'] = 'match'; foreach($row1 as $key => $value){ //ignore keys when checking we will check them when we do the index check if( !isset($ignore_filter[$key]) && (!isset($row2[$key]) || $row1[$key] !== $row2[$key])){ $returnArray['msg'] = 'no_match'; } } } } } else { $returnArray['msg'] = 'not_exists_table1'; } return $returnArray; } // /** // * Compare an index in two different tables // * @deprecated // * @param string $name index name // * @param string $table1 // * @param string $table2 // * @return array array with keys 'msg','table1','table2' // */ // public function <API key>($name, $table1, $table2) // $row1 = $this->describeIndex($name, $table1); // $row2 = $this->describeIndex($name, $table2); // $returnArray = array( // 'table1' => $row1, // 'table2' => $row2, // 'msg' => 'error', // $ignore_filter = array('Table'=>1, 'Seq_in_index'=>1,'Cardinality'=>1, 'Sub_part'=>1, 'Packed'=>1, 'Comment'=>1); // if ($row1) { // if (!$row2) { // //Exists on table1 but not table2 // $returnArray['msg'] = 'not_exists_table2'; // else { // if (sizeof($row1) != sizeof($row2)) { // $returnArray['msg'] = 'no_match'; // else { // $returnArray['msg'] = 'match'; // foreach ($row1 as $fname => $fvalue) { // if (!isset($row2[$fname])) { // $returnArray['msg'] = 'no_match'; // if(!isset($ignore_filter[$fname]) && $row1[$fname] != $row2[$fname]){ // $returnArray['msg'] = 'no_match'; // } else { // $returnArray['msg'] = 'not_exists_table1'; // return $returnArray; /** * Creates an index identified by name on the given fields. * * @param SugarBean $bean SugarBean instance * @param array $fieldDefs Field definitions, in vardef format * @param string $name index name * @param bool $unique optional, true if we want to create an unique index * @return bool query result */ public function createIndex(SugarBean $bean, $fieldDefs, $name, $unique = true) { $sql = $this->createIndexSQL($bean, $fieldDefs, $name, $unique); $tablename = $bean->getTableName(); $msg = "Error creating index $name on table: $tablename:"; return $this->query($sql,true,$msg); } /** * returns a SQL query that creates the indices as defined in metadata * @param array $indices Assoc array with index definitions from vardefs * @param string $table Focus table * @return array Array of SQL queries to generate indices */ public function getConstraintSql($indices, $table) { if (!$this->isFieldArray($indices)) $indices = array($indices); $columns = array(); foreach ($indices as $index) { if(!empty($index['db']) && $index['db'] != $this->dbType) continue; if (isset($index['source']) && $index['source'] != 'db') continue; $sql = $this->add_drop_constraint($table, $index); if(!empty($sql)) { $columns[] = $sql; } } return $columns; } /** * Adds a new indexes * * @param string $tablename * @param array $indexes indexes to add * @param bool $execute true if we want to execute the returned sql statement * @return string SQL statement */ public function addIndexes($tablename, $indexes, $execute = true) { $alters = $this->getConstraintSql($indexes, $tablename); if ($execute) { foreach($alters as $sql) { $this->query($sql, true, "Error adding index: "); } } if(!empty($alters)) { $sql = join(";\n", $alters).";\n"; } else { $sql = ''; } return $sql; } /** * Drops indexes * * @param string $tablename * @param array $indexes indexes to drop * @param bool $execute true if we want to execute the returned sql statement * @return string SQL statement */ public function dropIndexes($tablename, $indexes, $execute = true) { $sqls = array(); foreach ($indexes as $index) { $name =$index['name']; $sqls[$name] = $this->add_drop_constraint($tablename,$index,true); } if (!empty($sqls) && $execute) { foreach($sqls as $name => $sql) { unset(self::$index_descriptions[$tablename][$name]); $this->query($sql); } } if(!empty($sqls)) { return join(";\n",$sqls).";"; } else { return ''; } } /** * Modifies indexes * * @param string $tablename * @param array $indexes indexes to modify * @param bool $execute true if we want to execute the returned sql statement * @return string SQL statement */ public function modifyIndexes($tablename, $indexes, $execute = true) { return $this->dropIndexes($tablename, $indexes, $execute)."\n". $this->addIndexes($tablename, $indexes, $execute); } /** * Adds a column to table identified by field def. * * @param string $tablename * @param array $fieldDefs * @return bool query result */ public function addColumn($tablename, $fieldDefs) { $sql = $this->addColumnSQL($tablename, $fieldDefs); if ($this->isFieldArray($fieldDefs)){ $columns = array(); foreach ($fieldDefs as $fieldDef) $columns[] = $fieldDef['name']; $columns = implode(",", $columns); } else { $columns = $fieldDefs['name']; } $msg = "Error adding column(s) $columns on table: $tablename:"; return $this->query($sql,true,$msg); } /** * Alters old column identified by oldFieldDef to new fieldDef. * * @param string $tablename * @param array $newFieldDef * @param bool $ignoreRequired optional, true if we are ignoring this being a required field * @return bool query result */ public function alterColumn($tablename, $newFieldDef, $ignoreRequired = false) { $sql = $this->alterColumnSQL($tablename, $newFieldDef,$ignoreRequired); if ($this->isFieldArray($newFieldDef)){ $columns = array(); foreach ($newFieldDef as $fieldDef) { $columns[] = $fieldDef['name']; } $columns = implode(",", $columns); } else { $columns = $newFieldDef['name']; } $msg = "Error altering column(s) $columns on table: $tablename:"; $res = $this->query($sql,true,$msg); if($res) { $this->getTableDescription($tablename, true); // reload table description after altering } return $res; } /** * Drops the table associated with a bean * * @param SugarBean $bean SugarBean instance * @return bool query result */ public function dropTable(SugarBean $bean) { return $this->dropTableName($bean->getTableName()); } /** * Drops the table by name * * @param string $name Table name * @return bool query result */ public function dropTableName($name) { $sql = $this->dropTableNameSQL($name); return $this->query($sql,true,"Error dropping table $name:"); } /** * Deletes a column identified by fieldDef. * * @param SugarBean $bean SugarBean containing the field * @param array $fieldDefs Vardef definition of the field * @return bool query result */ public function deleteColumn(SugarBean $bean, $fieldDefs) { $tablename = $bean->getTableName(); $sql = $this->dropColumnSQL($tablename, $fieldDefs); $msg = "Error deleting column(s) on table: $tablename:"; return $this->query($sql,true,$msg); } /** * Generate a set of Insert statements based on the bean given * * @deprecated * * @param SugarBean $bean the bean from which table we will generate insert stmts * @param string $select_query the query which will give us the set of objects we want to place into our insert statement * @param int $start the first row to query * @param int $count the number of rows to query * @param string $table the table to query from * @param bool $is_related_query * @return string SQL insert statement */ public function generateInsertSQL(SugarBean $bean, $select_query, $start, $count = -1, $table, $is_related_query = false) { $this->log->info('call to DBManager::generateInsertSQL() is deprecated'); global $sugar_config; $rows_found = 0; $count_query = $bean-><API key>($select_query); if(!empty($count_query)) { // We have a count query. Run it and get the results. $result = $this->query($count_query, true, "Error running count query for $this->object_name List: "); $assoc = $this->fetchByAssoc($result); if(!empty($assoc['c'])) { $rows_found = $assoc['c']; } } if($count == -1){ $count = $sugar_config['<API key>']; } $next_offset = $start + $count; $result = $this->limitQuery($select_query, $start, $count); // get basic insert $sql = "INSERT INTO ".$table; $custom_sql = "INSERT INTO ".$table."_cstm"; // get field definitions $fields = $bean->getFieldDefinitions(); $custom_fields = array(); if($bean->hasCustomFields()){ foreach ($fields as $fieldDef){ if($fieldDef['source'] == 'custom_fields'){ $custom_fields[$fieldDef['name']] = $fieldDef['name']; } } if(!empty($custom_fields)){ $custom_fields['id_c'] = 'id_c'; $id_field = array('name' => 'id_c', 'custom_type' => 'id',); $fields[] = $id_field; } } // get column names and values $row_array = array(); $columns = array(); $cstm_row_array = array(); $cstm_columns = array(); $built_columns = false; while(($row = $this->fetchByAssoc($result)) != null) { $values = array(); $cstm_values = array(); if(!$is_related_query){ foreach ($fields as $fieldDef) { if(isset($fieldDef['source']) && $fieldDef['source'] != 'db' && $fieldDef['source'] != 'custom_fields') continue; $val = $row[$fieldDef['name']]; //handle auto increment values here only need to do this on insert not create if ($fieldDef['name'] == 'deleted'){ $values['deleted'] = $val; if(!$built_columns){ $columns[] = 'deleted'; } } else { $type = $fieldDef['type']; if(!empty($fieldDef['custom_type'])){ $type = $fieldDef['custom_type']; } // need to do some thing about types of values if($this->dbType == 'mysql' && $val == '' && ($type == 'datetime' || $type == 'date' || $type == 'int' || $type == 'currency' || $type == 'decimal')){ if(!empty($custom_fields[$fieldDef['name']])) $cstm_values[$fieldDef['name']] = 'null'; else $values[$fieldDef['name']] = 'null'; }else{ if(isset($type) && $type=='int') { if(!empty($custom_fields[$fieldDef['name']])) $cstm_values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val)); else $values[$fieldDef['name']] = $GLOBALS['db']->quote(from_html($val)); } else { if(!empty($custom_fields[$fieldDef['name']])) $cstm_values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'"; else $values[$fieldDef['name']] = "'".$GLOBALS['db']->quote(from_html($val))."'"; } } if(!$built_columns){ if(!empty($custom_fields[$fieldDef['name']])) $cstm_columns[] = $fieldDef['name']; else $columns[] = $fieldDef['name']; } } } } else { foreach ($row as $key=>$val) { if($key != 'orc_row'){ $values[$key] = "'$val'"; if(!$built_columns){ $columns[] = $key; } } } } $built_columns = true; if(!empty($values)){ $row_array[] = $values; } if(!empty($cstm_values) && !empty($cstm_values['id_c']) && (strlen($cstm_values['id_c']) > 7)){ $cstm_row_array[] = $cstm_values; } } //if (sizeof ($values) == 0) return ""; // no columns set // get the entire sql $sql .= "(".implode(",", $columns).") "; $sql .= "VALUES"; for($i = 0; $i < count($row_array); $i++){ $sql .= " (".implode(",", $row_array[$i]).")"; if($i < (count($row_array) - 1)){ $sql .= ", "; } } //custom // get the entire sql $custom_sql .= "(".implode(",", $cstm_columns).") "; $custom_sql .= "VALUES"; for($i = 0; $i < count($cstm_row_array); $i++){ $custom_sql .= " (".implode(",", $cstm_row_array[$i]).")"; if($i < (count($cstm_row_array) - 1)){ $custom_sql .= ", "; } } return array('data' => $sql, 'cstm_sql' => $custom_sql, /*'result_count' => $row_count, */ 'total_count' => $rows_found, 'next_offset' => $next_offset); } /** * @deprecated * Disconnects all instances */ public function disconnectAll() { DBManagerFactory::disconnectAll(); } /** * This function sets the query threshold limit * * @param int $limit value of query threshold limit */ public static function setQueryLimit($limit) { //reset the queryCount self::$queryCount = 0; self::$queryLimit = $limit; } /** * Returns the static queryCount value * * @return int value of the queryCount static variable */ public static function getQueryCount() { return self::$queryCount; } /** * Resets the queryCount value to 0 * */ public static function resetQueryCount() { self::$queryCount = 0; } /** * This function increments the global $sql_queries variable */ public function countQuery() { if (self::$queryLimit != 0 && ++self::$queryCount > self::$queryLimit &&(empty($GLOBALS['current_user']) || !is_admin($GLOBALS['current_user']))) { require_once('include/resource/ResourceManager.php'); $resourceManager = ResourceManager::getInstance(); $resourceManager->notifyObservers('ERR_QUERY_LIMIT'); } } /** * Pre-process string for quoting * @internal * @param string $string * @return string */ protected function quoteInternal($string) { return from_html($string); } /** * Return string properly quoted with '' * @param string $string * @return string */ public function quoted($string) { return "'".$this->quote($string)."'"; } /** * Quote value according to type * Numerics aren't quoted * Dates are converted and quoted * Rest is just quoted * @param string $type * @param string $value * @return string Quoted value */ public function quoteType($type, $value) { if($type == 'date') { return $this->convert($this->quoted($value), "date"); } if($type == 'time') { return $this->convert($this->quoted($value), "time"); } if(isset($this->type_class[$type]) && $this->type_class[$type] == "date") { return $this->convert($this->quoted($value), "datetime"); } if($this->isNumericType($type)) { return 0+$value; // ensure it's numeric } return $this->quoted($value); } /** * Quote the strings of the passed in array * * The array must only contain strings * * @param array $array * @return array Quoted strings */ public function arrayQuote(array &$array) { foreach($array as &$val) { $val = $this->quote($val); } return $array; } /** * Frees out previous results * * @param resource|bool $result optional, pass if you want to free a single result instead of all results */ protected function freeResult($result = false) { if($result) { $this->freeDbResult($result); } if($this->lastResult) { $this->freeDbResult($this->lastResult); $this->lastResult = null; } } /** * @abstract * Check if query has LIMIT clause * Relevant for now only for Mysql * @param string $sql * @return bool */ protected function hasLimit($sql) { return false; } /** * Runs a query and returns a single row containing single value * * @param string $sql SQL Statement to execute * @param bool $dieOnError True if we want to call die if the query returns errors * @param string $msg Message to log if error occurs * @return array single value from the query */ public function getOne($sql, $dieOnError = false, $msg = '') { $this->log->info("Get One: |$sql|"); if(!$this->hasLimit($sql)) { $queryresult = $this->limitQuery($sql, 0, 1, $dieOnError, $msg); } else { // support old code that passes LIMIT to sql // works only for mysql, so do not rely on this $queryresult = $this->query($sql, $dieOnError, $msg); } $this->checkError($msg.' Get One Failed:' . $sql, $dieOnError); if (!$queryresult) return false; $row = $this->fetchByAssoc($queryresult); if(!empty($row)) { return array_shift($row); } return false; } /** * Runs a query and returns a single row * * @param string $sql SQL Statement to execute * @param bool $dieOnError True if we want to call die if the query returns errors * @param string $msg Message to log if error occurs * @param bool $suppress Message to log if error occurs * @return array single row from the query */ public function fetchOne($sql, $dieOnError = false, $msg = '', $suppress = false) { $this->log->info("Fetch One: |$sql|"); $this->checkConnection(); $queryresult = $this->query($sql, $dieOnError, $msg); $this->checkError($msg.' Fetch One Failed:' . $sql, $dieOnError); if (!$queryresult) return false; $row = $this->fetchByAssoc($queryresult); if ( !$row ) return false; $this->freeResult($queryresult); return $row; } /** * Returns the number of rows affected by the last query * @abstract * See also affected_rows capability, will return 0 unless the DB supports it * @param resource $result query result resource * @return int */ public function getAffectedRowCount($result) { return 0; } /** * Returns the number of rows returned by the result * * This function can't be reliably implemented on most DB, do not use it. * @abstract * @deprecated * @param resource $result * @return int */ public function getRowCount($result) { return 0; } /** * Get table description * @param string $tablename * @param bool $reload true means load from DB, false allows using cache * @return array Vardef-format table description * */ public function getTableDescription($tablename, $reload = false) { if($reload || empty(self::$table_descriptions[$tablename])) { self::$table_descriptions[$tablename] = $this->get_columns($tablename); } return self::$table_descriptions[$tablename]; } /** * Returns the field description for a given field in table * * @param string $name * @param string $tablename * @return array */ protected function describeField($name, $tablename) { $table = $this->getTableDescription($tablename); if(!empty($table) && isset($table[$name])) return $table[$name]; $table = $this->getTableDescription($tablename, true); if(isset($table[$name])) return $table[$name]; return array(); } /** * Returns the index description for a given index in table * * @param string $name * @param string $tablename * @return array */ protected function describeIndex($name, $tablename) { if(isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename]) && isset(self::$index_descriptions[$tablename][$name])){ return self::$index_descriptions[$tablename][$name]; } self::$index_descriptions[$tablename] = $this->get_indices($tablename); if(isset(self::$index_descriptions[$tablename][$name])){ return self::$index_descriptions[$tablename][$name]; } return array(); } /** * Truncates a string to a given length * * @param string $string * @param int $len length to trim to * @return string * */ public function truncate($string, $len) { if ( is_numeric($len) && $len > 0) { $string = mb_substr($string,0,(int) $len, "UTF-8"); } return $string; } /** * Returns the database string needed for concatinating multiple database strings together * * @param string $table table name of the database fields to concat * @param array $fields fields in the table to concat together * @param string $space Separator between strings, default is single space * @return string */ public function concat($table, array $fields, $space = ' ') { if(empty($fields)) return ''; $elems = array(); $space = $this->quoted($space); foreach ( $fields as $field ) { if(!empty($elems)) $elems[] = $space; $elems[] = $this->convert("$table.$field", 'IFNULL', array("''")); } $first = array_shift($elems); return "LTRIM(RTRIM(".$this->convert($first, 'CONCAT', $elems)."))"; } /** * Given a sql stmt attempt to parse it into the sql and the tokens. Then return the index of this prepared statement * Tokens can come in the following forms: * ? - a scalar which will be quoted * ! - a literal which will not be quoted * & - binary data to read from a file * * @param string $sql The sql to parse * @return int index of the prepared statement to be used with execute */ public function prepareQuery($sql) { //parse out the tokens $tokens = preg_split('/((?<!\\\)[&?!])/', $sql, -1, <API key>); //maintain a count of the actual tokens for quick reference in execute $count = 0; $sqlStr = ''; foreach ($tokens as $key => $val) { switch ($val) { case '?' : case '!' : case '&' : $count++; $sqlStr .= '?'; break; default : //escape any special characters $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val); $sqlStr .= $tokens[$key]; break; } // switch } // foreach $this->preparedTokens[] = array('tokens' => $tokens, 'tokenCount' => $count, 'sqlString' => $sqlStr); end($this->preparedTokens); return key($this->preparedTokens); } /** * Takes a prepared stmt index and the data to replace and creates the query and runs it. * * @param int $stmt The index of the prepared statement from preparedTokens * @param array $data The array of data to replace the tokens with. * @return resource result set or false on error */ public function <API key>($stmt, $data = array()) { if(!empty($this->preparedTokens[$stmt])){ if(!is_array($data)){ $data = array($data); } $pTokens = $this->preparedTokens[$stmt]; //ensure that the number of data elements matches the number of replacement tokens //we found in prepare(). if(count($data) != $pTokens['tokenCount']){ //error the data count did not match the token count return false; } $query = ''; $dataIndex = 0; $tokens = $pTokens['tokens']; foreach ($tokens as $val) { switch ($val) { case '?': $query .= $this->quote($data[$dataIndex++]); break; case '&': $filename = $data[$dataIndex++]; $query .= file_get_contents($filename); break; case '!': $query .= $data[$dataIndex++]; break; default: $query .= $val; break; }//switch }//foreach return $this->query($query); }else{ return false; } } /** * Run both prepare and execute without the client having to run both individually. * * @param string $sql The sql to parse * @param array $data The array of data to replace the tokens with. * @return resource result set or false on error */ public function pQuery($sql, $data = array()) { $stmt = $this->prepareQuery($sql); return $this-><API key>($stmt, $data); } /** * Generates sql for create table statement for a bean. * * NOTE: does not handle out-of-table constraints, use createConstraintSQL for that * @param SugarBean $bean SugarBean instance * @return string SQL Create Table statement */ public function createTableSQL(SugarBean $bean) { $tablename = $bean->getTableName(); $fieldDefs = $bean->getFieldDefinitions(); $indices = $bean->getIndices(); return $this-><API key>($tablename, $fieldDefs, $indices); } /** * Generates SQL for insert statement. * * @param SugarBean $bean SugarBean instance * @return string SQL Create Table statement */ public function insertSQL(SugarBean $bean) { // get column names and values $sql = $this->insertParams($bean->getTableName(), $bean->getFieldDefinitions(), get_object_vars($bean), isset($bean->field_name_map)?$bean->field_name_map:null, false); return $sql; } /** * Generates SQL for update statement. * * @param SugarBean $bean SugarBean instance * @param array $where Optional, where conditions in an array * @return string SQL Create Table statement */ public function updateSQL(SugarBean $bean, array $where = array()) { $primaryField = $bean-><API key>(); $columns = array(); $fields = $bean->getFieldDefinitions(); // get column names and values foreach ($fields as $field => $fieldDef) { if (isset($fieldDef['source']) && $fieldDef['source'] != 'db') continue; // Do not write out the id field on the update statement. // We are not allowed to change ids. if ($fieldDef['name'] == $primaryField['name']) continue; // If the field is an auto_increment field, then we shouldn't be setting it. This was added // specially for Bugs and Cases which have a number associated with them. if (!empty($bean->field_name_map[$field]['auto_increment'])) continue; //custom fields handle their save separately if(isset($bean->field_name_map) && !empty($bean->field_name_map[$field]['custom_type'])) continue; // no need to clear deleted since we only update not deleted records anyway if($fieldDef['name'] == 'deleted' && empty($bean->deleted)) continue; if(isset($bean->$field)) { $val = from_html($bean->$field); } else { continue; } if(!empty($fieldDef['type']) && $fieldDef['type'] == 'bool'){ $val = $bean->getFieldValue($field); } if(strlen($val) == 0) { if(isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) { $val = $fieldDef['default']; } else { $val = null; } } if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) { $val = $this->truncate($val, $fieldDef['len']); } if(!is_null($val) || !empty($fieldDef['required'])) { $columns[] = "{$fieldDef['name']}=".$this->massageValue($val, $fieldDef); } elseif($this->isNullable($fieldDef)) { $columns[] = "{$fieldDef['name']}=NULL"; } else { $columns[] = "{$fieldDef['name']}=".$this->emptyValue($fieldDef['type']); } } if ( sizeof($columns) == 0 ) return ""; // no columns set // build where clause $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where)); if(isset($fields['deleted'])) { $where .= " AND deleted=0"; } return "UPDATE ".$bean->getTableName()." SET ".implode(",", $columns)." $where"; } /** * This method returns a where array so that it has id entry if * where is not an array or is empty * * @param SugarBean $bean SugarBean instance * @param array $where Optional, where conditions in an array * @return array */ protected function updateWhereArray(SugarBean $bean, array $where = array()) { if (count($where) == 0) { $fieldDef = $bean-><API key>(); $primaryColumn = $fieldDef['name']; $val = $bean->getFieldValue($fieldDef['name']); if ($val != FALSE){ $where[$primaryColumn] = $val; } } return $where; } /** * Returns a where clause without the 'where' key word * * The clause returned does not have an 'and' at the beginning and the columns * are joined by 'and'. * * @param string $table table name * @param array $whereArray Optional, where conditions in an array * @return string */ protected function <API key>($table, array $whereArray = array()) { $where = array(); foreach ($whereArray as $name => $val) { $op = "="; if (is_array($val)) { $op = "IN"; $temp = array(); foreach ($val as $tval){ $temp[] = $this->quoted($tval); } $val = implode(",", $temp); $val = "($val)"; } else { $val = $this->quoted($val); } $where[] = " $table.$name $op $val"; } if (!empty($where)) return implode(" AND ", $where); return ''; } /** * This method returns a complete where clause built from the * where values specified. * * @param SugarBean $bean SugarBean that describes the table * @param array $whereArray Optional, where conditions in an array * @return string */ protected function getWhereClause(SugarBean $bean, array $whereArray=array()) { return " WHERE " . $this-><API key>($bean->getTableName(), $whereArray); } /** * Outputs a correct string for the sql statement according to value * * @param mixed $val * @param array $fieldDef field definition * @return mixed */ public function massageValue($val, $fieldDef) { $type = $this->getFieldType($fieldDef); if(isset($this->type_class[$type])) { // handle some known types switch($this->type_class[$type]) { case 'bool': case 'int': if (!empty($fieldDef['required']) && $val == ''){ if (isset($fieldDef['default'])){ return $fieldDef['default']; } return 0; } return intval($val); case 'bigint' : $val = (float)$val; if (!empty($fieldDef['required']) && $val == false){ if (isset($fieldDef['default'])){ return $fieldDef['default']; } return 0; } return $val; case 'float': if (!empty($fieldDef['required']) && $val == ''){ if (isset($fieldDef['default'])){ return $fieldDef['default']; } return 0; } return floatval($val); case 'time': case 'date': // empty date can't be '', so convert it to either NULL or empty date value if($val == '') { if (!empty($fieldDef['required'])) { if (isset($fieldDef['default'])) { return $fieldDef['default']; } return $this->emptyValue($type); } return "NULL"; } break; } } else { if(!empty($val) && !empty($fieldDef['len']) && strlen($val) > $fieldDef['len']) { $val = $this->truncate($val, $fieldDef['len']); } } if ( is_null($val) ) { if(!empty($fieldDef['required'])) { if (isset($fieldDef['default'])){ return $fieldDef['default']; } return $this->emptyValue($type); } else { return "NULL"; } } if($type == "datetimecombo") { $type = "datetime"; } return $this->convert($this->quoted($val), $type); } /** * Massages the field defintions to fill in anything else the DB backend may add * * @param array $fieldDef * @param string $tablename * @return array */ public function massageFieldDef(&$fieldDef, $tablename) { if ( !isset($fieldDef['dbType']) ) { if ( isset($fieldDef['dbtype']) ) $fieldDef['dbType'] = $fieldDef['dbtype']; else $fieldDef['dbType'] = $fieldDef['type']; } $type = $this->getColumnType($fieldDef['dbType'],$fieldDef['name'],$tablename); $matches = array(); // len can be a number or a string like 'max', for example, nvarchar(max) preg_match_all('/(\w+)(?:\(([0-9]+,?[0-9]*|\w+)\)|)/i', $type, $matches); if ( isset($matches[1][0]) ) $fieldDef['type'] = $matches[1][0]; if ( isset($matches[2][0]) && empty($fieldDef['len']) ) $fieldDef['len'] = $matches[2][0]; if ( !empty($fieldDef['precision']) && is_numeric($fieldDef['precision']) && !strstr($fieldDef['len'],',') ) $fieldDef['len'] .= ",{$fieldDef['precision']}"; if (!empty($fieldDef['required']) || ($fieldDef['name'] == 'id' && !isset($fieldDef['required'])) ) { $fieldDef['required'] = 'true'; } } /** * Take an SQL statement and produce a list of fields used in that select * @param string $selectStatement * @return array */ public function <API key>($selectStatement) { $selectStatement = trim($selectStatement); if (strtoupper(substr($selectStatement, 0, 6)) == "SELECT") $selectStatement = trim(substr($selectStatement, 6)); //Due to sql functions existing in many selects, we can't use php explode $fields = array(); $level = 0; $selectField = ""; $strLen = strlen($selectStatement); for($i = 0; $i < $strLen; $i++) { $char = $selectStatement[$i]; if ($char == "," && $level == 0) { $field = $this-><API key>(trim($selectField)); $fields[$field] = $selectField; $selectField = ""; } else if ($char == "("){ $level++; $selectField .= $char; } else if($char == ")"){ $level $selectField .= $char; }else{ $selectField .= $char; } } $fields[$this-><API key>($selectField)] = $selectField; return $fields; } /** * returns the field name used in a select * @param string $string SELECT query * @return string */ protected function <API key>($string) { if(strncasecmp($string, "DISTINCT ", 9) == 0) { $string = substr($string, 9); } if (stripos($string, " as ") !== false) //"as" used for an alias return trim(substr($string, strripos($string, " as ") + 4)); else if (strrpos($string, " ") != 0) //Space used as a delimiter for an alias return trim(substr($string, strrpos($string, " "))); else if (strpos($string, ".") !== false) //No alias, but a table.field format was used return substr($string, strpos($string, ".") + 1); else //Give up and assume the whole thing is the field name return $string; } /** * Generates SQL for delete statement identified by id. * * @param SugarBean $bean SugarBean instance * @param array $where where conditions in an array * @return string SQL Update Statement */ public function deleteSQL(SugarBean $bean, array $where) { $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where)); return "UPDATE ".$bean->getTableName()." SET deleted=1 $where"; } /** * Generates SQL for select statement for any bean identified by id. * * @param SugarBean $bean SugarBean instance * @param array $where where conditions in an array * @return string SQL Select Statement */ public function retrieveSQL(SugarBean $bean, array $where) { $where = $this->getWhereClause($bean, $this->updateWhereArray($bean, $where)); return "SELECT * FROM ".$bean->getTableName()." $where AND deleted=0"; } /** * This method implements a generic sql for a collection of beans. * * Currently, this function does not support outer joins. * * @param array $beans Array of values returned by get_class method as the keys and a bean as * the value for that key. These beans will be joined in the sql by the key * attribute of field defs. * @param array $cols Optional, columns to be returned with the keys as names of bean * as identified by get_class of bean. Values of this array is the array of fieldDefs * to be returned for a bean. If an empty array is passed, all columns are selected. * @param array $whereClause Optional, values with the keys as names of bean as identified * by get_class of bean. Each value at the first level is an array of values for that * bean identified by name of fields. If we want to pass multiple values for a name, * pass it as an array. If where is not passed, all the rows will be returned. * * @return string SQL Select Statement */ public function retrieveViewSQL(array $beans, array $cols = array(), array $whereClause = array()) { $relations = array(); // stores relations between tables as they are discovered $where = $select = array(); foreach ($beans as $beanID => $bean) { $tableName = $bean->getTableName(); $beanTables[$beanID] = $tableName; $table = $beanID; $tables[$table] = $tableName; $aliases[$tableName][] = $table; // build part of select for this table if (is_array($cols[$beanID])) foreach ($cols[$beanID] as $def) $select[] = $table.".".$def['name']; // build part of where clause if (is_array($whereClause[$beanID])){ $where[] = $this-><API key>($table, $whereClause[$beanID]); } // initialize so that it can be used properly in form clause generation $table_used_in_from[$table] = false; $indices = $bean->getIndices(); foreach ($indices as $index){ if ($index['type'] == 'foreign') { $relationship[$table][] = array('foreignTable'=> $index['foreignTable'] ,'foreignColumn'=>$index['foreignField'] ,'localColumn'=> $index['fields'] ); } } $where[] = " $table.deleted = 0"; } // join these clauses $select = !empty($select) ? implode(",", $select) : "*"; $where = implode(" AND ", $where); // generate the from clause. Use relations array to generate outer joins // all the rest of the tables will be used as a simple from // relations table define relations between table1 and table2 through column on table 1 // table2 is assumed to joining through primary key called id $separator = ""; $from = ''; $table_used_in_from = array(); foreach ($relations as $table1 => $rightsidearray){ if ($table_used_in_from[$table1]) continue; // table has been joined $from .= $separator." ".$table1; $table_used_in_from[$table1] = true; foreach ($rightsidearray as $tablearray){ $table2 = $tablearray['foreignTable']; // get foreign table $tableAlias = $aliases[$table2]; // get a list of aliases for this table foreach ($tableAlias as $table2) { //choose first alias that does not match // we are doing this because of self joins. // in case of self joins, the same table will have many aliases. if ($table2 != $table1) break; } $col = $tablearray['foreingColumn']; $name = $tablearray['localColumn']; $from .= " LEFT JOIN $table on ($table1.$name = $table2.$col)"; $table_used_in_from[$table2] = true; } $separator = ","; } return "SELECT $select FROM $from WHERE $where"; } /** * Generates SQL for create index statement for a bean. * * @param SugarBean $bean SugarBean instance * @param array $fields fields used in the index * @param string $name index name * @param bool $unique Optional, set to true if this is an unique index * @return string SQL Select Statement */ public function createIndexSQL(SugarBean $bean, array $fields, $name, $unique = true) { $unique = ($unique) ? "unique" : ""; $tablename = $bean->getTableName(); $columns = array(); // get column names foreach ($fields as $fieldDef) $columns[] = $fieldDef['name']; if (empty($columns)) return ""; $columns = implode(",", $columns); return "CREATE $unique INDEX $name ON $tablename ($columns)"; } /** * Returns the type of the variable in the field * * @param array $fieldDef Vardef-format field def * @return string */ public function getFieldType($fieldDef) { // get the type for db type. if that is not set, // get it from type. This is done so that // we do not have change a lot of existing code // and add dbtype where type is being used for some special // purposes like referring to foreign table etc. if(!empty($fieldDef['dbType'])) return $fieldDef['dbType']; if(!empty($fieldDef['dbtype'])) return $fieldDef['dbtype']; if (!empty($fieldDef['type'])) return $fieldDef['type']; if (!empty($fieldDef['Type'])) return $fieldDef['Type']; if (!empty($fieldDef['data_type'])) return $fieldDef['data_type']; return null; } public function getTypeParts($type) { if(preg_match("#(?P<type>\w+)\s*(?P<arg>\((?P<len>\w+)\s*(,\s*(?P<scale>\d+))*\))*#", $type, $matches)) { $return = array(); // Not returning matches array as such as we don't want to expose the regex make up on the interface $return['baseType'] = $matches['type']; if( isset($matches['arg'])) { $return['arg'] = $matches['arg']; } if( isset($matches['len'])) { $return['len'] = $matches['len']; } if( isset($matches['scale'])) { $return['scale'] = $matches['scale']; } return $return; } else { return false; } } /** * Returns the defintion for a single column * * @param array $fieldDef Vardef-format field def * @param bool $ignoreRequired Optional, true if we should ignore this being a required field * @param string $table Optional, table name * @param bool $return_as_array Optional, true if we should return the result as an array instead of sql * @return string or array if $return_as_array is true */ protected function oneColumnSQLRep($fieldDef, $ignoreRequired = false, $table = '', $return_as_array = false) { $name = $fieldDef['name']; $type = $this->getFieldType($fieldDef); $colType = $this->getColumnType($type); if($parts = $this->getTypeParts($colType)) { $colBaseType = $parts['baseType']; $defLen = isset($parts['len']) ? $parts['len'] : '255'; // Use the mappings length (precision) as default if it exists } if(!empty($fieldDef['len'])) { if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char', 'clob', 'blob', 'text'))) { $colType = "$colBaseType(${fieldDef['len']})"; } elseif(($colBaseType == 'decimal' || $colBaseType == 'float')){ if(!empty($fieldDef['precision']) && is_numeric($fieldDef['precision'])) if(strpos($fieldDef['len'],',') === false){ $colType = $colBaseType . "(".$fieldDef['len'].",".$fieldDef['precision'].")"; }else{ $colType = $colBaseType . "(".$fieldDef['len'].")"; } else $colType = $colBaseType . "(".$fieldDef['len'].")"; } } else { if (in_array($colBaseType, array( 'nvarchar', 'nchar', 'varchar', 'varchar2', 'char'))) { $colType = "$colBaseType($defLen)"; } } $default = ''; // Bug #52610 We should have ability don't add DEFAULT part to query for boolean fields if (!empty($fieldDef['no_default'])) { // nothing to do } elseif (isset($fieldDef['default']) && strlen($fieldDef['default']) > 0) { $default = " DEFAULT ".$this->quoted($fieldDef['default']); } elseif (!isset($default) && $type == 'bool') { $default = " DEFAULT 0 "; } $auto_increment = ''; if(!empty($fieldDef['auto_increment']) && $fieldDef['auto_increment']) $auto_increment = $this->setAutoIncrement($table , $fieldDef['name']); $required = 'NULL'; // MySQL defaults to NULL, SQL Server defaults to NOT NULL -- must specify //Starting in 6.0, only ID and auto_increment fields will be NOT NULL in the DB. if ((empty($fieldDef['isnull']) || strtolower($fieldDef['isnull']) == 'false') && (!empty($auto_increment) || $name == 'id' || ($fieldDef['type'] == 'id' && !empty($fieldDef['required'])))) { $required = "NOT NULL"; } // If the field is marked both required & isnull=>false - alwqys make it not null // Use this to ensure primary key fields never defined as null if(isset($fieldDef['isnull']) && (strtolower($fieldDef['isnull']) == 'false' || $fieldDef['isnull'] === false) && !empty($fieldDef['required'])) { $required = "NOT NULL"; } if ($ignoreRequired) $required = ""; if ( $return_as_array ) { return array( 'name' => $name, 'colType' => $colType, 'colBaseType' => $colBaseType, // Adding base type for easier processing in derived classes 'default' => $default, 'required' => $required, 'auto_increment' => $auto_increment, 'full' => "$name $colType $default $required $auto_increment", ); } else { return "$name $colType $default $required $auto_increment"; } } /** * Returns SQL defintions for all columns in a table * * @param array $fieldDefs Vardef-format field def * @param bool $ignoreRequired Optional, true if we should ignor this being a required field * @param string $tablename Optional, table name * @return string SQL column definitions */ protected function columnSQLRep($fieldDefs, $ignoreRequired = false, $tablename) { $columns = array(); if ($this->isFieldArray($fieldDefs)) { foreach ($fieldDefs as $fieldDef) { if(!isset($fieldDef['source']) || $fieldDef['source'] == 'db') { $columns[] = $this->oneColumnSQLRep($fieldDef,false, $tablename); } } $columns = implode(",", $columns); } else { $columns = $this->oneColumnSQLRep($fieldDefs,$ignoreRequired, $tablename); } return $columns; } /** * Returns the next value for an auto increment * @abstract * @param string $table Table name * @param string $field_name Field name * @return string */ public function getAutoIncrement($table, $field_name) { return ""; } /** * Returns the sql for the next value in a sequence * @abstract * @param string $table Table name * @param string $field_name Field name * @return string */ public function getAutoIncrementSQL($table, $field_name) { return ""; } /** * Either creates an auto increment through queries or returns sql for auto increment * that can be appended to the end of column defination (mysql) * @abstract * @param string $table Table name * @param string $field_name Field name * @return string */ protected function setAutoIncrement($table, $field_name) { $this->deleteAutoIncrement($table, $field_name); return ""; } /** * Sets the next auto-increment value of a column to a specific value. * @abstract * @param string $table Table name * @param string $field_name Field name * @param int $start_value Starting autoincrement value * @return string * */ public function <API key>($table, $field_name, $start_value) { return ""; } /** * Deletes an auto increment * @abstract * @param string $table tablename * @param string $field_name */ public function deleteAutoIncrement($table, $field_name) { return; } /** * This method generates sql for adding a column to table identified by field def. * * @param string $tablename * @param array $fieldDefs * @return string SQL statement */ public function addColumnSQL($tablename, $fieldDefs) { return $this->changeColumnSQL($tablename, $fieldDefs, 'add'); } /** * This method genrates sql for altering old column identified by oldFieldDef to new fieldDef. * * @param string $tablename * @param array $newFieldDefs * @param bool $ignorerequired Optional, true if we should ignor this being a required field * @return string|array SQL statement(s) */ public function alterColumnSQL($tablename, $newFieldDefs, $ignorerequired = false) { return $this->changeColumnSQL($tablename, $newFieldDefs, 'modify', $ignorerequired); } /** * Generates SQL for dropping a table. * * @param SugarBean $bean Sugarbean instance * @return string SQL statement */ public function dropTableSQL(SugarBean $bean) { return $this->dropTableNameSQL($bean->getTableName()); } /** * Generates SQL for dropping a table. * * @param string $name table name * @return string SQL statement */ public function dropTableNameSQL($name) { return "DROP TABLE ".$name; } /** * Generates SQL for truncating a table. * @param string $name table name * @return string */ public function truncateTableSQL($name) { return "TRUNCATE $name"; } /** * This method generates sql that deletes a column identified by fieldDef. * * @param SugarBean $bean Sugarbean instance * @param array $fieldDefs * @return string SQL statement */ public function deleteColumnSQL(SugarBean $bean, $fieldDefs) { return $this->dropColumnSQL($bean->getTableName(), $fieldDefs); } /** * This method generates sql that drops a column identified by fieldDef. * Designed to work like the other addColumnSQL() and alterColumnSQL() functions * * @param string $tablename * @param array $fieldDefs * @return string SQL statement */ public function dropColumnSQL($tablename, $fieldDefs) { return $this->changeColumnSQL($tablename, $fieldDefs, 'drop'); } /** * Return a version of $proposed that can be used as a column name in any of our supported databases * Practically this means no longer than 25 characters as the smallest identifier length for our supported DBs is 30 chars for Oracle plus we add on at least four characters in some places (for indicies for example) * @param string|array $name Proposed name for the column * @param bool|string $ensureUnique Ensure the name is unique * @param string $type Name type (table, column) * @param bool $force Force new name * @return string|array Valid column name trimmed to right length and with invalid characters removed */ public function getValidDBName($name, $ensureUnique = false, $type = 'column', $force = false) { if(is_array($name)) { $result = array(); foreach($name as $field) { $result[] = $this->getValidDBName($field, $ensureUnique, $type); } return $result; } else { if(strchr($name, ".")) { // this is a compound name with dots, handle separately $parts = explode(".", $name); if(count($parts) > 2) { // some weird name, cut to table.name array_splice($parts, 0, count($parts)-2); } $parts = $this->getValidDBName($parts, $ensureUnique, $type, $force); return join(".", $parts); } // first strip any invalid characters - all but word chars (which is alphanumeric and _) $name = preg_replace( '/[^\w]+/i', '', $name ) ; $len = strlen( $name ) ; $maxLen = empty($this->maxNameLengths[$type]) ? $this->maxNameLengths[$type]['column'] : $this->maxNameLengths[$type]; if ($len <= $maxLen && !$force) { return strtolower($name); } if ($ensureUnique) { $md5str = md5($name); $tail = substr ( $name, -11) ; $temp = substr($md5str , strlen($md5str)-4 ); $result = substr( $name, 0, 10) . $temp . $tail ; } else { $result = substr( $name, 0, 11) . substr( $name, 11 - $maxLen); } return strtolower( $result ) ; } } /** * Returns the valid type for a column given the type in fieldDef * * @param string $type field type * @return string valid type for the given field */ public function getColumnType($type) { return isset($this->type_map[$type])?$this->type_map[$type]:$type; } /** * Checks to see if passed array is truely an array of defitions * * Such an array may have type as a key but it will point to an array * for a true array of definitions an to a col type for a definition only * * @param mixed $defArray * @return bool */ public function isFieldArray($defArray) { if ( !is_array($defArray) ) return false; if ( isset($defArray['type']) ){ // type key exists. May be an array of defs or a simple definition return is_array($defArray['type']); // type is not an array => definition else array } // type does not exist. Must be array of definitions return true; } /** * returns true if the type can be mapped to a valid column type * * @param string $type * @return bool */ protected function validColumnType($type) { $type = $this->getColumnType($type); return !empty($type); } /** * Generate query for audit table * @param SugarBean $bean SugarBean that was changed * @param array $changes List of changes, contains 'before' and 'after' * @return string Audit table INSERT query */ protected function auditSQL(SugarBean $bean, $changes) { global $current_user; $sql = "INSERT INTO ".$bean-><API key>(); //get field defs for the audit table. require('metadata/<API key>.php'); $fieldDefs = $dictionary['audit']['fields']; $values=array(); $values['id'] = $this->massageValue(create_guid(), $fieldDefs['id']); $values['parent_id']= $this->massageValue($bean->id, $fieldDefs['parent_id']); $values['field_name']= $this->massageValue($changes['field_name'], $fieldDefs['field_name']); $values['data_type'] = $this->massageValue($changes['data_type'], $fieldDefs['data_type']); if ($changes['data_type']=='text') { $values['before_value_text'] = $this->massageValue($changes['before'], $fieldDefs['before_value_text']); $values['after_value_text'] = $this->massageValue($changes['after'], $fieldDefs['after_value_text']); } else { $values['before_value_string'] = $this->massageValue($changes['before'], $fieldDefs['before_value_string']); $values['after_value_string'] = $this->massageValue($changes['after'], $fieldDefs['after_value_string']); } $values['date_created'] = $this->massageValue(TimeDate::getInstance()->nowDb(), $fieldDefs['date_created'] ); $values['created_by'] = $this->massageValue($current_user->id, $fieldDefs['created_by']); $sql .= "(".implode(",", array_keys($values)).") "; $sql .= "VALUES(".implode(",", $values).")"; return $sql; } /** * Saves changes to module's audit table * * @param SugarBean $bean Sugarbean instance that was changed * @param array $changes List of changes, contains 'before' and 'after' * @return bool query result * */ public function save_audit_records(SugarBean $bean, $changes) { return $this->query($this->auditSQL($bean, $changes)); } /** * Finds fields whose value has changed. * The before and after values are stored in the bean. * Uses $bean->fetched_row && $bean->fetched_rel_row to compare * * @param SugarBean $bean Sugarbean instance that was changed * @param array|null $field_filter Array of filter names to be inspected (NULL means all fields) * @return array */ public function getDataChanges(SugarBean &$bean, array $field_filter = null) { $changed_values=array(); $fetched_row = array(); if (is_array($bean->fetched_row)) { $fetched_row = array_merge($bean->fetched_row, $bean->fetched_rel_row); } if ($fetched_row) { $field_defs = $bean->field_defs; if (is_array($field_filter)) { $field_defs = array_intersect_key($field_defs, array_flip($field_filter)); } // remove fields which do not present in fetched row $field_defs = array_intersect_key($field_defs, $fetched_row); // remove fields which do not exist as bean property $field_defs = array_intersect_key($field_defs, (array) $bean); foreach ($field_defs as $field => $properties) { $before_value = $fetched_row[$field]; $after_value=$bean->$field; if (isset($properties['type'])) { $field_type=$properties['type']; } else { if (isset($properties['dbType'])) { $field_type=$properties['dbType']; } else if(isset($properties['data_type'])) { $field_type=$properties['data_type']; } else { $field_type=$properties['dbtype']; } } //Because of bug #25078(sqlserver haven't 'date' type, trim extra "00:00:00" when insert into *_cstm table). // so when we read the audit datetime field from sqlserver, we have to replace the extra "00:00:00" again. if(!empty($field_type) && $field_type == 'date'){ $before_value = $this->fromConvert($before_value , $field_type); } //if the type and values match, do nothing. if (!($this->_emptyValue($before_value,$field_type) && $this->_emptyValue($after_value,$field_type))) { if (trim($before_value) !== trim($after_value)) { // Bug #42475: Don't directly compare numeric values, instead do the subtract and see if the comparison comes out to be "close enough", it is necessary for floating point numbers. // Manual merge of fix <SHA1-like> from DBHelper // This fix also fixes Bug #44624 in a more generic way and therefore eliminates the need for fix <SHA1-like> in DBHelper if (!($this->isNumericType($field_type) && abs( 2*((trim($before_value)+0)-(trim($after_value)+0))/((trim($before_value)+0)+(trim($after_value)+0)) // Using relative difference so that it also works for other numerical types besides currencies )<0.0000000001)) { // Smaller than 10E-10 if (!($this->isBooleanType($field_type) && ($this->_getBooleanValue($before_value)== $this->_getBooleanValue($after_value)))) { $changed_values[$field]=array('field_name'=>$field, 'data_type'=>$field_type, 'before'=>$before_value, 'after'=>$after_value); } } } } } } return $changed_values; } /** * Uses the audit enabled fields array to find fields whose value has changed. * The before and after values are stored in the bean. * Uses $bean->fetched_row && $bean->fetched_rel_row to compare * * @param SugarBean $bean Sugarbean instance that was changed * @return array */ public function getAuditDataChanges(SugarBean $bean) { $audit_fields = $bean-><API key>(); return $this->getDataChanges($bean, array_keys($audit_fields)); } /** * Setup FT indexing * @abstract */ public function <API key>() { // Most DBs have nothing to setup, so provide default empty function } /** * Quotes a string for storing in the database * @deprecated * Return value will be not surrounded by quotes * * @param string $string * @return string */ public function escape_quote($string) { return $this->quote($string); } /** * Quotes a string for storing in the database * @deprecated * Return value will be not surrounded by quotes * * @param string $string * @return string */ public function quoteFormEmail($string) { return $this->quote($string); } /** * Renames an index using fields definition * * @param array $old_definition * @param array $new_definition * @param string $table_name * @return string SQL statement */ public function renameIndexDefs($old_definition, $new_definition, $table_name) { return array($this->add_drop_constraint($table_name,$old_definition,true), $this->add_drop_constraint($table_name,$new_definition), false); } /** * Check if type is boolean * @param string $type * @return bool */ public function isBooleanType($type) { return 'bool' == $type; } /** * Get truth value for boolean type * Allows 'off' to mean false, along with all 'empty' values * @param mixed $val * @return bool */ protected function _getBooleanValue($val) { if (empty($val) or $val==='off') return false; return true; } /** * Check if type is a number * @param string $type * @return bool */ public function isNumericType($type) { if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) { return true; } return false; } /** * Check if the value is empty value for this type * @param mixed $val Value * @param string $type Type (one of vardef types) * @return bool true if the value if empty */ protected function _emptyValue($val, $type) { if (empty($val)) return true; if($this->emptyValue($type) == $val) { return true; } switch ($type) { case 'decimal': case 'decimal2': case 'int': case 'double': case 'float': case 'uint': case 'ulong': case 'long': case 'short': return ($val == 0); case 'date': if ($val == '0000-00-00') return true; if ($val == 'NULL') return true; return false; } return false; } /** * @abstract * Does this type represent text (i.e., non-varchar) value? * @param string $type * @return bool */ public function isTextType($type) { return false; } /** * Check if this DB supports certain capability * See $this->capabilities for the list * @param string $cap * @return bool */ public function supports($cap) { return !empty($this->capabilities[$cap]); } /** * Create ORDER BY clause for ENUM type field * @param string $order_by Field name * @param array $values Possible enum value * @param string $order_dir Order direction, ASC or DESC * @return string */ public function orderByEnum($order_by, $values, $order_dir) { $i = 0; $order_by_arr = array(); foreach ($values as $key => $value) { if($key == '') { $order_by_arr[] = "WHEN ($order_by='' OR $order_by IS NULL) THEN $i"; } else { $order_by_arr[] = "WHEN $order_by=".$this->quoted($key)." THEN $i"; } $i++; } return "CASE ".implode("\n", $order_by_arr)." ELSE $i END $order_dir\n"; } /** * Return representation of an empty value depending on type * The value is fully quoted, converted, etc. * @param string $type * @return mixed Empty value */ public function emptyValue($type) { if(isset($this->type_class[$type]) && ($this->type_class[$type] == 'bool' || $this->type_class[$type] == 'int' || $this->type_class[$type] == 'float')) { return 0; } return "''"; } /** * List of available collation settings * @abstract * @return string */ public function getDefaultCollation() { return null; } /** * List of available collation settings * @abstract * @return array */ public function getCollationList() { return null; } /** * Returns the number of columns in a table * * @param string $table_name * @return int */ public function number_of_columns($table_name) { $table = $this->getTableDescription($table_name); return count($table); } /** * Return limit query based on given query * @param string $sql * @param int $start * @param int $count * @param bool $dieOnError * @param string $msg * @return resource|bool query result * @see DBManager::limitQuery() */ public function limitQuerySql($sql, $start, $count, $dieOnError=false, $msg='') { return $this->limitQuery($sql,$start,$count,$dieOnError,$msg,false); } /** * Return current time in format fit for insertion into DB (with quotes) * @return string */ public function now() { return $this->convert($this->quoted(TimeDate::getInstance()->nowDb()), "datetime"); } /** * Check if connecting user has certain privilege * @param string $privilege * @return bool Privilege allowed? */ public function checkPrivilege($privilege) { switch($privilege) { case "CREATE TABLE": $this->query("CREATE TABLE temp (id varchar(36))"); break; case "DROP TABLE": $sql = $this->dropTableNameSQL("temp"); $this->query($sql); break; case "INSERT": $this->query("INSERT INTO temp (id) VALUES ('<API key>')"); break; case "UPDATE": $this->query("UPDATE temp SET id = '<API key>' WHERE id = '<API key>'"); break; case 'SELECT': return $this->getOne('SELECT id FROM temp WHERE id=\'<API key>\'', false); case 'DELETE': $this->query("DELETE FROM temp WHERE id = '<API key>'"); break; case "ADD COLUMN": $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 50)); $sql = $this->changeColumnSQL("temp", $test, "add"); $this->query($sql); break; case "CHANGE COLUMN": $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100)); $sql = $this->changeColumnSQL("temp", $test, "modify"); $this->query($sql); break; case "DROP COLUMN": $test = array("test" => array("name" => "test", "type" => "varchar", "len" => 100)); $sql = $this->changeColumnSQL("temp", $test, "drop"); $this->query($sql); break; default: return false; } if($this->checkError("Checking privileges")) { return false; } return true; } /** * Check if the query is a select query * @param string $query * @return bool Is query SELECT? */ protected function isSelect($query) { $query = trim($query); $select_check = strpos(strtolower($query), strtolower("SELECT")); //Checks to see if there is union select which is valid $select_check2 = strpos(strtolower($query), strtolower("(SELECT")); if($select_check==0 || $select_check2==0){ //Returning false means query is ok! return true; } return false; } /** * Parse fulltext search query with mysql syntax: * terms quoted by "" * + means the term must be included * - means the term must be excluded * * or % at the end means wildcard * @param string $query * @return array of 3 elements - query terms, mandatory terms and excluded terms */ public function parseFulltextQuery($query) { /* split on space or comma, double quotes with \ for escape */ if(strpbrk($query, " ,")) { if(!preg_match_all('/("([^"]*?)"|[^"\s,]+)((,\s)+)?/', $query, $m)) { return false; } $qterms = $m[1]; } else { $qterms = array($query); } $terms = $must_terms = $not_terms = array(); foreach($qterms as $item) { if($item[0] == '"') { $item = trim($item, '"'); } if($item[0] == '+') { if (strlen($item) > 1) { $must_terms[] = substr($item, 1); } continue; } if($item[0] == '-') { if (strlen($item) > 1) { $not_terms[] = substr($item, 1); } continue; } $terms[] = $item; } return array($terms, $must_terms, $not_terms); } // Methods to check respective queries protected $standardQueries = array( 'ALTER TABLE' => 'verifyAlterTable', 'DROP TABLE' => 'verifyDropTable', 'CREATE TABLE' => 'verifyCreateTable', 'INSERT INTO' => 'verifyInsertInto', 'UPDATE' => 'verifyUpdate', 'DELETE FROM' => 'verifyDeleteFrom', ); /** * Extract table name from a query * @param string $query SQL query * @return string */ protected function extractTableName($query) { $query = preg_replace('/[^A-Za-z0-9_\s]/', "", $query); $query = trim(str_replace(array_keys($this->standardQueries), '', $query)); $firstSpc = strpos($query, " "); $end = ($firstSpc > 0) ? $firstSpc : strlen($query); $table = substr($query, 0, $end); return $table; } /** * Verify SQl statement using per-DB verification function * provided the function exists * @param string $query Query to verify * @param array $skipTables List of blacklisted tables that aren't checked * @return string */ public function verifySQLStatement($query, $skipTables) { $query = trim($query); foreach($this->standardQueries as $qstart => $check) { if(strncasecmp($qstart, $query, strlen($qstart)) == 0) { if(is_callable(array($this, $check))) { $table = $this->extractTableName($query); if(!in_array($table, $skipTables)) { return call_user_func(array($this, $check), $table, $query); } else { $this->log->debug("Skipping table $table as blacklisted"); } } else { $this->log->debug("No verification for $qstart on {$this->dbType}"); } break; } } return ""; } /** * Tests an CREATE TABLE query * @param string $table The table name to get DDL * @param string $query The query to test. * @return string Non-empty if error found */ protected function verifyCreateTable($table, $query) { $this->log->debug('verifying CREATE statement...'); // rewrite DDL with _temp name $this->log->debug('testing query: ['.$query.']'); $tempname = $table."__uw_temp"; $tempTableQuery = str_replace("CREATE TABLE {$table}", "CREATE TABLE $tempname", $query); if(strpos($tempTableQuery, '__uw_temp') === false) { return 'Could not use a temp table to test query!'; } $this->query($tempTableQuery, false, "Preflight Failed for: {$query}"); $error = $this->lastError(); // empty on no-errors if(!empty($error)) { return $error; } // check if table exists $this->log->debug('testing for table: '.$table); if(!$this->tableExists($tempname)) { return "Failed to create temp table!"; } $this->dropTableName($tempname); return ''; } /** * Execute multiple queries one after another * @param array $sqls Queries * @param bool $dieOnError Die on error, passed to query() * @param string $msg Error message, passed to query() * @param bool $suppress Supress errors, passed to query() * @return resource|bool result set or success/failure bool */ public function queryArray(array $sqls, $dieOnError = false, $msg = '', $suppress = false) { $last = true; foreach($sqls as $sql) { if(!($last = $this->query($sql, $dieOnError, $msg, $suppress))) { break; } } return $last; } /** * Fetches the next row in the query result into an associative array * * @param resource $result * @param bool $encode Need to HTML-encode the result? * @return array returns false if there are no more rows available to fetch */ public function fetchByAssoc($result, $encode = true) { if (empty($result)) return false; if(is_int($encode) && func_num_args() == 3) { // old API: $result, $rowNum, $encode $GLOBALS['log']->deprecated("Using row number in fetchByAssoc is not portable and no longer supported. Please fix your code."); $encode = func_get_arg(2); } $row = $this->fetchRow($result); if (!empty($row) && $encode && $this->encode) { return array_map('to_html', $row); } else { return $row; } } /** * Get DB driver name used for install/upgrade scripts * @return string */ public function getScriptName() { // Usually the same name as dbType return $this->dbType; } /** * Set database options * Options are usually db-dependant and derive from $config['dbconfigoption'] * @param array $options * @return DBManager */ public function setOptions($options) { $this->options = $options; return $this; } /** * Get DB options * @return array */ public function getOptions() { return $this->options; } /** * Get DB option by name * @param string $option Option name * @return mixed Option value or null if doesn't exist */ public function getOption($option) { if(isset($this->options[$option])) { return $this->options[$option]; } return null; } /** * Commits pending changes to the database when the driver is setup to support transactions. * Note that the default implementation is applicable for transaction-less or auto commit scenarios. * @abstract * @return bool true if commit succeeded, false if it failed */ public function commit() { $this->log->info("DBManager.commit() stub"); return true; } /** * Rollsback pending changes to the database when the driver is setup to support transactions. * Note that the default implementation is applicable for transaction-less or auto commit scenarios. * Since rollbacks cannot be done, this implementation always returns false. * @abstract * @return bool true if rollback succeeded, false if it failed */ public function rollback() { $this->log->info("DBManager.rollback() stub"); return false; } /** * Check if this DB name is valid * * @param string $name * @return bool */ public function isDatabaseNameValid($name) { // Generic case - no slashes, no dots return preg_match('#[/.\\\\]#', $name)==0; } /** * Check special requirements for DB installation. * @abstract * If everything is OK, return true. * If something's wrong, return array of error code and parameters * @return mixed */ public function canInstall() { return true; } /** * @abstract * Code run on new database before installing */ public function preInstall() { } /** * @abstract * Code run on new database after installing */ public function postInstall() { } /** * Disable keys on the table * @abstract * @param string $tableName */ public function disableKeys($tableName) { } /** * Re-enable keys on the table * @abstract * @param string $tableName */ public function enableKeys($tableName) { } /** * Quote string in DB-specific manner * @param string $string * @return string */ abstract public function quote($string); /** * Use when you need to convert a database string to a different value; this function does it in a * database-backend aware way * Supported conversions: * today return current date * left Take substring from the left * date_format Format date as string, supports %Y-%m-%d, %Y-%m, %Y * time_format Format time as string * date Convert date string to datetime value * time Convert time string to datetime value * datetime Convert datetime string to datetime value * ifnull If var is null, use default value * concat Concatenate strings * quarter Quarter number of the date * length Length of string * month Month number of the date * add_date Add specified interval to a date * add_time Add time interval to a date * text2char Convert text field to varchar * * @param string $string database string to convert * @param string $type type of conversion to do * @param array $<API key> optional, additional parameters to pass to the db function * @return string */ abstract public function convert($string, $type, array $<API key> = array()); /** * Converts from Database data to app data * * Supported types * - date * - time * - datetime * - datetimecombo * - timestamp * * @param string $string database string to convert * @param string $type type of conversion to do * @return string */ abstract public function fromConvert($string, $type); /** * Parses and runs queries * * @param string $sql SQL Statement to execute * @param bool $dieOnError True if we want to call die if the query returns errors * @param string $msg Message to log if error occurs * @param bool $suppress Flag to suppress all error output unless in debug logging mode. * @param bool $keepResult Keep query result in the object? * @return resource|bool result set or success/failure bool */ abstract public function query($sql, $dieOnError = false, $msg = '', $suppress = false, $keepResult = false); /** * Runs a limit query: one where we specify where to start getting records and how many to get * * @param string $sql SELECT query * @param int $start Starting row * @param int $count How many rows * @param boolean $dieOnError True if we want to call die if the query returns errors * @param string $msg Message to log if error occurs * @param bool $execute Execute or return SQL? * @return resource query result */ abstract function limitQuery($sql, $start, $count, $dieOnError = false, $msg = '', $execute = true); /** * Free Database result * @param resource $dbResult */ abstract protected function freeDbResult($dbResult); /** * Rename column in the DB * @param string $tablename * @param string $column * @param string $newname */ abstract function renameColumnSQL($tablename, $column, $newname); /** * Returns definitions of all indies for passed table. * * return will is a multi-dimensional array that * categorizes the index definition by types, unique, primary and index. * <code> * <?php * array( O * 'index1'=> array ( * 'name' => 'index1', * 'type' => 'primary', * 'fields' => array('field1','field2') * ) * ) * ?> * </code> * This format is similar to how indicies are defined in vardef file. * * @param string $tablename * @return array */ abstract public function get_indices($tablename); /** * Returns definitions of all indies for passed table. * * return will is a multi-dimensional array that * categorizes the index definition by types, unique, primary and index. * <code> * <?php * array( * 'field1'=> array ( * 'name' => 'field1', * 'type' => 'varchar', * 'len' => '200' * ) * ) * ?> * </code> * This format is similar to how indicies are defined in vardef file. * * @param string $tablename * @return array */ abstract public function get_columns($tablename); /** * Generates alter constraint statement given a table name and vardef definition. * * Supports both adding and droping a constraint. * * @param string $table tablename * @param array $definition field definition * @param bool $drop true if we are dropping the constraint, false if we are adding it * @return string SQL statement */ abstract public function add_drop_constraint($table, $definition, $drop = false); /** * Returns the description of fields based on the result * * @param resource $result * @param boolean $make_lower_case * @return array field array */ abstract public function getFieldsArray($result, $make_lower_case = false); /** * Returns an array of tables for this database * * @return array|false an array of with table names, false if no tables found */ abstract public function getTablesArray(); /** * Return's the version of the database * * @return string */ abstract public function version(); /** * Checks if a table with the name $tableName exists * and returns true if it does or false otherwise * * @param string $tableName * @return bool */ abstract public function tableExists($tableName); /** * Fetches the next row in the query result into an associative array * * @param resource $result * @return array returns false if there are no more rows available to fetch */ abstract public function fetchRow($result); /** * Connects to the database backend * * Takes in the database settings and opens a database connection based on those * will open either a persistent or non-persistent connection. * If a persistent connection is desired but not available it will defualt to non-persistent * * configOptions must include * db_host_name - server ip * db_user_name - database user name * db_password - database password * * @param array $configOptions * @param boolean $dieOnError */ abstract public function connect(array $configOptions = null, $dieOnError = false); /** * Generates sql for create table statement for a bean. * * @param string $tablename * @param array $fieldDefs * @param array $indices * @return string SQL Create Table statement */ abstract public function <API key>($tablename, $fieldDefs, $indices); /** * Generates the SQL for changing columns * * @param string $tablename * @param array $fieldDefs * @param string $action * @param bool $ignoreRequired Optional, true if we should ignor this being a required field * @return string|array */ abstract protected function changeColumnSQL($tablename, $fieldDefs, $action, $ignoreRequired = false); /** * Disconnects from the database * * Also handles any cleanup needed */ abstract public function disconnect(); /** * Get last database error * This function should return last error as reported by DB driver * and should return false if no error condition happened * @return string|false Error message or false if no error happened */ abstract public function lastDbError(); /** * Check if this query is valid * Validates only SELECT queries * @param string $query * @return bool */ abstract public function validateQuery($query); /** * Check if this driver can be used * @return bool */ abstract public function valid(); /** * Check if certain database exists * @param string $dbname */ abstract public function dbExists($dbname); /** * Get tables like expression * @param string $like Expression describing tables * @return array */ abstract public function tablesLike($like); /** * Create a database * @param string $dbname */ abstract public function createDatabase($dbname); /** * Drop a database * @param string $dbname */ abstract public function dropDatabase($dbname); /** * Get database configuration information (DB-dependent) * @return array|null */ abstract public function getDbInfo(); /** * Check if certain DB user exists * @param string $username */ abstract public function userExists($username); /** * Create DB user * @param string $database_name * @param string $host_name * @param string $user * @param string $password */ abstract public function createDbUser($database_name, $host_name, $user, $password); /** * Check if the database supports fulltext indexing * Note that database driver can be capable of supporting FT (see supports('fulltext)) * but particular instance can still have it disabled * @return bool */ abstract public function <API key>(); /** * Generate fulltext query from set of terms * @param string $field Field to search against * @param array $terms Search terms that may be or not be in the result * @param array $must_terms Search terms that have to be in the result * @param array $exclude_terms Search terms that have to be not in the result */ abstract public function getFulltextQuery($field, $terms, $must_terms = array(), $exclude_terms = array()); /** * Get install configuration for this DB * @return array */ abstract public function installConfig(); /** * Returns a DB specific FROM clause which can be used to select against functions. * Note that depending on the database that this may also be an empty string. * @abstract * @return string */ abstract public function getFromDummyTable(); /** * Returns a DB specific piece of SQL which will generate GUID (UUID) * This string can be used in dynamic SQL to do multiple inserts with a single query. * I.e. generate a unique Sugar id in a sub select of an insert statement. * @abstract * @return string */ abstract public function getGuidSQL(); }
# -*- coding: utf-8 -*- """ LMS index (home) page. """ from bok_choy.page_object import PageObject from . import BASE_URL BANNER_SELECTOR = 'section.home header div.outer-wrapper div.title hgroup h1' <API key> = 'div.play-intro' <API key> = 'section#video-modal.modal.<API key>.video-modal' class IndexPage(PageObject): """ LMS index (home) page, the default landing page for Open edX users when they are not logged in """ def __init__(self, browser): """Initialize the page. Arguments: browser (Browser): The browser instance. """ super(IndexPage, self).__init__(browser) url = "{base}/".format(base=BASE_URL) def is_browser_on_page(self): """ Returns a browser query object representing the video modal element """ element = self.q(css=BANNER_SELECTOR) return element.visible and element.text[0] == "Welcome to Open edX!" @property def banner_element(self): """ Returns a browser query object representing the video modal element """ return self.q(css=BANNER_SELECTOR) @property def intro_video_element(self): """ Returns a browser query object representing the video modal element """ return self.q(css=<API key>) @property def video_modal_element(self): """ Returns a browser query object representing the video modal element """ return self.q(css=<API key>) @property def footer_links(self): """Return a list of the text of the links in the page footer.""" return self.q(css='.nav-colophon a').attrs('text')
package collections.ship.marshal; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; /** * A SupplierKey serves as the key in the key/data pair for a supplier entity. * * <p> In this sample, SupplierKey is bound to the stored key tuple entry by * implementing the MarshalledKey interface, which is called by {@link * SampleViews.<API key>}. </p> * * @author Mark Hayes */ public class SupplierKey implements MarshalledKey { private String number; public SupplierKey(String number) { this.number = number; } public final String getNumber() { return number; } public String toString() { return "[SupplierKey: number=" + number + ']'; } SupplierKey() { // A no-argument constructor is necessary only to allow the binding to // instantiate objects of this class. } public void unmarshalKey(TupleInput keyInput) { this.number = keyInput.readString(); } public void marshalKey(TupleOutput keyOutput) { keyOutput.writeString(this.number); } }