answer
stringlengths
15
1.25M
#include <assert.h> #include "c_typebase.h" #include "idl_scope.h" #include "idl_genCxxHelper.h" #include "os_heap.h" #include "os_stdlib.h" #define IDL_MAXSCOPE (20) /* This modules handles the name scopes of objects by providing a scope stack. Each time a name scope is defined, the name is pushed on the stack. Each time the name scope is left, the name is popped from the stack. Name scopes are defined by the IDL definition "module <name>", "struct <name>" and "union <name>". */ /* idl_scopeElement specifies a scope stack element where "scopeName" specifies the name of the scope and "scopeType" specifies the kind of scope, either "idl_tFile" which is currently not used, "idl_tModule" for a module definition, "idl_tStruct" for a structure definition and "idl_tUnion" for a union definition. */ C_STRUCT(idl_scopeElement) { c_char *scopeName; idl_scopeType scopeType; }; /* idl_scope specifies the scope stack where "stack" is an array of "idl_scopeElement", "baseName" specifies the basename of the file that contains the scope stack and "scopePointer" specifies the actual top of the stack (-1 specifies an empty stack). */ C_STRUCT(idl_scope) { idl_scopeElement stack[IDL_MAXSCOPE]; c_char *baseName; c_long scopePointer; }; /* Create a new scope element with the specified name and type */ idl_scopeElement idl_scopeElementNew ( const char *scopeName, idl_scopeType scopeType) { idl_scopeElement element; assert (scopeName); assert (strlen(scopeName)); element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement)); element->scopeName = os_strdup (scopeName); element->scopeType = scopeType; return element; } /* Free a scope element */ void <API key> ( idl_scopeElement element) { assert (element); os_free (element->scopeName); os_free (element); } /* Create a copy of an existing scope element */ idl_scopeElement idl_scopeElementDup ( idl_scopeElement element) { idl_scopeElement new_element; assert (element); new_element = os_malloc ((size_t)C_SIZEOF(idl_scopeElement)); new_element->scopeName = os_strdup (element->scopeName); new_element->scopeType = element->scopeType; return new_element; } /* Return the scope name related to a specific scope element */ c_char * <API key> ( idl_scopeElement element) { if (element) { return element->scopeName; } return ""; } /* Return the scope type related to a specific scope element */ idl_scopeType <API key> ( idl_scopeElement element) { if (element == NULL) { /* Empty scope stack will deliver NULL scope element */ return idl_tModule; } return element->scopeType; } /* Create a new and empty scope stack, for a specified basename */ idl_scope idl_scopeNew ( const char *baseName) { idl_scope scope = os_malloc ((size_t)C_SIZEOF(idl_scope)); scope->baseName = os_strdup (baseName); scope->scopePointer = -1; return scope; } /* Create a new and empty scope stack, for a specified basename */ idl_scope idl_scopeDup ( idl_scope scope) { idl_scope newScope = idl_scopeNew(idl_scopeBasename(scope)); c_long si; for (si = 0; si < (scope->scopePointer+1); si++) { idl_scopePush (newScope, idl_scopeElementDup(scope->stack[si])); } return newScope; } /* Free a scope stack, also freeing all scope elements */ void idl_scopeFree ( idl_scope scope) { c_long si; assert (scope); for (si = 0; si < (scope->scopePointer+1); si++) { <API key>(scope->stack[si]); } os_free (scope->baseName); os_free (scope); return; } /* Push a scope element on the scope stack */ void idl_scopePush ( idl_scope scope, idl_scopeElement element ) { assert (scope); assert (scope->scopePointer < IDL_MAXSCOPE); assert (element); scope->scopePointer++; scope->stack[scope->scopePointer] = element; } /* Return the size of a scope stack (the amount of scope elements) */ c_long idl_scopeStackSize ( idl_scope scope) { return (scope->scopePointer+1); } /* Remove the top element from a scope stack */ void idl_scopePop ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= 0); scope->scopePointer } /* Remove the top element from a scope stack, and free its resources */ void idl_scopePopFree ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= 0); <API key>(scope->stack[scope->scopePointer]); scope->scopePointer } /* Return the top element from a scope stack */ idl_scopeElement idl_scopeCur ( idl_scope scope) { assert (scope); assert (scope->scopePointer >= -1); if (scope->scopePointer == -1) { return NULL; } return scope->stack[scope->scopePointer]; } /* Return the element from a scope stack, by index where "index" >= 0 and "index" <= "scopePointer" */ idl_scopeElement idl_scopeIndexed ( idl_scope scope, c_long index) { assert (index >= 0); assert (index <= scope->scopePointer); return scope->stack[index]; } /* Determine if two scope stacks are equal */ c_bool idl_scopeEqual ( idl_scope scope1, idl_scope scope2) { c_long i; /* If the "scopePointer"s are unequal, the stack do not equal */ if (scope1->scopePointer != scope2->scopePointer) { return FALSE; } /* Per stack element compare the names, if any does not equal the stacks are unequal */ for (i = 0; i < (scope1->scopePointer + 1); i++) { if (strcmp(<API key>(scope1->stack[i]), <API key>(scope2->stack[i])) != 0) { return FALSE; } } return TRUE; } /* Determine if a scope stack is contained by a second stack */ c_bool idl_scopeSub ( idl_scope scope, /* moduleScope */ idl_scope scopeSub) /* keyScope */ { c_long i; /* If the "scopePointer" of the stack is higher than the "scopePointer" of the second stack, the second stack can not contain the first stack */ if (scope->scopePointer > scopeSub->scopePointer) { return FALSE; } /* For all scope elements of the stack with the scope elements of the second stack. If one of them does not equal, the second stack can not contain the first. The scope element types are not compared, this should not a real problem. */ for (i = 0; i < (scope->scopePointer + 1); i++) { if (strcmp(<API key>(scope->stack[i]), <API key>(scopeSub->stack[i])) != 0) { return FALSE; } } return TRUE; } /* Build a textual representation of a scope stack with a specified seperator and optionally add a user specified identifier */ c_char * idl_scopeStack ( idl_scope scope, const char *scopeSepp, const char *name) { c_long si; c_char *scopeStack; c_char *elName; if (scope && (scope->scopePointer >= 0)) { /* If the stack is not empty */ si = 0; /* copy the first scope element name */ scopeStack = os_strdup (<API key>(scope->stack[si])); si++; /* for all scope elements */ while (si <= scope->scopePointer) { elName = <API key>(scope->stack[si]); /* allocate space for current scope stack + separator + next scope name */ scopeStack = os_realloc (scopeStack, (size_t)( (int)strlen(scopeStack)+ (int)strlen(scopeSepp)+ (int)strlen(elName)+1)); /* concatinate the separator */ os_strcat (scopeStack, scopeSepp); /* concatinate scope name */ os_strcat (scopeStack, elName); si++; } if (name) { /* if a user identifier is specified, allocate space for current scope stack + separator + user identifier */ scopeStack = os_realloc (scopeStack, (size_t)( (int)strlen(scopeStack)+ (int)strlen(scopeSepp)+ (int)strlen(name)+1)); /* concatinate the separator */ os_strcat (scopeStack, scopeSepp); /* concatinate user identifier */ os_strcat (scopeStack, name); } } else { /* Empty scope stack */ if (name) { /* if a user identifier is specified, copy the user identifier */ scopeStack = os_strdup (name); } else { /* make the scope stack representation empty */ scopeStack = os_strdup(""); } } /* return the scope stack represenation */ return scopeStack; } /* Return the basename related to a scope */ c_char * idl_scopeBasename ( idl_scope scope) { return os_strdup(scope->baseName); }
# This file is part of Paru # Paru is free software: you can redistribute it and/or modify # (at your option) any later version. # Paru is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the require_relative "./inline.rb" module Paru module PandocFilter # A Subscript inline node class Subscript < Inline end end end
<?xml version="1.0" encoding="UTF-8"?> <html lang="en" class="no-js ie8"> <!--<![endif]--> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <title> Mein Bookmanager </title> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <link rel="shortcut icon" href="/bookmanager/static/images/favicon.ico" type="image/x-icon"/> <link rel="apple-touch-icon" href="/bookmanager/static/images/apple-touch-icon.png"/> <link rel="apple-touch-icon" sizes="114x114" href="/bookmanager/static/images/<API key>.png"/> <link rel="stylesheet" href="/bookmanager/static/css/main.css" type="text/css"/> <link rel="stylesheet" href="/bookmanager/static/css/mobile.css" type="text/css"/> <meta name="layout" content="main"/> <style type="text/css" media="screen"> #status { background-color: #eee; border: .2em solid #fff; margin: 2em 2em 1em; padding: 1em; width: 12em; float: left; -moz-box-shadow: 0px 0px 1.25em #ccc; -webkit-box-shadow: 0px 0px 1.25em #ccc; box-shadow: 0px 0px 1.25em #ccc; -moz-border-radius: 0.6em; -<API key>: 0.6em; border-radius: 0.6em; } .ie6 #status { display: inline; } #status ul { font-size: 0.9em; list-style-type: none; margin-bottom: 0.6em; padding: 0; } #status li { line-height: 1.3; } #status h1 { text-transform: uppercase; font-size: 1.1em; margin: 0 0 0.3em; } #page-body { margin: 2em 1em 1.25em 18em; } h2 { margin-top: 1em; margin-bottom: 0.3em; font-size: 1em; } p { line-height: 1.5; margin: 0.25em 0; } #controller-list ul { list-style-position: inside; } #controller-list li { line-height: 1.3; list-style-position: inside; margin: 0.25em 0; } @media screen and (max-width: 480px) { #status { display: none; } #page-body { margin: 0 1em 1em; } #page-body h1 { margin-top: 0; } } </style> </head> <body> <div id="grailsLogo" role="banner"> <a href="http://grails.org"> <img src="/bookmanager/static/images/grails_logo.png" alt="Grails"/> </a> </div> <div class="nav" style="background-color: #9CAD6F;"> <ul> <li> <a href="/bookmanager/" class="home"> Start </a> </li> <li> <a href="/bookmanager/buchsuche/suchmaske" class="list"> Bücher Suche </a> </li> <li> <a href="/bookmanager/buch/index" class="list"> Bücher verwalten </a> </li> <li> <a href="/bookmanager/verlag/index" class="list"> Verlage verwalten </a> </li> <li> <a href="/bookmanager/autor/index" class="list"> Autoren verwalten </a> </li> </ul> </div> <a href="#page-body" class="skip"> Skip to content… </a> <div id="status" role="complementary"> <h1> Status der Anwendung </h1> <ul> <li> App version: 0.1 </li> <li> Grails version: 2.3.5 </li> <li> Groovy version: 2.1.9 </li> <li> JVM version: 1.6.0_27 </li> <li> Reloading active: true </li> <li> Controllers: 8 </li> <li> Domains: 3 </li> <li> Services: 4 </li> <li> Tag Libraries: 13 </li> </ul> <h1> Installierte Plugins </h1> <ul> <li> logging - 2.3.5 </li> <li> i18n - 2.3.5 </li> <li> core - 2.3.5 </li> <li> restResponder - 2.3.5 </li> <li> dataBinding - 2.3.5 </li> <li> resources - 1.2.1 </li> <li> databaseMigration - 1.3.8 </li> <li> webxml - 1.4.1 </li> <li> jquery - 1.10.2.2 </li> <li> codeCoverage - 1.2.7 </li> <li> geb - 0.9.2 </li> <li> spock - 0.7 </li> <li> urlMappings - 2.3.5 </li> <li> servlets - 2.3.5 </li> <li> codecs - 2.3.5 </li> <li> dataSource - 2.3.5 </li> <li> controllers - 2.3.5 </li> <li> functionalTest - 2.0.RC1 </li> <li> mimeTypes - 2.3.5 </li> <li> filters - 2.3.5 </li> <li> domainClass - 2.3.5 </li> <li> controllersAsync - 2.3.5 </li> <li> converters - 2.3.5 </li> <li> hibernate - 3.6.10.7 </li> <li> groovyPages - 2.3.5 </li> <li> validation - 2.3.5 </li> <li> services - 2.3.5 </li> <li> scaffolding - 2.0.1 </li> <li> cache - 1.1.1 </li> <li> buildTestData - 2.1.2 </li> </ul> </div> <div id="page-body" role="main"> <h1> Mein Bookmanager </h1> <p> Congratulations, you have successfully started your first Grails application! At the moment this is the default page, feel free to modify it to either redirect to a controller or display whatever content you may choose. Below is a list of controllers that are currently deployed in this application, click on each to execute its default action: </p> <div id="controller-list" role="navigation"> <h2> Verfügbare Controller: </h2> <ul> <li class="controller"> <a href="/bookmanager/autor/index"> bookmanager.AutorController </a> </li> <li class="controller"> <a href="/bookmanager/buch/index"> bookmanager.BuchController </a> </li> <li class="controller"> <a href="/bookmanager/buchsuche/index"> bookmanager.BuchsucheController </a> </li> <li class="controller"> <a href="/bookmanager/home/index"> bookmanager.HomeController </a> </li> <li class="controller"> <a href="/bookmanager/verlag/index"> bookmanager.VerlagController </a> </li> <li class="controller"> <a href="/bookmanager/functionaltesting/index"> com.grailsrocks.functionaltest.controllers.<API key> </a> </li> <li class="controller"> <a href="/bookmanager/selfTest/paramecho"> com.grailsrocks.functionaltest.controllers.test.SelfTestController </a> </li> <li class="controller"> <a href="/bookmanager/dbdoc"> grails.plugin.databasemigration.DbdocController </a> </li> </ul> </div> </div> <div class="footer" role="contentinfo"> © 2009 - 2014 - exensio GmbH - Version 0.1 </div> <div id="spinner" class="spinner" style="display:none;"> Loading… </div> <script src="/bookmanager/static/js/application.js" type="text/javascript"> </script> </body> </html>
using Nikse.SubtitleEdit.Core.Common; using Nikse.SubtitleEdit.Forms.Options; using Nikse.SubtitleEdit.Logic; using Nikse.SubtitleEdit.Logic.VideoPlayers; using System; using System.Text; using System.Windows.Forms; namespace Nikse.SubtitleEdit.Forms { public partial class VideoError : Form { public VideoError() { UiUtil.PreInitialize(this); InitializeComponent(); UiUtil.FixFonts(this); UiUtil.FixLargeFonts(this, buttonCancel); } public void Initialize(string fileName, Exception exception) { var sb = new StringBuilder(); sb.AppendLine("There seems to be missing a codec (or file is not a valid video/audio file)!"); sb.AppendLine(); var currentVideoPlayer = Configuration.Settings.General.VideoPlayer; var isLibMpvInstalled = LibMpvDynamic.IsInstalled; if (currentVideoPlayer == "MPV" && !isLibMpvInstalled) { currentVideoPlayer = "DirectShow"; } if (currentVideoPlayer == "VLC" && !LibVlcDynamic.IsInstalled) { currentVideoPlayer = "DirectShow"; } if (Configuration.IsRunningOnLinux) { sb.AppendLine("Try installing latest version of libmpv and libvlc!"); sb.Append("Read more about Subtitle Edit on Linux here: https://nikse.dk/SubtitleEdit/Help#linux"); } else if (currentVideoPlayer == "DirectShow") { sb.AppendLine("Try installing/updating \"LAV Filters - DirectShow Media Splitter and Decoders\": https://github.com/Nevcairiel/LAVFilters/releases"); sb.Append("Note that Subtitle Edit is a " + IntPtr.Size * 8 + "-bit program, and hence requires " + IntPtr.Size * 8 + "-bit codecs!"); sb.AppendLine(); } else if (currentVideoPlayer == "VLC") { sb.AppendLine("VLC media player was unable to play this file (perhaps it's not a valid video/audio file) - you can change video player via Options -> Settings -> Video Player"); sb.AppendLine("Latest version of VLC is available here: http: sb.AppendLine(); } else if (currentVideoPlayer == "MPV" && Configuration.IsRunningOnWindows) { sb.AppendLine("You can re-download mpv or change video player via Options -> Settings -> Video Player"); sb.AppendLine(); } richTextBoxMessage.Text = sb.ToString(); if (!Configuration.IsRunningOnWindows || currentVideoPlayer == "MPV") { buttonMpvSettings.Visible = false; labelMpvInfo.Visible = false; } else if (currentVideoPlayer != "MPV") { labelMpvInfo.Text = $"You could also switch video player from \"{currentVideoPlayer}\" to \"mpv\"."; if (isLibMpvInstalled) { buttonMpvSettings.Text = "Use \"mpv\" as video player"; } } if (exception != null) { var source = string.Empty; if (!string.IsNullOrEmpty(exception.Source)) { source = "Source: " + exception.Source.Trim() + Environment.NewLine + Environment.NewLine; } textBoxError.Text = "Message: " + exception.Message.Trim() + Environment.NewLine + source + "Stack Trace: " + Environment.NewLine + exception.StackTrace.Trim(); } Text += fileName; } private void VideoError_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { DialogResult = DialogResult.Cancel; } } private void <API key>(object sender, <API key> e) { UiUtil.OpenUrl(e.LinkText); } private void <API key>(object sender, EventArgs e) { if (LibMpvDynamic.IsInstalled) { Configuration.Settings.General.VideoPlayer = "MPV"; DialogResult = DialogResult.OK; return; } using (var form = new SettingsMpv(true)) { if (form.ShowDialog(this) == DialogResult.OK) { Configuration.Settings.General.VideoPlayer = "MPV"; DialogResult = DialogResult.OK; } } } } }
var __v=[ { "Id": 3568, "Panel": 1763, "Name": "", "Sort": 0, "Str": "" }, { "Id": 3569, "Panel": 1763, "Name": "API", "Sort": 0, "Str": "" }, { "Id": 3570, "Panel": 1763, "Name": "Example", "Sort": 0, "Str": "" } ]
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Mon Dec 09 13:16:02 CET 2013 --> <title>m0.main</title> <meta name="date" content="2013-12-09"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../m0/main/package-summary.html" target="classFrame">m0.main</a></h1> <div class="indexContainer"> <h2 title="Interfaces">Interfaces</h2> <ul title="Interfaces"> <li><a href="<API key>.html" title="interface in m0.main" target="classFrame"><i><API key></i></a></li> </ul> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="ClientLauncher.html" title="class in m0.main" target="classFrame">ClientLauncher</a></li> <li><a href="RemoteConfiguration.html" title="class in m0.main" target="classFrame">RemoteConfiguration</a></li> <li><a href="ServerLauncher.html" title="class in m0.main" target="classFrame">ServerLauncher</a></li> </ul> </div> </body> </html>
#ifndef ZIK_API_H #define ZIK_API_H /* Audio */ #define <API key> "/api/audio/equalizer/enabled" #define <API key> "/api/audio/noise" #define <API key> "/api/audio/noise_control" #define <API key> "/api/audio/noise_control/enabled" #define <API key> "/api/audio/noise_control/auto_nc" #define <API key> "/api/audio/noise_control/phone_mode" #define <API key> "/api/audio/preset/bypass" #define <API key> "/api/audio/preset/current" #define <API key> "/api/audio/smart_audio_tune" #define <API key> "/api/audio/sound_effect" #define <API key> "/api/audio/sound_effect/enabled" #define <API key> "/api/audio/sound_effect/room_size" #define <API key> "/api/audio/sound_effect/angle" #define <API key> "/api/audio/source" #define <API key> "/api/audio/thumb_equalizer/value" #define <API key> "/api/audio/track/metadata" #define <API key> "/api/audio/volume" /* Bluetooth */ #define <API key> "/api/bluetooth/friendlyname" /* Software */ #define <API key> "/api/software/version" #define <API key> "/api/software/tts" /* System */ #define <API key> "/api/system/anc_phone_mode/enabled" #define <API key> "/api/system/auto_connection/enabled" #define <API key> "/api/system/battery" #define <API key> "/api/system/battery/forecast" #define <API key> "/api/system/color" #define <API key> "/api/system/device_type" #define <API key> "/api/flight_mode" #define <API key> "/api/system/head_detection/enabled" #define <API key> "/api/system/pi" #define <API key> "/api/system/auto_power_off" /* Other */ #define <API key> "/api/flight_mode" #endif
<?php class WP_Gist { /** * Instance of the class. * * @var WP_Gist */ protected static $instance = null; /** * Class slug. * * @var string */ protected $slug = 'wp-gist'; /** * Class version. * * Used for cache-busting of style and script file references. */ protected $version = '3.1.0'; /** * Gets instance of class. * * @return WP_Gist Instance of the class. */ public static function get_instance() { if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Gets slug. * * @return string Slug. */ public function get_slug() { return $this->slug; } /** * Gets version. * * @return string Version. */ public function get_version() { return $this->version; } }
<?php // Clear variables $boardGameError = ""; $boardGameAvailable = ""; // Get the playerID, if null return user to the available page $playerID = null; if (!empty($_GET['playerID'])) { $playerID = $_REQUEST['playerID']; } if ( null==$playerID ) { header("Location: ../available.php"); } if ($_SERVER["REQUEST_METHOD"] == "POST") { $valid = true; if (empty($_POST["boardGameAvailable"])) { $boardGameError = "Board game name is required"; $valid = false; } else { $boardGameAvailable = validate_input($_POST["boardGameAvailable"]); // Check if first name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$boardGameAvailable)) { $boardGameError = "Only letters and white space allowed"; $valid = false; } } } // The database will only be connected to if PHP deems that the input is valid // Connect to DB and add player details if ($valid) { $pdo = Database::connect(); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO gamesavailable (boardGameAvailable, playerID) values(?, ?)"; $q = $pdo->prepare($sql); $q->execute(array($boardGameAvailable, $playerID)); Database::disconnect(); header("Location: ../available.php"); } // Validate and return input function validate_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>
var events = require('events'), koanize = require('koanizer'), util = require('util'); koanize(this); // Standard and RFC set these values var <API key> = 90000; // RTP packet constants and masks var RTP_HEADER_SIZE = 12; var <API key> = 4; var SAMPLES_PER_FRAME = 1152; // ISO 11172-3 var SAMPLING_FREQUENCY = 44100; var TIMESTAMP_DELTA = Math.floor(SAMPLES_PER_FRAME * <API key> / SAMPLING_FREQUENCY); var SECONDS_PER_FRAME = SAMPLES_PER_FRAME / SAMPLING_FREQUENCY; var RTPProtocol = function(){ events.EventEmitter.call(this); this.setMarker = false; this.ssrc = Math.floor(Math.random() * 100000); this.seqNum = Math.floor(Math.random() * 1000); this.timestamp = Math.floor(Math.random() * 1000); }; util.inherits(RTPProtocol, events.EventEmitter); RTPProtocol.prototype.pack = function(payload){ ++this.seqNum; // RFC3550 says it must increase by the number of samples // sent in a block in case of CBR audio streaming this.timestamp += TIMESTAMP_DELTA; if (!payload) { // Tried to send a packet, but packet was not ready. // Timestamp and Sequence Number should be increased // anyway 'cause interval callback was called and // that's like sending silence this.setMarker = true; return; } var RTPPacket = new Buffer(RTP_HEADER_SIZE + <API key> + payload.length); // version = 2: 10 // padding = 0: 0 // extension = 0: 0 // CRSCCount = 0: 0000 /* KOAN #1 should write Version, Padding, Extension and Count */ RTPPacket.writeUInt8(128, 0); // Marker = 0: 0 // RFC 1890: RTP Profile for Audio and Video Conferences with Minimal Control // Payload = 14: (MPEG Audio Only) 0001110 RTPPacket.writeUInt8(this.setMarker? 142 : 14, 1); this.setMarker = false; // SequenceNumber /* KOAN #2 should write Sequence Number */ RTPPacket.writeUInt16BE(this.seqNum, 2); // Timestamp /* KOAN #3 should write Timestamp... */ RTPPacket.writeUInt32BE(this.timestamp, 4); // SSRC /* KOAN #3 SSRC and... */ RTPPacket.writeUInt32BE(this.ssrc, 8); // RFC 2250: RTP Payload Format for MPEG1/MPEG2 Video // 3.5 MPEG Audio-specific header /* KOAN #3 payload Format */ RTPPacket.writeUInt32BE(0, 12); payload.copy(RTPPacket, 16); this.emit('packet', RTPPacket); //return RTPPacket; }; module.exports = exports.RTPProtocol = RTPProtocol;
<?php namespace PH7; class HomeController extends Controller { private $sTitle; public function __construct() { parent::__construct(); /** Predefined meta_description and keywords tags **/ $this->view->meta_description = t('Become an Affiliate with the affiliate dating community platform %site_name%'); $this->view->meta_keywords = t('affiliate,dating,dating site,social network,pay per click affiliate program, affiliate program'); } public function index() { $this->view->page_title = t('Affiliate Platform with %site_name%! Dating Social Affiliate'); $this->view->h1_title = t('Affiliate Platform - %site_name%'); if (Affiliate::auth()) $this->view->h3_title = t('Hello <em>%0%</em>, welcome to your site!', $this->session->get('<API key>')); if (!Affiliate::auth()) $this->design->addCss(PH7_LAYOUT . PH7_SYS . PH7_MOD . $this->registry->module . PH7_SH . PH7_TPL . PH7_TPL_MOD_NAME . PH7_SH . PH7_CSS, 'style.css'); $this->output(); } public function login() { $this->sTitle = t('Login Affiliate'); $this->view->page_title = $this->sTitle; $this->view->meta_description = $this->sTitle; $this->view->h1_title = $this->sTitle; $this->output(); } public function resendActivation() { $this->sTitle = t('Resend activation email'); $this->view->page_title = $this->sTitle; $this->view->h2_title = $this->sTitle; $this->output(); } public function logout() { (new Affiliate)->logout(); } }
// AppDelegate.h // Pedigree #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <<API key>> @property (strong, nonatomic) UIWindow *window; @end
from abc import ABC import configargparse from sklearn.externals import joblib from termcolor import colored class ScikitBase(ABC): """ Base class for AI strategies """ arg_parser = configargparse.get_argument_parser() arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True) arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)') pipeline = None def __init__(self): args = self.arg_parser.parse_known_args()[0] super(ScikitBase, self).__init__() self.pipeline = self.load_pipeline(args.pipeline) if args.feature_names: self.feature_names = self.load_pipeline(args.feature_names) @staticmethod def load_pipeline(pipeline_file): """ Loads scikit model/pipeline """ print(colored('Loading pipeline: ' + pipeline_file, 'green')) return joblib.load(pipeline_file) def <API key>(self): """ Method fetches pipeline from server/cloud """ # TODO pass def predict(self, df): """ Returns predictions based on the model/pipeline """ try: return self.pipeline.predict(df) except (ValueError, TypeError): print(colored('Got ValueError while using scikit model.. ', 'red')) return None
package com.octagon.airships.block; import com.octagon.airships.reference.Reference; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; public abstract class AirshipsBlock extends Block { public AirshipsBlock(Material material) { super(material); } public AirshipsBlock() { this(Material.rock); } @Override public String getUnlocalizedName() { return String.format("tile.%s%s", Reference.MOD_ID.toLowerCase() + ":", <API key>(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister iconRegister) { blockIcon = iconRegister.registerIcon(String.format("%s", <API key>(this.getUnlocalizedName()))); } protected String <API key>(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } }
#include "simple_form_widget.h" #include "<API key>.h" SimpleFormWidget::SimpleFormWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SimpleFormWidget) { ui->setupUi(this); } SimpleFormWidget::~SimpleFormWidget() { delete ui; }
package itaf.<API key>; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the itaf.<API key> package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private static final QName <API key> = new QName("itaf.framework.ws.server.consumer", "deleteByIdResponse"); private static final QName _GetById_QNAME = new QName("itaf.framework.ws.server.consumer", "getById"); private static final QName <API key> = new QName("itaf.framework.ws.server.consumer", "<API key>"); private static final QName <API key> = new QName("itaf.framework.ws.server.consumer", "<API key>"); private static final QName <API key> = new QName("itaf.framework.ws.server.consumer", "getByIdResponse"); private static final QName <API key> = new QName("itaf.framework.ws.server.consumer", "findListByUserId"); private static final QName _DeleteById_QNAME = new QName("itaf.framework.ws.server.consumer", "deleteById"); private static final QName _SaveOrUpdate_QNAME = new QName("itaf.framework.ws.server.consumer", "saveOrUpdate"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: itaf.<API key> * */ public ObjectFactory() { } /** * Create an instance of {@link FindListByUserId } * */ public FindListByUserId <API key>() { return new FindListByUserId(); } /** * Create an instance of {@link DeleteById } * */ public DeleteById createDeleteById() { return new DeleteById(); } /** * Create an instance of {@link SaveOrUpdate } * */ public SaveOrUpdate createSaveOrUpdate() { return new SaveOrUpdate(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link GetById } * */ public GetById createGetById() { return new GetById(); } /** * Create an instance of {@link DeleteByIdResponse } * */ public DeleteByIdResponse <API key>() { return new DeleteByIdResponse(); } /** * Create an instance of {@link GetByIdResponse } * */ public GetByIdResponse <API key>() { return new GetByIdResponse(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzInvoiceItemDto } * */ public BzInvoiceItemDto <API key>() { return new BzInvoiceItemDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link SysRoleDto } * */ public SysRoleDto createSysRoleDto() { return new SysRoleDto(); } /** * Create an instance of {@link BzStockOrderDto } * */ public BzStockOrderDto <API key>() { return new BzStockOrderDto(); } /** * Create an instance of {@link BzOrderPaymentDto } * */ public BzOrderPaymentDto <API key>() { return new BzOrderPaymentDto(); } /** * Create an instance of {@link WsPageResult } * */ public WsPageResult createWsPageResult() { return new WsPageResult(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzProductDto } * */ public BzProductDto createBzProductDto() { return new BzProductDto(); } /** * Create an instance of {@link BzMerchantCreditDto } * */ public BzMerchantCreditDto <API key>() { return new BzMerchantCreditDto(); } /** * Create an instance of {@link BzOrderDto } * */ public BzOrderDto createBzOrderDto() { return new BzOrderDto(); } /** * Create an instance of {@link BzPaymentTypeDto } * */ public BzPaymentTypeDto <API key>() { return new BzPaymentTypeDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzInvoiceDto } * */ public BzInvoiceDto createBzInvoiceDto() { return new BzInvoiceDto(); } /** * Create an instance of {@link SysUserDto } * */ public SysUserDto createSysUserDto() { return new SysUserDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzPositionDto } * */ public BzPositionDto createBzPositionDto() { return new BzPositionDto(); } /** * Create an instance of {@link BzStockDto } * */ public BzStockDto createBzStockDto() { return new BzStockDto(); } /** * Create an instance of {@link BzDistComCreditDto } * */ public BzDistComCreditDto <API key>() { return new BzDistComCreditDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzStockOrderItemDto } * */ public BzStockOrderItemDto <API key>() { return new BzStockOrderItemDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzMerchantDto } * */ public BzMerchantDto createBzMerchantDto() { return new BzMerchantDto(); } /** * Create an instance of {@link TrProductStockIdDto } * */ public TrProductStockIdDto <API key>() { return new TrProductStockIdDto(); } /** * Create an instance of {@link BzOrderItemDto } * */ public BzOrderItemDto <API key>() { return new BzOrderItemDto(); } /** * Create an instance of {@link BzShelfDto } * */ public BzShelfDto createBzShelfDto() { return new BzShelfDto(); } /** * Create an instance of {@link BzCartItemDto } * */ public BzCartItemDto createBzCartItemDto() { return new BzCartItemDto(); } /** * Create an instance of {@link SysResourceDto } * */ public SysResourceDto <API key>() { return new SysResourceDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzOrderHistoryDto } * */ public BzOrderHistoryDto <API key>() { return new BzOrderHistoryDto(); } /** * Create an instance of {@link BzProductBrandDto } * */ public BzProductBrandDto <API key>() { return new BzProductBrandDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link BzConsumerCreditDto } * */ public BzConsumerCreditDto <API key>() { return new BzConsumerCreditDto(); } /** * Create an instance of {@link BzUserPositionDto } * */ public BzUserPositionDto <API key>() { return new BzUserPositionDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link TrProductStockDto } * */ public TrProductStockDto <API key>() { return new TrProductStockDto(); } /** * Create an instance of {@link <API key> } * */ public <API key> <API key>() { return new <API key>(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteByIdResponse }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteByIdResponse") public JAXBElement<DeleteByIdResponse> <API key>(DeleteByIdResponse value) { return new JAXBElement<DeleteByIdResponse>(<API key>, DeleteByIdResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetById }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getById") public JAXBElement<GetById> createGetById(GetById value) { return new JAXBElement<GetById>(_GetById_QNAME, GetById.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link <API key> }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "<API key>") public JAXBElement<<API key>> <API key>(<API key> value) { return new JAXBElement<<API key>>(<API key>, <API key>.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link <API key> }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "<API key>") public JAXBElement<<API key>> <API key>(<API key> value) { return new JAXBElement<<API key>>(<API key>, <API key>.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link GetByIdResponse }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "getByIdResponse") public JAXBElement<GetByIdResponse> <API key>(GetByIdResponse value) { return new JAXBElement<GetByIdResponse>(<API key>, GetByIdResponse.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link FindListByUserId }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "findListByUserId") public JAXBElement<FindListByUserId> <API key>(FindListByUserId value) { return new JAXBElement<FindListByUserId>(<API key>, FindListByUserId.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link DeleteById }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "deleteById") public JAXBElement<DeleteById> createDeleteById(DeleteById value) { return new JAXBElement<DeleteById>(_DeleteById_QNAME, DeleteById.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link SaveOrUpdate }{@code >}} * */ @XmlElementDecl(namespace = "itaf.framework.ws.server.consumer", name = "saveOrUpdate") public JAXBElement<SaveOrUpdate> createSaveOrUpdate(SaveOrUpdate value) { return new JAXBElement<SaveOrUpdate>(_SaveOrUpdate_QNAME, SaveOrUpdate.class, null, value); } }
<?php # include files from root dir # $root_1 = realpath($_SERVER["DOCUMENT_ROOT"]); $currentdir = getcwd(); $root_2 = str_replace($root_1, '', $currentdir); $root_3 = explode("/", $root_2); if ($root_3[1] == 'core') { echo $root_3[1]; $root = realpath($_SERVER["DOCUMENT_ROOT"]); }else{ $root = $root_1 . '/' . $root_3[1]; } $login_module = "modul_g-plus-login";//need to get extra config for modules include($root.'/core/backend/admin/modules/'.$login_module. '/index.php'); ?>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_111) on Thu Dec 22 11:36:55 CET 2016 --> <title>ch.ethz.inspire.emod.model.units</title> <meta name="date" content="2016-12-22"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ch.ethz.inspire.emod.model.units"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../ch/ethz/inspire/emod/model/thermal/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../ch/ethz/inspire/emod/simulation/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/units/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h1 title="Package" class="title">Package&nbsp;ch.ethz.inspire.emod.model.units</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiConstants.html" title="class in ch.ethz.inspire.emod.model.units">SiConstants</a></td> <td class="colLast"> <div class="block">Implements varoius SI constants</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiUnit.html" title="class in ch.ethz.inspire.emod.model.units">SiUnit</a></td> <td class="colLast"> <div class="block">SI unit class</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/SiUnitDefinition.html" title="class in ch.ethz.inspire.emod.model.units">SiUnitDefinition</a></td> <td class="colLast"> <div class="block">Implementation of the SI definitions</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/ContainerType.html" title="enum in ch.ethz.inspire.emod.model.units">ContainerType</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../../ch/ethz/inspire/emod/model/units/Unit.html" title="enum in ch.ethz.inspire.emod.model.units">Unit</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../ch/ethz/inspire/emod/model/thermal/package-summary.html">Prev&nbsp;Package</a></li> <li><a href="../../../../../../ch/ethz/inspire/emod/simulation/package-summary.html">Next&nbsp;Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?ch/ethz/inspire/emod/model/units/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
import commandRunner as cr import subprocess import glob, os, platform, shutil, adb from pathlib import Path def <API key>(udid): cmd = 'rebot -N Combined --outputdir browserlogs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.system() == "Windows": cmd += os.getcwd() + "\\browserlogs\\" + device + "\output.xml " else: cmd += os.getcwd() + "/browserlogs/" + device + "/output.xml " cr.run_command(cmd) pngs = [] #For screenshot images if platform.system() == "Windows": for idx, device in enumerate(udid): pngs += glob.glob(os.getcwd() + "\\browserlogs\\" + device + "\\" + "*.png") for p in pngs: shutil.copy(p, p.replace(device + "\\", "")) #remove those that have been moved/copied pngs = [p for p in pngs if not p] else: for idx, device in enumerate(udid): pngs += glob.glob(os.getcwd() + "/browserlogs/" + device + "/" + "*.png") for p in pngs: shutil.copy(p, p.replace(device + "/", "")) #remove those that have been moved/copied pngs = [p for p in pngs if not p] def combine_logs(udid): cmd = 'rebot -N Combined --outputdir logs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.system() == "Windows": cmd += os.getcwd() + "\logs\\" + device + "_" + "*\output.xml " else: cmd += os.getcwd() + "/logs/" + device + "_" + "*/output.xml " cr.run_command(cmd) pngs = [] #For screenshot images if platform.system() == "Windows": pngs = glob.glob(os.getcwd() + "\logs\**\*.png") for idx, device in enumerate(udid): for p in pngs: if Path(p).is_file(): #If image exist imgname = p[p.rindex('\\')+1:] k = p.rfind("\logs\\") path = p[:k] newPath = path + "\logs\\" + imgname shutil.move(p,newPath) else: pngs = glob.glob(os.getcwd() + "/logs*.png") for idx, device in enumerate(udid): for p in pngs: if Path(p).is_file(): #If image exist imgname = p[p.rindex('/')+1:] k = p.rfind("/logs/") path = p[:k] newPath = path + "/logs/" + imgname shutil.move(p,newPath) def zip_logs(): if platform.system() == "Windows": cmd = "Compress-Archive logs logs-$(date +%Y-%m-%d-%H%M).zip" subprocess.call(["powershell.exe", cmd]) elif platform.system() == "Linux" or platform.system() == "Darwin": cmd = "zip -vr logs-$(date +%Y-%m-%d-%H%M).zip" + " logs/" cr.run_command(cmd) def zip_browsers_logs(): if platform.system() == "Windows": cmd = "Compress-Archive browserlogs browserlogs-$(date +%Y-%m-%d-%H%M).zip" subprocess.call(["powershell.exe", cmd]) elif platform.system() == "Linux" or platform.system() == "Darwin": cmd = "zip -vr browserlogs-$(date +%Y-%m-%d-%H%M).zip" + " browserlogs/" cr.run_command(cmd) def <API key>():
package com.lh64.randomdungeon.actors.buffs; import com.lh64.randomdungeon.ui.BuffIndicator; import com.lh64.utils.Bundle; public class SnipersMark extends FlavourBuff { public int object = 0; private static final String OBJECT = "object"; @Override public void storeInBundle( Bundle bundle ) { super.storeInBundle( bundle ); bundle.put( OBJECT, object ); } @Override public void restoreFromBundle( Bundle bundle ) { super.restoreFromBundle( bundle ); object = bundle.getInt( OBJECT ); } @Override public int icon() { return BuffIndicator.MARK; } @Override public String toString() { return "Zeroed in"; } }
namespace Maticsoft.TaoBao.Request { using Maticsoft.TaoBao; using Maticsoft.TaoBao.Util; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; public class <API key> : ITopRequest<<API key>> { private IDictionary<string, string> otherParameters; public void AddOtherParameter(string key, string value) { if (this.otherParameters == null) { this.otherParameters = new TopDictionary(); } this.otherParameters.Add(key, value); } public string GetApiName() { return "taobao.simba.adgroup.campcatmatchs.get"; } public IDictionary<string, string> GetParameters() { TopDictionary dictionary = new TopDictionary(); dictionary.Add("campaign_id", this.CampaignId); dictionary.Add("nick", this.Nick); dictionary.Add("page_no", this.PageNo); dictionary.Add("page_size", this.PageSize); dictionary.AddAll(this.otherParameters); return dictionary; } public void Validate() { RequestValidator.ValidateRequired("campaign_id", this.CampaignId); } public long? CampaignId { get; set; } public string Nick { get; set; } public long? PageNo { get; set; } public long? PageSize { get; set; } } }
<?php ?> <?php include("../_includes/start-session.inc.php"); include("../_includes/init.inc.php"); require_once(DIR_ROOT . "classes/Autoloader.php"); <API key>('DomainMOD\Autoloader::classAutoloader'); $system = new DomainMOD\System(); $error = new DomainMOD\Error(); $layout = new DomainMOD\Layout(); $domain = new DomainMOD\Domain(); $time = new DomainMOD\Time(); $form = new DomainMOD\Form(); include(DIR_INC . "head.inc.php"); include(DIR_INC . "config.inc.php"); include(DIR_INC . "software.inc.php"); include(DIR_INC . "settings/queue-add.inc.php"); include(DIR_INC . "database.inc.php"); $system->authCheck($web_root); $system->readOnlyCheck($_SERVER['HTTP_REFERER']); $new_raid = $_REQUEST['new_raid']; $raw_domain_list = $_POST['raw_domain_list']; if ($new_raid != '' ) { $query = "SELECT apir.name, apir.<API key>, apir.<API key>, apir.req_reseller_id, apir.req_api_app_name, apir.req_api_key, apir.req_api_secret, apir.req_ip_address, apir.lists_domains, apir.ret_expiry_date, apir.ret_dns_servers, apir.ret_privacy_status, apir.<API key>, apir.notes, ra.username, ra.password, ra.reseller_id, ra.api_app_name, ra.api_key, ra.api_secret, ra.api_ip_id FROM registrar_accounts AS ra, registrars AS r, api_registrars AS apir WHERE ra.registrar_id = r.id AND r.api_registrar_id = apir.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); $q->bind_result($api_registrar_name, $<API key>, $<API key>, $req_reseller_id, $req_api_app_name, $req_api_key, $req_api_secret, $req_ip_address, $lists_domains, $ret_expiry_date, $ret_dns_servers, $ret_privacy_status, $<API key>, $registrar_notes, $account_username, $account_password, $reseller_id, $api_app_name, $api_key, $api_secret, $api_ip_id); $q->fetch(); $q->close(); } else $error->outputSqlError($conn, "ERROR"); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { $format = new DomainMOD\Format(); $domain_list = $format-><API key>($raw_domain_list); // If the registrar has the ability to retrieve the list of domains if ($lists_domains == '1' && $raw_domain_list == '') { if ($new_raid == '') { if ($new_raid == '') $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>"; } else { $query = "SELECT ra.owner_id, ra.registrar_id, r.api_registrar_id FROM registrar_accounts AS ra, registrars AS r WHERE ra.registrar_id = r.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); $q->bind_result($t_owner_id, $t_registrar_id, $t_api_registrar_id); while ($q->fetch()) { $temp_owner_id = $t_owner_id; $temp_registrar_id = $t_registrar_id; $<API key> = $t_api_registrar_id; } $q->close(); } else $error->outputSqlError($conn, "ERROR"); $query = "INSERT INTO domain_queue_list (api_registrar_id, owner_id, registrar_id, account_id, created_by, insert_time) VALUES (?, ?, ?, ?, ?, ?)"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $timestamp = $time->stamp(); $q->bind_param('iiiiis', $<API key>, $temp_owner_id, $temp_registrar_id, $new_raid, $_SESSION['s_user_id'], $timestamp); $q->execute() or $error->outputSqlError($conn, "Couldn't add registrar account to list queue"); $q->close(); } else $error->outputSqlError($conn, "ERROR"); $_SESSION['<API key>'] = '1'; $_SESSION['s_message_success'] .= "Registrar Account Added To Domain List Queue<BR>"; header("Location: index.php"); exit; } } else { // If the registrar's API DOES NOT have the ability to retrieve the list of domains, or if there's a // problem with he automatic import, use the list supplied // check to make sure that the registrar associated with the account has API support $query = "SELECT ra.id, ra.registrar_id FROM registrar_accounts AS ra, registrars AS r, api_registrars AS ar WHERE ra.registrar_id = r.id AND r.api_registrar_id = ar.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); if ($q->num_rows() == 0) { $query2 = "SELECT registrar_id FROM registrar_accounts WHERE id = ?"; $q2 = $conn->stmt_init(); if ($q2->prepare($query2)) { $q2->bind_param('i', $new_raid); $q2->execute(); $q2->store_result(); $q2->bind_result($t_rid); while ($q2->fetch()) { $temp_registrar_id = $t_rid; } $q2->close(); } else $error->outputSqlError($conn, "ERROR"); $has_api_support = '0'; } else { $has_api_support = '1'; } $q->close(); } else $error->outputSqlError($conn, "ERROR"); if ($new_raid == '' || $raw_domain_list == '' || $has_api_support != '1') { if ($has_api_support != '1' && $new_raid != '') { $_SESSION['s_message_danger'] .= "Either the registrar associated with this account doesn't have API support, or you haven't yet updated the registrar to indicate API support.<BR><BR>Please check the <a href='" . $web_root . "/assets/edit/registrar.php?rid=" . $temp_registrar_id . "'>registrar</a> and try again."; } else { if ($new_raid == '') $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>"; if ($raw_domain_list == '') $_SESSION['s_message_danger'] .= "Enter the list of domains to add to the queue<BR>"; } } else { list($invalid_to_display, $invalid_domains, $invalid_count, $temp_result_message) = $domain->findInvalidDomains($domain_list); if ($raw_domain_list == "" || $invalid_domains == 1) { if ($invalid_domains == 1) { if ($invalid_count == 1) { $_SESSION['s_message_danger'] .= "There is " . number_format($invalid_count) . " invalid domain on your list<BR><BR>" . $temp_result_message; } else { $_SESSION['s_message_danger'] .= "There are " . number_format($invalid_count) . " invalid domains on your list<BR><BR>" . $temp_result_message; if (($invalid_count - $invalid_to_display) == 1) { $_SESSION['s_message_danger'] .= "<BR>Plus " . number_format($invalid_count - $invalid_to_display) . " other<BR>"; } elseif (($invalid_count - $invalid_to_display) > 1) { $_SESSION['s_message_danger'] .= "<BR>Plus " . number_format($invalid_count - $invalid_to_display) . " others<BR>"; } } } else { $_SESSION['s_message_danger'] .= "Enter the list of domains to add to the queue<BR>"; } $submission_failed = 1; } else { $date = new DomainMOD\Date(); reset($domain_list); // cycle through domains here while (list($key, $new_domain) = each($domain_list)) { $query = "SELECT domain FROM domains WHERE domain = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('s', $new_domain); $q->execute(); $q->store_result(); if ($q->num_rows() > 0) { $<API key> = '1'; } } } reset($domain_list); // cycle through domains here while (list($key, $new_domain) = each($domain_list)) { $query = "SELECT domain FROM domain_queue WHERE domain = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('s', $new_domain); $q->execute(); $q->store_result(); if ($q->num_rows() > 0) { $<API key> = '1'; } } } if ($new_raid == "" || $new_raid == "0" || $<API key> == '1' || $<API key> == '1') { if ($<API key> == '1') $_SESSION['s_message_danger'] .= "At least one of the domains you entered already exists in " . $software_title . ".<BR><BR>You should run the domain list through a Segment filter to determine which one(s).<BR><BR>"; if ($<API key> == '1') $_SESSION['s_message_danger'] .= "At least one of the domains you entered is already in the domain queue.<BR>"; if ($new_raid == "" || $new_raid == "0") $_SESSION['s_message_danger'] .= "Please choose the registrar account<BR>"; $submission_failed = 1; } else { $query = "SELECT ra.owner_id, ra.registrar_id, r.api_registrar_id FROM registrar_accounts AS ra, registrars AS r WHERE ra.registrar_id = r.id AND ra.id = ?"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $q->bind_param('i', $new_raid); $q->execute(); $q->store_result(); $q->bind_result($t_oid, $t_rid, $t_apirid); while ($q->fetch()) { $temp_owner_id = $t_oid; $temp_registrar_id = $t_rid; $<API key> = $t_apirid; } $q->close(); } else $error->outputSqlError($conn, "ERROR"); reset($domain_list); // cycle through domains here while (list($key, $new_domain) = each($domain_list)) { $domain_temp = new DomainMOD\Domain(); $new_tld = $domain_temp->getTld($new_domain); $query = "INSERT INTO domain_queue (api_registrar_id, domain, owner_id, registrar_id, account_id, tld, created_by, insert_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $q = $conn->stmt_init(); if ($q->prepare($query)) { $timestamp = $time->stamp(); $q->bind_param('isiiisis', $<API key>, $new_domain, $temp_owner_id, $temp_registrar_id, $new_raid, $new_tld, $_SESSION['s_user_id'], $timestamp); $q->execute() or $error->outputSqlError($conn, "Couldn't add domains to queue"); $q->close(); } else $error->outputSqlError($conn, "ERROR"); } // finish cycling through domains here $done = "1"; reset($domain_list); $<API key> = implode(", ", $domain_list); $_SESSION['s_domains_in_queue'] = '1'; $_SESSION['s_message_success'] .= "Domains Added To Queue<BR>"; } } } } } ?> <?php include(DIR_INC . 'doctype.inc.php'); ?> <html> <head> <title><?php echo $system->pageTitle($software_title, $page_title); ?></title> <?php include(DIR_INC . "layout/head-tags.inc.php"); ?> <?php echo $layout->jumpMenu(); ?> </head> <body class="hold-transition skin-red sidebar-mini"> <?php include(DIR_INC . "layout/header.inc.php"); ?> <?php if ($done == "1") { if ($submission_failed != "1") { ?> <strong>The following domains were added to the queue:</strong><BR> <?php echo htmlentities($<API key>, ENT_QUOTES, 'UTF-8'); ?><BR><BR><?php } } ?> <strong>Domain Queue & API Prerequisites</strong><BR> Before you can add domains to DomainMOD using the Domain Queue you must first do the following: <ol> <li>Ensure that the registrar has an API and that your account has been granted access to it</li> <li>Enable API Support on the <a href="<?php echo $web_root; ?>/assets/registrars.php">registrar asset</a></li> <li>Save the required API credentials with the <a href="<?php echo $web_root; ?>/assets/registrar-accounts.php">registrar account asset</a></li> </ol><?php echo $form->showFormTop(''); echo $form->showDropdownTopJump('', '', '', ''); $sql_account = "SELECT ra.id, ra.username, o.name AS o_name, r.name AS r_name FROM registrar_accounts AS ra, owners AS o, registrars AS r WHERE ra.owner_id = o.id AND ra.registrar_id = r.id AND r.api_registrar_id != '0' ORDER BY r_name, o_name, ra.username"; $result_account = mysqli_query($connection, $sql_account) or $error->outputOldSqlError($connection); echo $form-><API key>('add.php', '', 'Choose the Registrar Account to import', ''); while ($row_account = mysqli_fetch_object($result_account)) { echo $form-><API key>('add.php?new_raid=', $row_account->id, $row_account->r_name . ', ' . $row_account->o_name . ' (' . $row_account->username . ')', $new_raid); } echo $form->showDropdownBottom(''); if ($new_raid != '') { ?> <strong>API Requirements</strong><BR> <?php echo $api_registrar_name; ?> requires the following credentials in order to use their API. These credentials must to be saved with the <a href="<?php echo $web_root; ?>/assets/edit/registrar-account.php?raid=<?php echo urlencode($new_raid); ?>">registrar account asset</a>. <ul><?php $missing_text = ' (<a href="' . $web_root . '/assets/edit/registrar-account.php?raid=' . htmlentities($new_raid, ENT_QUOTES, 'UTF-8') . '"><span style="color: #a30000"><strong>missing - click here to enter</strong></span></a>)'; $saved_text = ' (<span style="color: darkgreen"><strong>saved</strong></span>)'; if ($<API key> == '1') { echo '<li>Registrar Account Username'; if ($account_username == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($<API key> == '1') { echo '<li>Registrar Account Password'; if ($account_password == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_reseller_id == '1') { echo '<li>Reseller ID'; if ($reseller_id == '' || $reseller_id == '0') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_api_app_name == '1') { echo '<li>API Application Name'; if ($api_app_name == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_api_key == '1') { echo '<li>API Key'; if ($api_key == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_api_secret == '1') { echo '<li>API Secret'; if ($api_secret == '') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } if ($req_ip_address == '1') { echo '<li>Connecting IP Address'; if ($api_ip_id == '0') { echo $missing_text; } else { echo $saved_text; } echo '</li>'; } ?> </ul><?php } if ($registrar_notes != '') { echo '<strong>Registrar Notes</strong><BR>'; echo $registrar_notes . "<BR><BR>"; } if ($new_raid != '') { if ($lists_domains == '1') { echo '<strong>Domain List</strong><BR>'; echo htmlentities($api_registrar_name, ENT_QUOTES, 'UTF-8') . '\'s API has a domain list feature, so you don\'t even have to supply a list of the domains you want to import, DomainMOD will retrieve them for you automatically. If for some reason you\'re having issues with the automatic import though, you can still manually paste a list of domains to import below.<BR><BR>'; echo $form->showInputTextarea('raw_domain_list', '[OPTIONAL] Domains to add (one per line)', '', $raw_domain_list, '', '', ''); } else { echo $form->showInputTextarea('raw_domain_list', 'Domains to add (one per line)', '', $raw_domain_list, '1', '', ''); } } if ($new_raid != '') { echo $form->showSubmitButton('Add Domains', '', ''); } echo $form->showInputHidden('new_raid', $new_raid); echo $form->showFormBottom(''); ?> <?php include(DIR_INC . "layout/footer.inc.php"); ?> </body> </html>
# 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 ''' hello Usage: hello (--help | --version) Options: --help -h display this help message and exit --version print version information and exit ''' import sys import docopt import hello def main(argv=sys.argv[1:]): try: docopt.docopt(__doc__, argv=argv, version=hello.__version__) except docopt.DocoptExit as e: print(str(e), file=sys.stderr) return 2 except SystemExit as e: return 0 if __name__ == "__main__": # pragma: no cover sys.exit(main())
#include <iostream> #include <iomanip> #include <fstream> #include <algorithm> #include <iterator> #include <cmath> #include <boost/filesystem.hpp> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Eigenvalues> #include "constants.h" #include "utilities.h" /* * Call this program like: * * ./mctdh_specinput <dE> <threshold> * * dE: the adiabatic electronic excitation energy in eV * threshold: the cutoff threshold for including terms in * the Hamiltonian (optional, default zero) * * The following files must be present in the working directory: * * 'gs_freqs' the ground and excited state normal mode frequencies in cm-1 * 'es_freqs' * 'Displacement_Vector.dat' the vector K and the matrix J as output from FCClasses * 'Duschinsky_Matrix.dat' */ int main(int argc, char *argv[]) { /* * Test for the command arguments: */ if (argc < 2) { std::cerr << "ERROR: wrong number of arguments\n"; return 2; } double dE = atof(argv[1]); /* * Test for existence of the required files. */ std::ifstream gsfc("gs_freqs", std::ifstream::in); if (!gsfc.good()) { std::cerr << "ERROR: File 'gs_freqs' could not be opened." << std::endl; return 1; } std::ifstream esfc("es_freqs", std::ifstream::in); if (!esfc.good()) { std::cerr << "ERROR: File 'es_freqs' could not be opened." << std::endl; return 1; } std::ifstream shift("Displacement_Vector.dat", std::ifstream::in); if (!shift.good()) { std::cerr << "ERROR: File 'Displacement_Vector.dat' could not be opened." << std::endl; return 1; } std::ifstream dusch("Duschinsky_Matrix.dat", std::ifstream::in); if (!dusch.good()) { std::cerr << "ERROR: File 'Duschinsky_Matrix.dat' could not be opened." << std::endl; return 1; } /* * Get the number of lines (aka normal modes) in the ground state mode file. * Check, if the excited state mode file contains the same number of modes. */ int Nmodes = std::count(std::istreambuf_iterator<char>(gsfc), std::istreambuf_iterator<char>(), '\n'); if (std::count(std::istreambuf_iterator<char>(esfc), std::istreambuf_iterator<char>(), '\n') != Nmodes) { std::cerr << "ERROR: The files 'gs_freqs' and 'es_freqs' do not contain the same number of lines." << std::endl; return 1; } gsfc.seekg(0); // jump back to start of file esfc.seekg(0); /* * Read the ground and excited state frequencies * as well as the Displacement Vector and the Duschinsky Matrix. */ Eigen::VectorXd v1(Nmodes); Eigen::VectorXd v2(Nmodes); Eigen::VectorXd Korig(Nmodes), K(Nmodes); Eigen::MatrixXd Jorig(Nmodes, Nmodes), J(Nmodes, Nmodes); for (int i = 0; i < 2; i++) shift.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip the first two lines in the K file for (int i = 0; i < 5; i++) dusch.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // and the first five lines in the J file for (int i = 0; i < Nmodes; i++) { int dummyIndex, dummyIndex2; gsfc >> v1(i); esfc >> v2(i); shift >> dummyIndex >> Korig(i); for (int j = 0; j < Nmodes; j++) dusch >> dummyIndex >> dummyIndex2 >> Jorig(j,i); } /* * Calculate our J/K quantities from the FCClasses ones. */ J = Jorig.transpose(); K = -Jorig.transpose() * Korig; /* * Calculate the force constants from the frequencies. */ Eigen::VectorXd f1(Nmodes); Eigen::VectorXd f2(Nmodes); /* * conversion from wavenumbers in cm-1 to mass-weighted force constants * in atomic units * * fac = 4 pi**2 * c**2 * (100 cm/m)**2 * me**2 * a0**4 / hbar**2 */ double factor = 40000.0 * M_PI * M_PI * c0 * c0 * me * me * a0 * a0 * a0 * a0 / (hbar * hbar); for (int i = 0; i < Nmodes; i++) { f1(i) = v1(i) * v1(i) * factor; f2(i) = v2(i) * v2(i) * factor; } /* * Calculate the zero-point energies of the two states and print them out. */ double zpe1 = 0.0; double zpe2 = 0.0; for (int i = 0; i < Nmodes; i++) { zpe1 += 0.5 * sqrt(f1(i)); zpe2 += 0.5 * sqrt(f2(i)); } /* * Open the log file and write some statistics: */ std::ofstream logFile("log"); logFile << "Electronic transition energy: " << dE << std::endl; logFile << "Number of normal modes: " << Nmodes << std::endl; logFile << "Ground state force constants:\n"; Utils::WriteVectorToFile(logFile, f1); logFile << "Excited state force constants:\n"; Utils::WriteVectorToFile(logFile, f2); logFile << "Ground state zero-point Energy: " << zpe1 << "Eh\n"; logFile << "Excited state zero-point Energy: " << zpe2 << "Eh\n"; logFile << "Original Displacement Vector from FCClasses:\n"; Utils::WriteVectorToFile(logFile, Korig); logFile << "Original Duschinsky Matrix from FCClasses:\n"; Utils::WriteMatrixToFile(logFile, Jorig); logFile << "Displacement Vector:\n"; Utils::WriteVectorToFile(logFile, K); logFile << "Duschinsky Matrix:\n"; Utils::WriteMatrixToFile(logFile, J, 3, true); logFile << "Metric of the Duschinsky Matrix:\n"; Utils::WriteMatrixToFile(logFile, J.transpose() * J, 3, true); logFile << "Frobenius norm of the Duschinsky matrix: " << J.norm() << std::endl; logFile << "Determinant of the Duschinsky matrix: " << J.determinant() << std::endl; Eigen::VectorXd fp(Nmodes); for (int m = 0; m < Nmodes; m++) { fp(m) = 0.0; for (int n = 0; n < Nmodes; n++) fp(m) += f2(n) * J(n,m) * J(n,m); } /* * Calculate the first-order coefficients. */ Eigen::VectorXd kappa(Nmodes); for (int m = 0; m < Nmodes; m++) { kappa(m) = 0.0; for (int n = 0; n < Nmodes; n++) kappa(m) += f2(n) * K(n) * J(n,m); } /* * Calculate the couplings. */ Eigen::MatrixXd phi(Eigen::MatrixXd::Zero(Nmodes,Nmodes)); Eigen::MatrixXd phiFull(Eigen::MatrixXd::Zero(Nmodes,Nmodes)); for (int m = 0; m < Nmodes; m++) { for (int o = m + 1; o < Nmodes; o++) { phi(m,o) = 0.0; phiFull(m,o) = 0.0; for (int n = 0; n < Nmodes; n++) phi(m,o) += f2(n) * J(n,m) * J(n,o); phiFull(m,o) = phi(m,o); phiFull(o,m) = phi(m,o); } phiFull(m,m) = fp(m); } /* * Calculate the energy shifts. */ Eigen::VectorXd d(Nmodes); for (int i = 0; i < Nmodes; i++) d(i) = (0.5 * f2(i) * K(i) * K(i)); /* * write the coupling matrix to the log file: */ logFile << "Coupling matrix phi with the force constants fp on the diagonal:\n"; Utils::WriteMatrixToFile(logFile, phiFull, 3, true); std::cout << "Enter the base-name for the MCTDH files to be generated.\nThe files <name>.inp and <name>.op will then be written.\n>>> "; std::string basename; std::cin >> basename; std::string inputFileName = basename + ".inp"; std::string operatorFileName = basename + ".op"; if (boost::filesystem::exists(inputFileName) || boost::filesystem::exists(operatorFileName)) { std::cout << "One of the MCTDH files already exists. Should they be overwritten? (Y/N)\n>>> "; char answer; std::cin >> answer; if (answer == 'N' || answer == 'n') return 0; } std::ofstream inputFile(inputFileName); std::ofstream operatorFile(operatorFileName); inputFile.precision(1); operatorFile.precision(8); /* * The run-section */ inputFile << "run-section\n"; inputFile << " name =\n"; inputFile << " propagation\n"; inputFile << " tfinal =\n"; inputFile << " tout =\n"; inputFile << " tpsi =\n"; inputFile << " psi gridpop auto steps graphviz\n"; inputFile << "end-run-section\n\n"; /* * The operator-section */ inputFile << "operator-section\n"; inputFile << " opname = " << basename << std::endl; inputFile << "<API key>\n\n"; /* * The mlbasis-section */ // rearrange the modes in order of decreasing coupling Eigen::MatrixXd phi_sort = phi.cwiseAbs(); std::vector<int> sortedModes; while (phi_sort.norm() > 0.0) { Eigen::MatrixXd::Index maxRow, maxCol; phi_sort.maxCoeff(&maxRow, &maxCol); phi_sort(maxRow, maxCol) = 0.0; if (std::find(sortedModes.begin(), sortedModes.end(), maxRow) == sortedModes.end()) sortedModes.push_back(maxRow); if (std::find(sortedModes.begin(), sortedModes.end(), maxCol) == sortedModes.end()) sortedModes.push_back(maxCol); } // determine the required number of layers int layers = 1; while (pow(2.0, layers) < Nmodes) layers++; layers // determine the number of nodes in each layer std::vector<int> nodesPerLayer(layers); nodesPerLayer.at(layers - 1) = Nmodes / 2; for (int i = layers - 1; i > 0; i { nodesPerLayer.at(i - 1) = nodesPerLayer.at(i) / 2; } inputFile << "mlbasis-section\n"; for (int i = 0; i < Nmodes - 1; i += 2) { if (sortedModes.size() - i == 3) inputFile << " [q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i) + 1 << " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+1) + 1 << " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+2) + 1 << "]\n"; else inputFile << " [q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i) + 1 << " q_" << std::setfill('0') << std::setw(3) << sortedModes.at(i+1) + 1 << "]\n"; } inputFile << "end-mlbasis-section\n\n"; /* * The pbasis-section */ inputFile << "pbasis-section\n"; for (int i = 0; i < Nmodes; i++) inputFile << " q_" << std::setfill('0') << std::setw(3) << i + 1 << " ho " << std::setw(3) << std::setfill(' ') << lrint(-0.8 * log(fp(i))) << " xi-xf " // the basis boundarie are -kappa / fp +- 4 / fp**1/4 << std::fixed << std::setfill(' ') << std::setw(8) << -(kappa(i) / fp(i)) - (2.1 / pow(fp(i), 0.305)) << std::fixed << std::setfill(' ') << std::setw(8) << -(kappa(i) / fp(i)) + (2.1 / pow(fp(i), 0.305)) << std::endl; inputFile << "end-pbasis-section\n\n"; /* * The integrator section */ inputFile << "integrator-section\n"; inputFile << " vmf\n"; inputFile << " abm = 6, 1.0d-7, 0.01d0\n"; inputFile << "<API key>\n\n"; /* * The init wf section */ inputFile << "init_wf-section\n"; inputFile << " build\n"; for (int i = 0; i < Nmodes; i++) inputFile << " q_" << std::setfill('0') << std::setw(3) << i + 1 << " eigenf" << " Eq_" << std::setfill('0') << std::setw(3) << i + 1 << " pop = 1\n"; inputFile << " end-build\n"; inputFile << "end-init_wf-section\n\n"; inputFile << "end-input\n\n"; /* * Now the operator file * * First the op-define section */ operatorFile << "op_define-section\n"; operatorFile << " title\n"; operatorFile << " " << basename << std::endl; operatorFile << " end-title\n"; operatorFile << "<API key>\n\n"; /* * The parameter section */ operatorFile << "parameter-section\n"; // the masses for (int i = 0; i < Nmodes; i++) operatorFile << " mass_q_" << std::setfill('0') << std::setw(3) << i + 1 << " = 1.0\n"; // the ground state force constants for (int i = 0; i < Nmodes; i++) { operatorFile << " f1_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, f1(i)); operatorFile << std::endl; } // the excited state force constants for (int i = 0; i < Nmodes; i++) { operatorFile << " f2_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, f2(i)); operatorFile << std::endl; } // the new effective excited state force constants for (int i = 0; i < Nmodes; i++) { operatorFile << " fp_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, fp(i)); operatorFile << std::endl; } // the couplings for (int i = 0; i < Nmodes; i++) for (int j = i + 1; j < Nmodes; j++) { operatorFile << " phi_" << std::setfill('0') << std::setw(3) << i + 1 << "_" << std::setfill('0') << std::setw(3) << j + 1 << " = "; Utils::WriteFortranNumber(operatorFile, phi(i,j)); operatorFile << std::endl; } // the first-order coefficients (shifts) for (int i = 0; i < Nmodes; i++) { operatorFile << " kappa_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, kappa(i)); operatorFile << std::endl; } // the energy offsets for (int i = 0; i < Nmodes; i++) { operatorFile << " d_" << std::setfill('0') << std::setw(3) << i + 1 << " = "; Utils::WriteFortranNumber(operatorFile, d(i)); operatorFile << std::endl; } // the electronic offset minus the ground state ZPE operatorFile << " dE = "; Utils::WriteFortranNumber(operatorFile, dE / Eh2eV - zpe1); operatorFile << "\<API key>\n\n"; /* * The hamiltonian section */ operatorFile << "hamiltonian-section"; for (int i = 0; i < Nmodes; i++) { if (i % 8 == 0) operatorFile << std::endl << "modes"; operatorFile << " | q_" << std::setfill('0') << std::setw(3) << i + 1; } operatorFile << std::endl; for (int i = 0; i < Nmodes; i++) operatorFile << "1.0 |" << i + 1 << " KE\n"; for (int i = 0; i < Nmodes; i++) operatorFile << "0.5*fp_" << std::setfill('0') << std::setw(3) << i + 1 << " |" << i + 1 << " q^2\n"; for (int i = 0; i < Nmodes; i++) for (int j = i + 1; j < Nmodes; j++) operatorFile << "phi_" << std::setfill('0') << std::setw(3) << i + 1 << "_" << std::setfill('0') << std::setw(3) << j + 1 << " |" << i + 1 << " q" << " |" << j + 1 << " q\n"; for (int i = 0; i < Nmodes; i++) operatorFile << "kappa_" << std::setfill('0') << std::setw(3) << i + 1 << " |" << i + 1 << " q\n"; for (int i = 0; i < Nmodes; i++) operatorFile << "d_" << std::setfill('0') << std::setw(3) << i + 1 << " |" << i + 1 << " 1\n"; operatorFile << "dE |1 1\n"; operatorFile << "<API key>\n\n"; /* * One-dimensional Hamiltonians for the ground state normal modes */ for (int i = 0; i < Nmodes; i++) { operatorFile << "<API key>" << std::setfill('0') << std::setw(3) << i + 1 << std::endl; operatorFile << "usediag\n"; operatorFile << "modes | q_" << std::setfill('0') << std::setw(3) << i + 1 << std::endl; operatorFile << "1.0 |1 KE\n"; operatorFile << "0.5*f1_" << std::setfill('0') << std::setw(3) << i + 1 << " |1 q^2\n"; operatorFile << "<API key>\n\n"; } operatorFile << "end-operator\n"; /* * Diagonalize the coupling matrix to get the force constants back */ Eigen::<API key><Eigen::MatrixXd> phiSolv(phiFull); logFile << "Eigenvalues of the full force constant / coupling matrix:\n"; Utils::WriteVectorToFile(logFile, phiSolv.eigenvalues()); /* * Solve the linear system of the full coupling matrix and the kappa vector * to get the coordinates of the minimum */ Eigen::ColPivHouseholderQR<Eigen::MatrixXd> phiLin(phiFull); Eigen::VectorXd minima = phiLin.solve(-kappa); logFile << "minimum coordinates\n"; Utils::WriteVectorToFile(logFile, minima); /* * calculate the potential energy at the minimum */ double Emin = 0.0; // first, quadratic term: for (int i = 0; i < Nmodes; i++) Emin += 0.5 * fp(i) * minima(i) * minima(i); // second, coupling term: for (int i = 0; i < Nmodes; i++) for (int j = i + 1; j < Nmodes; j++) Emin += phi(i,j) * minima(i) * minima(j); // third, displacement term: for (int i = 0; i < Nmodes; i++) Emin += kappa(i) * minima(i); // fourth, constant term: for (int i = 0; i < Nmodes; i++) Emin += d(i); logFile << "Energy at minimum: " << Emin << std::endl; /* * Calculate the 1st moment of the spectrum analytically */ double moment = dE; for (int i = 0; i < Nmodes; i++) moment += 0.25 * (fp(i) - f1(i)) / sqrt(f1(i)); std::cout << "1st moment of the spectrum: " <<std::setprecision(8) << moment << std::endl; return 0; }
CREATE TABLE IF NOT EXISTS `stena` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_user` int(11) NOT NULL, `id_stena` int(11) NOT NULL, `time` int(11) NOT NULL, `msg` varchar(1024) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `read` int(11) DEFAULT '1', PRIMARY KEY (`id`), KEY `time` (`time`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `stena_like` ( `id` int(11) NOT NULL AUTO_INCREMENT, `id_user` int(11) NOT NULL, `id_stena` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
#!/bin/sh # split must fail when given length/count of zero. # 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 . "${srcdir=.}/tests/init.sh"; path_prepend_ ./src print_ver_ split getlimits_ touch in || framework_failure_ split -a 0 in 2> /dev/null || fail=1 returns_ 1 split -b 0 in 2> /dev/null || fail=1 returns_ 1 split -C 0 in 2> /dev/null || fail=1 returns_ 1 split -l 0 in 2> /dev/null || fail=1 returns_ 1 split -n 0 in 2> /dev/null || fail=1 returns_ 1 split -n 1/0 in 2> /dev/null || fail=1 returns_ 1 split -n 0/1 in 2> /dev/null || fail=1 returns_ 1 split -n 2/1 in 2> /dev/null || fail=1 # Make sure -C doesn't create empty files. rm -f x?? || fail=1 echo x | split -C 1 || fail=1 test -f xaa && test -f xab || fail=1 test -f xac && fail=1 # Make sure that the obsolete -N notation still works split -1 in 2> /dev/null || fail=1 # Then make sure that -0 evokes a failure. returns_ 1 split -0 in 2> /dev/null || fail=1 split --lines=$UINTMAX_MAX in || fail=1 split --bytes=$OFF_T_MAX in || fail=1 returns_ 1 split --line-bytes=$OFF_T_OFLOW 2> /dev/null in || fail=1 returns_ 1 split --line-bytes=$SIZE_OFLOW 2> /dev/null in || fail=1 if truncate -s$SIZE_OFLOW large; then # Ensure we can split chunks of a large file on 32 bit hosts split --number=$SIZE_OFLOW/$SIZE_OFLOW large >/dev/null || fail=1 fi split --number=r/$UINTMAX_MAX/$UINTMAX_MAX </dev/null >/dev/null || fail=1 returns_ 1 split --number=r/$UINTMAX_OFLOW </dev/null 2>/dev/null || fail=1 # Make sure that a huge obsolete option evokes the right failure. split -<API key> 2> out # On losing systems (x86 Solaris 5.9 c89), we get a message like this: # split: line count option -9999999999... is too large # while on most, we get this: # split: line count option -<API key>... is too large # so map them both to -99*. sed 's/99[19]*/99*/' out > out-t mv -f out-t out cat <<\EOF > exp split: line count option -99*... is too large EOF compare exp out || fail=1 # Make sure split fails when it can't read input # (the current directory in this case) if ! cat . >/dev/null; then # can't read() directories returns_ 1 split . || fail=1 fi Exit $fail
#ifndef <API key> #define <API key> #include <QColor> #include <QJsonObject> #include <QPainter> #include <rpgmapper/layer/layer.hpp> // fwd namespace rpgmapper::model { class Map; } namespace rpgmapper::model::layer { /** * Objects of the GridLayer class draw grids on a map. */ class GridLayer : public Layer { Q_OBJECT public: /** * Constructs a new GridLayer. * * @param map the map this layer belongs to. */ explicit GridLayer(rpgmapper::model::Map * map); /** * Destructs the GridLayer. */ ~GridLayer() override = default; /** * Draws the grid onto the map. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void draw(QPainter & painter, int tileSize) const override; /** * Gets the color of the grid. * * @return the color used to paint the grid on the map. */ QColor getColor() const; /** * Extracts this layer as JSON object. * * @return a JSON object holding the layer data. */ QJsonObject getJSON() const override; /** * Applies a new grid color. * * @param color the new grid color. */ void setColor(QColor color); signals: /** * The grid color has changed. * * @param color the new grid color. */ void gridColorChanged(QColor color); private: /** * Draws the map border. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void drawBorder(QPainter & painter, int tileSize) const; /** * Draws all X-axis. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void drawXAxis(QPainter & painter, int tileSize) const; /** * Draws all Y-axis. * * @param painter the painter used for drawing. * @param tileSize the size of a single tile square side in pixels. */ void drawYAxis(QPainter & painter, int tileSize) const; }; } #endif
<?php // This is a SPIP language file -- Ceci est un fichier langue de SPIP // ** ne pas modifier le fichier ** if (!defined("_ECRIRE_INC_VERSION")) return; $GLOBALS[$GLOBALS['idx_lang']] = array( 'bouton_effacer' => 'L&ouml;schen', '<API key>' => 'Auf den neuesten Stand bringen', 'bouton_reset' => 'Zur&uuml;cksetzen', 'cfg' => 'CFG', '<API key>' => 'W&auml;hlen Sie das zu konfigurierende Modul', 'config_enregistree' => 'Speicherung von <b>@nom@</b> erfolgreich', 'config_supprimee' => 'L&ouml;schen von <b>@nom@</b> erfolgreich', '<API key>' => 'Konfiguration der Module', '<API key>' => 'Die Datei @fichier@ kann nicht an ihren Zielort kopiert werden.', '<API key>' => 'Ein Fehler ist aufgetreten beim Speichern von <b>@nom@</b>', 'erreur_lecture' => 'Fehler beim Lesen von @nom@', '<API key>' => 'Fehler beim &Ouml;ffnen der Datei @fichier@ zum Schreiben', 'erreur_suppression' => 'Ein Fehler ist aufgetreten beim L&ouml;schen von <b>@nom@</b>', '<API key>' => 'Die Datei @fichier@ kann nicht gel&ouml;scht werden.', 'erreur_type_id' => 'Das Feld @champ@ muss mit einem Buchstaben oder einem Unterstrich beginnen.', 'erreur_type_idnum' => 'Das Feld @champ@ muss numerisch sein.', 'erreur_type_pwd' => 'Das Feld @champ@ ben&ouml;tigt mindestens 5 Zeichen.', 'id_manquant' => 'Fehlende ID', '<API key>' => 'Herunterladen der Bibliotheken', '<API key>' => 'Liste der Bibliotheken', '<API key>' => 'Sie m&uuml;ssen ein beschreibbares Verzeichnis mit dem Namen @dir@ im Wurzelverzeichnis Ihrer SPIP-Website anlegen.', 'installer_lib_192' => 'Um eine Bibliothek zu installieren, entpacken Sie die ZIP-Datei manuell und kopieren Sie den Inhalt des Archivs in das Verzeichnis @dir@.', 'label_activer' => 'Aktivieren', 'label_obligatoire' => 'Pflichtfeld', 'nom_table_manquant' => 'Fehlender Name der SQL Tabelle', 'nouveau' => 'Neu', 'ok' => 'OK', 'pas_de_champs_dans' => 'Kein Feld in @nom@ gefunden', 'pas_de_changement' => 'Keine &Auml;nderung in <b>@nom@</b>', '<API key>' => 'Nur die Administratoren der Site d&uuml;rfen diese Einstellungen &auml;ndern.', '<API key>' => 'Nur ein Webmaster darf diese EInstellungen bearbeiten.', 'reset' => 'Reset', 'supprimer' => '<API key> wieder herstellen' ); ?>
var searchData= [ ['handler_5fallocator',['handler_allocator',['../<API key>.html',1,'websocketpp::transport::asio']]], ['hash32',['Hash32',['../<API key>.html',1,'nfd::name_tree']]], ['hash64',['Hash64',['../<API key>.html',1,'nfd::name_tree']]], ['<API key>',['hash&lt; ndn::Name &gt;',['../<API key>.html',1,'std']]], ['<API key>',['hash&lt; ndn::util::ethernet::Address &gt;',['../<API key>.html',1,'std']]], ['hashable',['Hashable',['../<API key>.html',1,'ndn']]], ['header',['Header',['../<API key>.html',1,'ndn::lp::field_location_tags']]], ['hierarchicalchecker',['HierarchicalChecker',['../<API key>.html',1,'ndn::security::conf']]], ['hijacker',['Hijacker',['../<API key>.html',1,'ns3']]], ['httpexception',['HttpException',['../classHttpException.html',1,'']]], ['hybi00',['hybi00',['../<API key>.html',1,'websocketpp::processor']]], ['<API key>',['hybi00&lt; stub_config &gt;',['../<API key>.html',1,'websocketpp::processor']]], ['hybi07',['hybi07',['../<API key>.html',1,'websocketpp::processor']]], ['hybi08',['hybi08',['../<API key>.html',1,'websocketpp::processor']]], ['hybi13',['hybi13',['../<API key>.html',1,'websocketpp::processor']]], ['<API key>',['hybi13&lt; stub_config &gt;',['../<API key>.html',1,'websocketpp::processor']]], ['<API key>',['hybi13&lt; stub_config_ext &gt;',['../<API key>.html',1,'websocketpp::processor']]], ['<API key>',['<API key>',['../<API key>.html',1,'ndn::security::conf']]] ];
#ifndef QT_NO_DEBUG #include <QDebug> #endif #include "progressPie.h" #include "../../../constants.h" #include <QPaintEvent> #include <QPainter> #include <QLineEdit> // INIT ProgressPie::ProgressPie(QWidget* parent) : QWidget(parent), _value(Constants::<API key>), _pRedBrush(new QBrush(Qt::red)), _pGreenBrush(new QBrush(Qt::darkGreen)) { /* * we want this widget to be enclosed within a square that has the same * height as a default QLineEdit. */ QLineEdit <API key>; int size = <API key>.sizeHint().height(); setFixedSize(size, size); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } ProgressPie::~ProgressPie() { delete _pGreenBrush; delete _pRedBrush; } // OVERRIDES void ProgressPie::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setPen(Qt::NoPen); painter.setRenderHint(QPainter::Antialiasing, true); /* * Qt draws angles with 1/16 degree precision. */ static const int STEPS = 16; static const int TOP = -270* STEPS ; /* * how many degrees in a full circle ? */ static const int FULL_CIRCLE = 360; /* * draw red circle */ painter.setBrush(*_pRedBrush); painter.drawEllipse(this->visibleRegion().boundingRect()); /* * draw green pie */ painter.setBrush(*_pGreenBrush); painter.drawPie(this->visibleRegion().boundingRect(), TOP, static_cast<int> (-FULL_CIRCLE * _value * STEPS)); event->accept(); } // SLOTS void ProgressPie::setValue(const double value) { _value = value; repaint(); }
package com.dotmarketing.servlets; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dotcms.repackage.commons_lang_2_4.org.apache.commons.lang.time.FastDateFormat; import com.dotmarketing.util.Constants; import com.dotmarketing.util.Logger; import com.liferay.util.FileUtil; public class IconServlet extends HttpServlet { private static final long serialVersionUID = 1L; FastDateFormat df = FastDateFormat.getInstance(Constants.RFC2822_FORMAT, TimeZone.getTimeZone("GMT"), Locale.US); protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String i = request.getParameter("i"); if(i !=null && i.length() > 0 && i.indexOf('.') < 0){ i="." + i; } String icon = com.dotmarketing.util.UtilMethods.getFileExtension(i); java.text.SimpleDateFormat httpDate = new java.text.SimpleDateFormat(Constants.RFC2822_FORMAT, Locale.US); httpDate.setTimeZone(TimeZone.getDefault()); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.setTime(new Date(0)); Date _lastModified = c.getTime(); String _eTag = "dot:icon-" + icon + "-" + _lastModified.getTime() ; String ifModifiedSince = request.getHeader("If-Modified-Since"); String ifNoneMatch = request.getHeader("If-None-Match"); /* * If the etag matches then the file is the same * */ if(ifNoneMatch != null){ if(_eTag.equals(ifNoneMatch) || ifNoneMatch.equals("*")){ response.setStatus(HttpServletResponse.SC_NOT_MODIFIED ); return; } } /* Using the If-Modified-Since Header */ if(ifModifiedSince != null){ try{ Date ifModifiedSinceDate = httpDate.parse(ifModifiedSince); if(_lastModified.getTime() <= ifModifiedSinceDate.getTime()){ response.setStatus(HttpServletResponse.SC_NOT_MODIFIED ); return; } } catch(Exception e){} } response.setHeader("Last-Modified", df.format(_lastModified)); response.setHeader("ETag", "\"" + _eTag +"\""); ServletOutputStream out = response.getOutputStream(); response.setContentType("image/png"); java.util.GregorianCalendar expiration = new java.util.GregorianCalendar(); expiration.add(java.util.Calendar.YEAR, 1); response.setHeader("Expires", httpDate.format(expiration.getTime())); response.setHeader("Cache-Control", "max-age=" +(60*60*24*30*12)); File f = new File(FileUtil.getRealPath("/html/images/icons/" + icon + ".png")); if(!f.exists()){ f = new File(FileUtil.getRealPath("/html/images/icons/ukn.png")); } response.setHeader("Content-Length", String.valueOf(f.length())); BufferedInputStream fis = null; try { fis = new BufferedInputStream(new FileInputStream(f)); int n; while ((n = fis.available()) > 0) { byte[] b = new byte[n]; int result = fis.read(b); if (result == -1) break; out.write(b); } // end while } catch (Exception e) { Logger.error(this.getClass(), "cannot read:" + f.toString()); } finally { if (fis != null) fis.close(); f=null; } out.close(); } }
# 2016 YouCompleteMe contributors # This file is part of YouCompleteMe. # YouCompleteMe is free software: you can redistribute it and/or modify # (at your option) any later version. # YouCompleteMe is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Not installing aliases from python-future; it's unreliable and slow. from builtins import * # noqa from future.utils import iterkeys import vim import os import json import re from collections import defaultdict from ycmd.utils import ( <API key>, GetCurrentDirectory, JoinLinesAsUnicode, ToBytes, ToUnicode ) from ycmd import user_options_store BUFFER_COMMAND_MAP = { 'same-buffer' : 'edit', 'horizontal-split' : 'split', 'vertical-split' : 'vsplit', 'new-tab' : 'tabedit' } <API key> = ( 'The requested operation will apply changes to {0} files which are not ' 'currently open. This will therefore open {0} new files in the hidden ' 'buffers. The quickfix list can then be used to review the changes. No ' 'files will be written to disk. Do you wish to continue?' ) <API key> = list( map( ToBytes, [ '[', '(', ',', ':' ] ) ) def CanComplete(): """Returns whether it's appropriate to provide any completion at the current line and column.""" try: line, column = <API key>() except TypeError: return False if ( line, column ) == <API key>(): return True return ( ToBytes( vim.current.buffer[ line ][ column - 1 ] ) in <API key> ) def <API key>(): """Will return <API key>(), except when there's solely whitespace between caret and a potential hint trigger, where it "snaps to trigger", returning hint trigger's line and column instead.""" try: line, column = <API key>() except TypeError: return <API key>() if ( ToBytes( vim.current.buffer[ line ][ column - 1 ] ) in <API key> ): return ( line, column ) return <API key>() def <API key>(): line, column = <API key>() line_value = vim.current.line[ :column ].rstrip() while not line_value: line = line - 1 if line == -1: return None line_value = vim.current.buffer[ line ].rstrip() return line, len( line_value ) <API key> = "No valid selection was made; aborting." def <API key>(): """Returns the 0-based current line and 0-based current column.""" # See the comment in CurrentColumn about the calculation for the line and # column number line, column = vim.current.window.cursor line -= 1 return line, column def CurrentColumn(): """Returns the 0-based current column. Do NOT access the CurrentColumn in vim.current.line. It doesn't exist yet when the cursor is at the end of the line. Only the chars before the current column exist in vim.current.line.""" # vim's columns are 1-based while vim.current.line columns are 0-based # ... but vim.current.window.cursor (which returns a (line, column) tuple) # columns are 0-based, while the line from that same tuple is 1-based. # vim.buffers buffer objects OTOH have 0-based lines and columns. # Pigs have wings and I'm a loopy purple duck. Everything makes sense now. return vim.current.window.cursor[ 1 ] def CurrentLineContents(): return ToUnicode( vim.current.line ) def <API key>(): """Returns the line contents as a unicode string and the 0-based current column as a codepoint offset. If the current column is outside the line, returns the column position at the end of the line.""" line = CurrentLineContents() byte_column = CurrentColumn() # <API key> expects 1-based offset. column = <API key>( line, byte_column + 1 ) - 1 return line, column def TextAfterCursor(): """Returns the text after CurrentColumn.""" return ToUnicode( vim.current.line[ CurrentColumn(): ] ) def TextBeforeCursor(): """Returns the text before CurrentColumn.""" return ToUnicode( vim.current.line[ :CurrentColumn() ] ) # Note the difference between buffer OPTIONS and VARIABLES; the two are not # the same. def GetBufferOption( buffer_object, option ): # NOTE: We used to check for the 'options' property on the buffer_object which # is available in recent versions of Vim and would then use: # buffer_object.options[ option ] # to read the value, BUT this caused annoying flickering when the # buffer_object was a hidden buffer (with option = 'ft'). This was all due to # a Vim bug. Until this is fixed, we won't use it. to_eval = 'getbufvar({0}, "&{1}")'.format( buffer_object.number, option ) return GetVariableValue( to_eval ) def BufferModified( buffer_object ): return bool( int( GetBufferOption( buffer_object, 'mod' ) ) ) def <API key>( including_filepath ): """Build part of the request containing the contents and filetypes of all dirty buffers as well as the buffer with filepath |including_filepath|.""" buffers_data = {} for buffer_object in vim.buffers: buffer_filepath = GetBufferFilepath( buffer_object ) if not ( BufferModified( buffer_object ) or buffer_filepath == including_filepath ): continue buffers_data[ buffer_filepath ] = { # Add a newline to match what gets saved to disk. See #1455 for details. 'contents': JoinLinesAsUnicode( buffer_object ) + '\n', 'filetypes': FiletypesForBuffer( buffer_object ) } return buffers_data def <API key>( filename, open_file_if_needed = True ): return GetIntValue( u"bufnr('{0}', {1})".format( EscapeForVim( os.path.realpath( filename ) ), int( open_file_if_needed ) ) ) def <API key>(): return GetBufferFilepath( vim.current.buffer ) def BufferIsVisible( buffer_number ): if buffer_number < 0: return False window_number = GetIntValue( "bufwinnr({0})".format( buffer_number ) ) return window_number != -1 def GetBufferFilepath( buffer_object ): if buffer_object.name: return buffer_object.name # buffer name so we use the buffer number for that. return os.path.join( GetCurrentDirectory(), str( buffer_object.number ) ) def <API key>(): return vim.current.buffer.number def <API key>( bufnr ): return GetIntValue( 'getbufvar({0}, "changedtick")'.format( bufnr ) ) def UnplaceSignInBuffer( buffer_number, sign_id ): if buffer_number < 0: return vim.command( 'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format( sign_id, buffer_number ) ) def PlaceSign( sign_id, line_num, buffer_num, is_error = True ): # libclang can give us diagnostics that point "outside" the file; Vim borks # on these. if line_num < 1: line_num = 1 sign_name = 'YcmError' if is_error else 'YcmWarning' vim.command( 'sign place {0} name={1} line={2} buffer={3}'.format( sign_id, sign_name, line_num, buffer_num ) ) def <API key>(): matches = <API key>( 'getmatches()' ) for match in matches: if match[ 'group' ].startswith( 'Ycm' ): vim.eval( 'matchdelete({0})'.format( match[ 'id' ] ) ) def <API key>( line_num, column_num, line_end_num = None, column_end_num = None, is_error = True ): """Highlight a range in the current window starting from (|line_num|, |column_num|) included to (|line_end_num|, |column_end_num|) excluded. If |line_end_num| or |column_end_num| are not given, highlight the character at (|line_num|, |column_num|). Both line and column numbers are 1-based. Return the ID of the newly added match.""" group = 'YcmErrorSection' if is_error else 'YcmWarningSection' line_num, column_num = <API key>( line_num, column_num ) if not line_end_num or not column_end_num: return GetIntValue( "matchadd('{0}', '\%{1}l\%{2}c')".format( group, line_num, column_num ) ) # -1 and then +1 to account for column end not included in the range. line_end_num, column_end_num = <API key>( line_end_num, column_end_num - 1 ) column_end_num += 1 return GetIntValue( "matchadd('{0}', '\%{1}l\%{2}c\_.\\{{-}}\%{3}l\%{4}c')".format( group, line_num, column_num, line_end_num, column_end_num ) ) # Clamps the line and column numbers so that they are not past the contents of # the buffer. Numbers are 1-based byte offsets. def <API key>( line_num, column_num ): new_line_num = line_num new_column_num = column_num max_line = len( vim.current.buffer ) if line_num and line_num > max_line: new_line_num = max_line max_column = len( vim.current.buffer[ new_line_num - 1 ] ) if column_num and column_num > max_column: new_column_num = max_column return new_line_num, new_column_num def SetLocationList( diagnostics ): """Populate the location list with diagnostics. Diagnostics should be in qflist format; see ":h setqflist" for details.""" vim.eval( 'setloclist( 0, {0} )'.format( json.dumps( diagnostics ) ) ) def OpenLocationList( focus = False, autoclose = False ): """Open the location list to full width at the bottom of the screen with its height automatically set to fit all entries. This behavior can be overridden by using the YcmLocationOpened autocommand. When focus is set to True, the location list window becomes the active window. When autoclose is set to True, the location list window is automatically closed after an entry is selected.""" vim.command( 'botright lopen' ) <API key>() if autoclose: # This autocommand is automatically removed when the location list window is # closed. vim.command( 'au WinLeave <buffer> q' ) if VariableExists( '#User#YcmLocationOpened' ): vim.command( 'doautocmd User YcmLocationOpened' ) if not focus: <API key>() def SetQuickFixList( quickfix_list ): """Populate the quickfix list and open it. List should be in qflist format: see ":h setqflist" for details.""" vim.eval( 'setqflist( {0} )'.format( json.dumps( quickfix_list ) ) ) def OpenQuickFixList( focus = False, autoclose = False ): """Open the quickfix list to full width at the bottom of the screen with its height automatically set to fit all entries. This behavior can be overridden by using the YcmQuickFixOpened autocommand. See the OpenLocationList function for the focus and autoclose options.""" vim.command( 'botright copen' ) <API key>() if autoclose: # This autocommand is automatically removed when the quickfix window is # closed. vim.command( 'au WinLeave <buffer> q' ) if VariableExists( '#User#YcmQuickFixOpened' ): vim.command( 'doautocmd User YcmQuickFixOpened' ) if not focus: <API key>() def <API key>(): window_width = GetIntValue( 'winwidth( 0 )' ) fitting_height = 0 for line in vim.current.buffer: fitting_height += len( line ) // window_width + 1 vim.command( '{0}wincmd _'.format( fitting_height ) ) def <API key>( diagnostics ): def <API key>( diagnostic ): # See :h getqflist for a description of the dictionary fields. # Note that, as usual, Vim is completely inconsistent about whether # line/column numbers are 1 or 0 based in its various APIs. Here, it wants # them to be 1-based. The documentation states quite clearly that it # expects a byte offset, by which it means "1-based column number" as # described in :h getqflist ("the first column is 1"). location = diagnostic[ 'location' ] line_num = location[ 'line_num' ] # libclang can give us diagnostics that point "outside" the file; Vim borks # on these. if line_num < 1: line_num = 1 text = diagnostic[ 'text' ] if diagnostic.get( 'fixit_available', False ): text += ' (FixIt available)' return { 'bufnr' : <API key>( location[ 'filepath' ] ), 'lnum' : line_num, 'col' : location[ 'column_num' ], 'text' : text, 'type' : diagnostic[ 'kind' ][ 0 ], 'valid' : 1 } return [ <API key>( x ) for x in diagnostics ] def GetVimGlobalsKeys(): return vim.eval( 'keys( g: )' ) def <API key>( vim_expression ): """Returns a Python type from the return value of the supplied Vim expression. If the expression returns a list, dict or other non-string type, then it is returned unmodified. If the string return can be converted to an integer, returns an integer, otherwise returns the result converted to a Unicode string.""" result = vim.eval( vim_expression ) if not ( isinstance( result, str ) or isinstance( result, bytes ) ): return result try: return int( result ) except ValueError: return ToUnicode( result ) def HiddenEnabled( buffer_object ): return bool( int( GetBufferOption( buffer_object, 'hid' ) ) ) def BufferIsUsable( buffer_object ): return not BufferModified( buffer_object ) or HiddenEnabled( buffer_object ) def EscapedFilepath( filepath ): return filepath.replace( ' ' , r'\ ' ) # Both |line| and |column| need to be 1-based def <API key>( filename, line, column ): filepath = os.path.realpath( filename ) for tab in vim.tabpages: for win in tab.windows: if win.buffer.name == filepath: vim.current.tabpage = tab vim.current.window = win vim.current.window.cursor = ( line, column - 1 ) # Center the screen on the jumped-to location vim.command( 'normal! zz' ) return True # 'filename' is not opened in any tab pages return False # Maps User command to vim command def GetVimCommand( user_command, default = 'edit' ): vim_command = BUFFER_COMMAND_MAP.get( user_command, default ) if vim_command == 'edit' and not BufferIsUsable( vim.current.buffer ): vim_command = 'split' return vim_command # Both |line| and |column| need to be 1-based def JumpToLocation( filename, line, column ): # Add an entry to the jumplist vim.command( "normal! m'" ) if filename != <API key>(): # We prefix the command with 'keepjumps' so that opening the file is not # recorded in the jumplist. So when we open the file and move the cursor to # a location in it, the user can use CTRL-O to jump back to the original # location, not to the start of the newly opened file. # Sadly this fails on random occasions and the undesired jump remains in the # jumplist. user_command = user_options_store.Value( 'goto_buffer_command' ) if user_command == 'new-or-existing-tab': if <API key>( filename, line, column ): return user_command = 'new-tab' vim_command = GetVimCommand( user_command ) try: vim.command( 'keepjumps {0} {1}'.format( vim_command, EscapedFilepath( filename ) ) ) # When the file we are trying to jump to has a swap file # Vim opens swap-exists-choices dialog and throws vim.error with E325 error, # or KeyboardInterrupt after user selects one of the options. except vim.error as e: if 'E325' not in str( e ): raise # Do nothing if the target file is still not opened (user chose (Q)uit) if filename != <API key>(): return # Thrown when user chooses (A)bort in .swp message box except KeyboardInterrupt: return vim.current.window.cursor = ( line, column - 1 ) # Center the screen on the jumped-to location vim.command( 'normal! zz' ) def NumLinesInBuffer( buffer_object ): # This is actually less than obvious, that's why it's wrapped in a function return len( buffer_object ) # Calling this function from the non-GUI thread will sometimes crash Vim. At # the time of writing, YCM only uses the GUI thread inside Vim (this used to # not be the case). def PostVimMessage( message, warning = True, truncate = False ): """Display a message on the Vim status line. By default, the message is highlighted and logged to Vim command-line history (see :h history). Unset the |warning| parameter to disable this behavior. Set the |truncate| parameter to avoid hit-enter prompts (see :h hit-enter) when the message is longer than the window width.""" echo_command = 'echom' if warning else 'echo' # Displaying a new message while previous ones are still on the status line # might lead to a hit-enter prompt or the message appearing without a # newline so we do a redraw first. vim.command( 'redraw' ) if warning: vim.command( 'echohl WarningMsg' ) message = ToUnicode( message ) if truncate: vim_width = GetIntValue( '&columns' ) message = message.replace( '\n', ' ' ) if len( message ) > vim_width: message = message[ : vim_width - 4 ] + '...' old_ruler = GetIntValue( '&ruler' ) old_showcmd = GetIntValue( '&showcmd' ) vim.command( 'set noruler noshowcmd' ) vim.command( "{0} '{1}'".format( echo_command, EscapeForVim( message ) ) ) SetVariableValue( '&ruler', old_ruler ) SetVariableValue( '&showcmd', old_showcmd ) else: for line in message.split( '\n' ): vim.command( "{0} '{1}'".format( echo_command, EscapeForVim( line ) ) ) if warning: vim.command( 'echohl None' ) def PresentDialog( message, choices, <API key> = 0 ): """Presents the user with a dialog where a choice can be made. This will be a dialog for gvim users or a question in the message buffer for vim users or if `set guioptions+=c` was used. choices is list of alternatives. <API key> is the 0-based index of the default element that will get choosen if the user hits <CR>. Use -1 for no default. PresentDialog will return a 0-based index into the list or -1 if the dialog was dismissed by using <Esc>, Ctrl-C, etc. If you are presenting a list of options for the user to choose from, such as a list of imports, or lines to insert (etc.), SelectFromList is a better option. See also: :help confirm() in vim (Note that vim uses 1-based indexes) Example call: PresentDialog("Is this a nice example?", ["Yes", "No", "May&be"]) Is this a nice example? [Y]es, (N)o, May(b)e:""" to_eval = "confirm('{0}', '{1}', {2})".format( EscapeForVim( ToUnicode( message ) ), EscapeForVim( ToUnicode( "\n" .join( choices ) ) ), <API key> + 1 ) try: return GetIntValue( to_eval ) - 1 except KeyboardInterrupt: return -1 def Confirm( message ): """Display |message| with Ok/Cancel operations. Returns True if the user selects Ok""" return bool( PresentDialog( message, [ "Ok", "Cancel" ] ) == 0 ) def SelectFromList( prompt, items ): """Ask the user to select an item from the list |items|. Presents the user with |prompt| followed by a numbered list of |items|, from which they select one. The user is asked to enter the number of an item or click it. |items| should not contain leading ordinals: they are added automatically. Returns the 0-based index in the list |items| that the user selected, or a negative number if no valid item was selected. See also :help inputlist().""" vim_items = [ prompt ] vim_items.extend( [ "{0}: {1}".format( i + 1, item ) for i, item in enumerate( items ) ] ) # The vim documentation warns not to present lists larger than the number of # lines of display. This is sound advice, but there really isn't any sensible # thing we can do in that scenario. Testing shows that Vim just pages the # message; that behaviour is as good as any, so we don't manipulate the list, # or attempt to page it. # For an explanation of the purpose of inputsave() / inputrestore(), # see :help input(). Briefly, it makes inputlist() work as part of a mapping. vim.eval( 'inputsave()' ) try: # Vim returns the number the user entered, or the line number the user # clicked. This may be wildly out of range for our list. It might even be # negative. # The first item is index 0, and this maps to our "prompt", so we subtract 1 # from the result and return that, assuming it is within the range of the # supplied list. If not, we return negative. # See :help input() for explanation of the use of inputsave() and inpput # restore(). It is done in try/finally in case vim.eval ever throws an # exception (such as KeyboardInterrupt) selected = GetIntValue( "inputlist( " + json.dumps( vim_items ) + " )" ) - 1 except KeyboardInterrupt: selected = -1 finally: vim.eval( 'inputrestore()' ) if selected < 0 or selected >= len( items ): # User selected something outside of the range raise RuntimeError( <API key> ) return selected def EscapeForVim( text ): return ToUnicode( text.replace( "'", "''" ) ) def CurrentFiletypes(): return <API key>( "&filetype" ).split( '.' ) def GetBufferFiletypes( bufnr ): command = 'getbufvar({0}, "&ft")'.format( bufnr ) return <API key>( command ).split( '.' ) def FiletypesForBuffer( buffer_object ): # NOTE: Getting &ft for other buffers only works when the buffer has been # visited by the user at least once, which is true for modified buffers return GetBufferOption( buffer_object, 'ft' ).split( '.' ) def VariableExists( variable ): return GetBoolValue( "exists( '{0}' )".format( EscapeForVim( variable ) ) ) def SetVariableValue( variable, value ): vim.command( "let {0} = {1}".format( variable, json.dumps( value ) ) ) def GetVariableValue( variable ): return vim.eval( variable ) def GetBoolValue( variable ): return bool( int( vim.eval( variable ) ) ) def GetIntValue( variable ): return int( vim.eval( variable ) ) def _SortChunksByFile( chunks ): """Sort the members of the list |chunks| (which must be a list of dictionaries conforming to ycmd.responses.FixItChunk) by their filepath. Returns a new list in arbitrary order.""" chunks_by_file = defaultdict( list ) for chunk in chunks: filepath = chunk[ 'range' ][ 'start' ][ 'filepath' ] chunks_by_file[ filepath ].append( chunk ) return chunks_by_file def <API key>( file_list ): """Returns the number of file in the iterable list of files |file_list| which are not curerntly open in visible windows""" return len( [ f for f in file_list if not BufferIsVisible( <API key>( f, False ) ) ] ) def <API key>( filepath ): """Ensure that the supplied filepath is open in a visible window, opening a new split if required. Returns the buffer number of the file and an indication of whether or not a new split was opened. If the supplied filename is already open in a visible window, return just return its buffer number. If the supplied file is not visible in a window in the current tab, opens it in a new vertical split. Returns a tuple of ( buffer_num, split_was_opened ) indicating the buffer number and whether or not this method created a new split. If the user opts not to open a file, or if opening fails, this method raises RuntimeError, otherwise, guarantees to return a visible buffer number in buffer_num.""" buffer_num = <API key>( filepath, False ) # We only apply changes in the current tab page (i.e. "visible" windows). # Applying changes in tabs does not lead to a better user experience, as the # quickfix list no longer works as you might expect (doesn't jump into other # tabs), and the complexity of choosing where to apply edits is significant. if BufferIsVisible( buffer_num ): # file is already open and visible, just return that buffer number (and an # idicator that we *didn't* open a split) return ( buffer_num, False ) # The file is not open in a visible window, so we open it in a split. # We open the file with a small, fixed height. This means that we don't # make the current buffer the smallest after a series of splits. OpenFilename( filepath, { 'focus': True, 'fix': True, 'size': GetIntValue( '&previewheight' ), } ) # OpenFilename returns us to the original cursor location. This is what we # want, because we don't want to disorientate the user, but we do need to # know the (now open) buffer number for the filename buffer_num = <API key>( filepath, False ) if not BufferIsVisible( buffer_num ): # This happens, for example, if there is a swap file and the user # selects the "Quit" or "Abort" options. We just raise an exception to # make it clear to the user that the abort has left potentially # partially-applied changes. raise RuntimeError( 'Unable to open file: {0}\nFixIt/Refactor operation ' 'aborted prior to completion. Your files have not been ' 'fully updated. Please use undo commands to revert the ' 'applied changes.'.format( filepath ) ) # We opened this file in a split return ( buffer_num, True ) def ReplaceChunks( chunks ): """Apply the source file deltas supplied in |chunks| to arbitrary files. |chunks| is a list of changes defined by ycmd.responses.FixItChunk, which may apply arbitrary modifications to arbitrary files. If a file specified in a particular chunk is not currently open in a visible buffer (i.e., one in a window visible in the current tab), we: - issue a warning to the user that we're going to open new files (and offer her the option to abort cleanly) - open the file in a new split, make the changes, then hide the buffer. If for some reason a file could not be opened or changed, raises RuntimeError. Otherwise, returns no meaningful value.""" # We apply the edits file-wise for efficiency, and because we must track the # file-wise offset deltas (caused by the modifications to the text). chunks_by_file = _SortChunksByFile( chunks ) # We sort the file list simply to enable repeatable testing sorted_file_list = sorted( iterkeys( chunks_by_file ) ) # Make sure the user is prepared to have her screen mutilated by the new # buffers num_files_to_open = <API key>( sorted_file_list ) if num_files_to_open > 0: if not Confirm( <API key>.format( num_files_to_open ) ): return # Store the list of locations where we applied changes. We use this to display # the quickfix window showing the user where we applied changes. locations = [] for filepath in sorted_file_list: ( buffer_num, close_window ) = <API key>( filepath ) <API key>( chunks_by_file[ filepath ], vim.buffers[ buffer_num ], locations ) # When opening tons of files, we don't want to have a split for each new # file, as this simply does not scale, so we open the window, make the # edits, then hide the window. if close_window: # Some plugins (I'm looking at you, syntastic) might open a location list # for the window we just opened. We don't want that location list hanging # around, so we close it. lclose is a no-op if there is no location list. vim.command( 'lclose' ) # Note that this doesn't lose our changes. It simply "hides" the buffer, # which can later be re-accessed via the quickfix list or `:ls` vim.command( 'hide' ) # Open the quickfix list, populated with entries for each location we changed. if locations: SetQuickFixList( locations ) OpenQuickFixList() PostVimMessage( 'Applied {0} changes'.format( len( chunks ) ), warning = False ) def <API key>( chunks, vim_buffer, locations ): """Apply changes in |chunks| to the buffer-like object |buffer|. Append each chunk's start to the list |locations|""" # We need to track the difference in length, but ensuring we apply fixes # in ascending order of insertion point. chunks.sort( key = lambda chunk: ( chunk[ 'range' ][ 'start' ][ 'line_num' ], chunk[ 'range' ][ 'start' ][ 'column_num' ] ) ) # Remember the line number we're processing. Negative line number means we # haven't processed any lines yet (by nature of being not equal to any # real line number). last_line = -1 line_delta = 0 for chunk in chunks: if chunk[ 'range' ][ 'start' ][ 'line_num' ] != last_line: # If this chunk is on a different line than the previous chunk, # then ignore previous deltas (as offsets won't have changed). last_line = chunk[ 'range' ][ 'end' ][ 'line_num' ] char_delta = 0 ( new_line_delta, new_char_delta ) = ReplaceChunk( chunk[ 'range' ][ 'start' ], chunk[ 'range' ][ 'end' ], chunk[ 'replacement_text' ], line_delta, char_delta, vim_buffer, locations ) line_delta += new_line_delta char_delta += new_char_delta # Replace the chunk of text specified by a contiguous range with the supplied # text. # * start and end are objects with line_num and column_num properties # * the range is inclusive # * indices are all 1-based # * the returned character delta is the delta for the last line # returns the delta (in lines and characters) that any position after the end # needs to be adjusted by. # NOTE: Works exclusively with bytes() instances and byte offsets as returned # by ycmd and used within the Vim buffers def ReplaceChunk( start, end, replacement_text, line_delta, char_delta, vim_buffer, locations = None ): # ycmd's results are all 1-based, but vim's/python's are all 0-based # (so we do -1 on all of the values) start_line = start[ 'line_num' ] - 1 + line_delta end_line = end[ 'line_num' ] - 1 + line_delta source_lines_count = end_line - start_line + 1 start_column = start[ 'column_num' ] - 1 + char_delta end_column = end[ 'column_num' ] - 1 if source_lines_count == 1: end_column += char_delta # NOTE: replacement_text is unicode, but all our offsets are byte offsets, # so we convert to bytes replacement_lines = ToBytes( replacement_text ).splitlines( False ) if not replacement_lines: replacement_lines = [ bytes( b'' ) ] <API key> = len( replacement_lines ) # NOTE: Vim buffers are a list of byte objects on Python 2 but unicode # objects on Python 3. end_existing_text = ToBytes( vim_buffer[ end_line ] )[ end_column : ] start_existing_text = ToBytes( vim_buffer[ start_line ] )[ : start_column ] new_char_delta = ( len( replacement_lines[ -1 ] ) - ( end_column - start_column ) ) if <API key> > 1: new_char_delta -= start_column replacement_lines[ 0 ] = start_existing_text + replacement_lines[ 0 ] replacement_lines[ -1 ] = replacement_lines[ -1 ] + end_existing_text vim_buffer[ start_line : end_line + 1 ] = replacement_lines[:] if locations is not None: locations.append( { 'bufnr': vim_buffer.number, 'filename': vim_buffer.name, # line and column numbers are 1-based in qflist 'lnum': start_line + 1, 'col': start_column + 1, 'text': replacement_text, 'type': 'F', } ) new_line_delta = <API key> - source_lines_count return ( new_line_delta, new_char_delta ) def InsertNamespace( namespace ): if VariableExists( 'g:<API key>' ): expr = GetVariableValue( 'g:<API key>' ) if expr: SetVariableValue( "g:<API key>", namespace ) vim.eval( expr ) return pattern = '^\s*using\(\s\+[a-zA-Z0-9]\+\s\+=\)\?\s\+[a-zA-Z0-9.]\+\s*;\s*' existing_indent = '' line = <API key>( pattern ) if line: existing_line = <API key>( line ) existing_indent = re.sub( r"\S.*", "", existing_line ) new_line = "{0}using {1};\n\n".format( existing_indent, namespace ) replace_pos = { 'line_num': line + 1, 'column_num': 1 } ReplaceChunk( replace_pos, replace_pos, new_line, 0, 0, vim.current.buffer ) PostVimMessage( 'Add namespace: {0}'.format( namespace ), warning = False ) def <API key>( pattern ): """ Returns the 1-indexed line on which the pattern matches (going UP from the current position) or 0 if not found """ return GetIntValue( "search('{0}', 'Wcnb')".format( EscapeForVim( pattern ))) def <API key>( line_number ): """ Returns the text on the 1-indexed line (NOT 0-indexed) """ return vim.current.buffer[ line_number - 1 ] def ClosePreviewWindow(): """ Close the preview window if it is present, otherwise do nothing """ vim.command( 'silent! pclose!' ) def JumpToPreviewWindow(): """ Jump the vim cursor to the preview window, which must be active. Returns boolean indicating if the cursor ended up in the preview window """ vim.command( 'silent! wincmd P' ) return vim.current.window.options[ 'previewwindow' ] def <API key>(): """ Jump the vim cursor to its previous window position """ vim.command( 'silent! wincmd p' ) def JumpToTab( tab_number ): """Jump to Vim tab with corresponding number """ vim.command( 'silent! tabn {0}'.format( tab_number ) ) def <API key>( filename ): """ Open the supplied filename in the preview window """ vim.command( 'silent! pedit! ' + filename ) def <API key>( message ): """ Display the supplied message in the preview window """ # This isn't something that comes naturally to Vim. Vim only wants to show # tags and/or actual files in the preview window, so we have to hack it a # little bit. We generate a temporary file name and "open" that, then write # the data to it. We make sure the buffer can't be edited or saved. Other # approaches include simply opening a split, but we want to take advantage of # the existing Vim options for preview window height, etc. ClosePreviewWindow() <API key>( vim.eval( 'tempname()' ) ) if JumpToPreviewWindow(): # We actually got to the preview window. By default the preview window can't # be changed, so we make it writable, write to it, then make it read only # again. vim.current.buffer.options[ 'modifiable' ] = True vim.current.buffer.options[ 'readonly' ] = False vim.current.buffer[:] = message.splitlines() vim.current.buffer.options[ 'buftype' ] = 'nofile' vim.current.buffer.options[ 'bufhidden' ] = 'wipe' vim.current.buffer.options[ 'buflisted' ] = False vim.current.buffer.options[ 'swapfile' ] = False vim.current.buffer.options[ 'modifiable' ] = False vim.current.buffer.options[ 'readonly' ] = True # We need to prevent closing the window causing a warning about unsaved # file, so we pretend to Vim that the buffer has not been changed. vim.current.buffer.options[ 'modified' ] = False <API key>() else: # We couldn't get to the preview window, but we still want to give the user # the information we have. The only remaining option is to echo to the # status area. PostVimMessage( message, warning = False ) def <API key>( filename ): """Check if a buffer exists for a specific file.""" buffer_number = <API key>( filename, False ) return BufferIsVisible( buffer_number ) def <API key>( filename ): """Close all buffers for a specific file.""" buffer_number = <API key>( filename, False ) while buffer_number != -1: vim.command( 'silent! bwipeout! {0}'.format( buffer_number ) ) new_buffer_number = <API key>( filename, False ) if buffer_number == new_buffer_number: raise RuntimeError( "Buffer {0} for filename '{1}' should already be " "wiped out.".format( buffer_number, filename ) ) buffer_number = new_buffer_number def OpenFilename( filename, options = {} ): """Open a file in Vim. Following options are available: - command: specify which Vim command is used to open the file. Choices are same-buffer, horizontal-split, vertical-split, and new-tab (default: horizontal-split); - size: set the height of the window for a horizontal split or the width for a vertical one (default: ''); - fix: set the winfixheight option for a horizontal split or winfixwidth for a vertical one (default: False). See :h winfix for details; - focus: focus the opened file (default: False); - watch: automatically watch for changes (default: False). This is useful for logs; - position: set the position where the file is opened (default: start). Choices are start and end.""" # Set the options. command = GetVimCommand( options.get( 'command', 'horizontal-split' ), 'horizontal-split' ) size = ( options.get( 'size', '' ) if command in [ 'split', 'vsplit' ] else '' ) focus = options.get( 'focus', False ) # There is no command in Vim to return to the previous tab so we need to # remember the current tab if needed. if not focus and command == 'tabedit': previous_tab = GetIntValue( 'tabpagenr()' ) else: previous_tab = None # Open the file. try: vim.command( '{0}{1} {2}'.format( size, command, filename ) ) # When the file we are trying to jump to has a swap file, # Vim opens swap-exists-choices dialog and throws vim.error with E325 error, # or KeyboardInterrupt after user selects one of the options which actually # opens the file (Open read-only/Edit anyway). except vim.error as e: if 'E325' not in str( e ): raise # Otherwise, the user might have chosen Quit. This is detectable by the # current file not being the target file if filename != <API key>(): return except KeyboardInterrupt: # Raised when the user selects "Abort" after swap-exists-choices return _SetUpLoadedBuffer( command, filename, options.get( 'fix', False ), options.get( 'position', 'start' ), options.get( 'watch', False ) ) # Vim automatically set the focus to the opened file so we need to get the # focus back (if the focus option is disabled) when opening a new tab or # window. if not focus: if command == 'tabedit': JumpToTab( previous_tab ) if command in [ 'split', 'vsplit' ]: <API key>() def _SetUpLoadedBuffer( command, filename, fix, position, watch ): """After opening a buffer, configure it according to the supplied options, which are as defined by the OpenFilename method.""" if command == 'split': vim.current.window.options[ 'winfixheight' ] = fix if command == 'vsplit': vim.current.window.options[ 'winfixwidth' ] = fix if watch: vim.current.buffer.options[ 'autoread' ] = True vim.command( "exec 'au BufEnter <buffer> :silent! checktime {0}'" .format( filename ) ) if position == 'end': vim.command( 'silent! normal! Gzz' )
<!-- resources/views/vendor/openpolice/nodes/<API key>.blade.php --> <a class="btn btn-primary btn-lg" href="/<API key>/{{ $d['deptRow']->dept_slug }}" <?php /* @if (in_array(substr($d['deptRow']->dept_slug, 0, 3), ['NY-', 'MA-', 'MD-', 'MN-', 'DC-'])) href="/<API key>/{{ $d['deptRow']->dept_slug }}" @else href="/join-beta-test/{{ $d['deptRow']->dept_slug }}" @endif */ ?> >File a Complaint or Compliment</a> <div class="pT15 mT10"></div> <style> #node2707kids { padding-top: 30px; } #blockWrap2710 { margin-bottom: -20px; } </style>
<?php Prado::Using('Application.Engine.*'); class CombinedView extends TPage { public $text; public $tiroText; public function onLoad() { global $ABS_PATH,$USERS_PREFIX; $this->text = TextRecord::finder()->findByPk($_GET['id']); $this->tiroText = new TiroText($ABS_PATH.'/'.$USERS_PREFIX.'/'.$this->User->Name.'/'.$this->text->dir_name); // Display the text at the bottom. $textDOM = new DomDocument; $textDOM->loadXML($this->tiroText->getText()); $styleSheet = new DOMDocument; $styleSheet->load('protected/Data/xsl/tiro2js_tree.xsl'); $proc = new XSLTProcessor; $proc->importStyleSheet($styleSheet); $this->LatinPreview->Controls->add($proc->transformToXML($textDOM)); } } ?>
#if defined HAVE_CONFIG_H #include "config.h" #endif #include <solver_core.hpp> #include <triqs/operators/many_body_operator.hpp> #include <triqs/hilbert_space/<API key>.hpp> #include <triqs/gfs.hpp> #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <iomanip> //#include <boost/mpi/communicator.hpp> #include "triqs_cthyb_qmc.hpp" using namespace std; using namespace cthyb; using triqs::utility::many_body_operator; using triqs::utility::c; using triqs::utility::c_dag; using triqs::utility::n; using namespace triqs::gfs; using indices_type = triqs::utility::many_body_operator<double>::indices_t; void ctqmc_triqs_run( bool rot_inv, bool leg_measure, bool hist, bool wrt_files, bool tot_not, /*boolean*/ int n_orbitals, int n_freq, int n_tau, int n_l, int n_cycles_, int cycle_length, int ntherm, int verbo, int seed, /*integer*/ double beta_, /*double*/ double *epsi, double *umat_ij, double *umat_ijkl, std::complex<double> *f_iw_ptr, std::complex<double> *g_iw_ptr, double *g_tau, double *gl, MPI_Fint *MPI_world_ptr ){ /*array pointers & simple pointers*/ cout.setf(ios::fixed); //cout.precision(17); //Initialize Boost mpi environment int rank; boost::mpi::environment env; //int rank = boost::mpi::communicator(MPI_Comm_f2c(*MPI_world_ptr), boost::mpi::comm_attach).rank(); { boost::mpi::communicator c; c << MPI_Comm_f2c( *MPI_world_ptr ); //auto c_ = MPI_Comm_f2c(*MPI_world_ptr); //boost::mpi::communicator c = boost::mpi::communicator(MPI_Comm_f2c(*MPI_world_ptr), boost::mpi::comm_attach); rank=c.rank(); //MPI_Comm_rank(MPI_Comm_f2c(*MPI_world_ptr), &rank); } // Parameters relay from Fortran and default values affectation double beta = beta_; //Temperature inverse int num_orbitals = n_orbitals; //double U = U_; //Impurity site Interaction term double mu = 0.0;//Chemical Potential Functionality avail but not used here //bool n_n_only = !(rot_inv);//density-density? int Nfreq = n_freq; //Number of Matsubara frequencies int Ntau = n_tau; //Number of imaginary times int Nl = n_l; //Number of Legendre measures 30 int n_cycles = n_cycles_; int nspin = 2; //always it's Nature //Print informations about the Solver Parameters if(rank==0 && verbo>0){ std::cout << endl <<" == Key Input Parameters for the TRIQS CTHYB solver == "<<endl<<endl; std::cout <<" Beta = "<< beta <<" [eV]^(-1) "<<endl; std::cout <<" Mu = "<< mu <<" [eV]"<<endl; std::cout <<" Nflavour = "<< num_orbitals <<endl; std::cout <<" Nfreq = "<< Nfreq << endl; std::cout <<" Ntau = "<< Ntau << endl; std::cout <<" Nl = "<< Nl << endl; std::cout <<" Ncycles = "<< n_cycles << endl; std::cout <<" Cycle length = "<< cycle_length << endl; std::cout <<" Ntherm = "<< ntherm << endl; std::cout <<" Verbosity (0->3) = "<< verbo << endl; std::cout <<" Abinit Seed = "<< seed << endl <<endl; for(int o = 0; o < num_orbitals; ++o){ std::cout << " e- level["<< o+1 <<"] = "<< setprecision(17) << epsi[o] <<" [eV]"<< endl; //ed != cste => vecteur a parcourir ensuite } std::cout << endl; std::cout <<" U(i,j) [eV] = " <<endl<< endl<<"\t"; for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ std::cout << setprecision(17) << fixed <<umat_ij[o+oo*num_orbitals] << "\t"; //ed != cste => vecteur a parcourir ensuite } std::cout << endl<<"\t"; } } // Hamiltonian definition many_body_operator<double> H; //Spin Orbit general case num_orbitals*2=Nflavour) //Init Hamiltonian Basic terms H = init_Hamiltonian( epsi, num_orbitals, U, J ); // U=cste if(!rot_inv){ if(rank==0 && verbo>0) std::cout <<endl<<" == Density-Density Terms Included == "<<endl<<endl; H = init_Hamiltonian( epsi, num_orbitals, umat_ij ); //}else if(rank==0 && verbo>0) std::cout <<" == Rotationnaly Invariant Terms Not Included == "<< endl << endl; //Include density-density term (J != 0) spin flips and pair hopping => density-density term case }else{//if(rot_inv){ if(rank==0 && verbo>0)std::cout <<" == Rotationnaly Invariant Terms Included == "<< endl << endl; if(tot_not){ H = <API key>( epsi, num_orbitals, umat_ijkl ); }else{ //up and down separation H = <API key>( epsi, num_orbitals, umat_ijkl ); } }//else if(rank==0 && verbo>0) std::cout <<endl<<" == Density-Density Terms Not Included == "<<endl<<endl; std::map<std::string, indices_type> gf_struct; if( tot_not ){ std::map<std::string, indices_type> gf_struct_tmp{{"tot",indices_type{}}};//{{"tot",indices_type{}}}; //{0,1} for(int o = 0; o < num_orbitals; ++o){ gf_struct_tmp["tot"].push_back(o); } gf_struct = gf_struct_tmp; }else{ //spin orb case: general case std::map<std::string, indices_type> gf_struct_tmp{{"up",indices_type{}},{"down",indices_type{}}}; for(int o = 0; o < num_orbitals; ++o){ gf_struct_tmp["up"].push_back(o); gf_struct_tmp["down"].push_back(o); } gf_struct = gf_struct_tmp; } if(rank==0 && verbo>0) std::cout <<" == Green Function Structure Initialized == "<< endl << endl; // Construct CTQMC solver with mesh parameters solver_core solver(beta, gf_struct, Nfreq, Ntau, Nl); if(rank==0 && verbo>0) std::cout <<" == Solver Core Initialized == "<< endl << endl; //Fill in "hybridation+eps"=F(iw)~Delta(iw) coming from fortran inside delta_iw term RHS gf<imfreq> delta_iw = gf<imfreq>{{beta, Fermion, Nfreq}, {num_orbitals,num_orbitals}}; auto w_mesh = delta_iw.mesh(); ofstream delta_init; delta_init.open("delta_init_check"); // only on one rank ! if(rank==0){ delta_init << "# w_index l l' Im(iw) delta(iw)\n" << endl; } for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ auto iw = w_mesh.index_to_point(w_index); auto cell = delta_iw[w_index]; for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ cell(o,oo) = f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals]; //cout <<"[IN C++]"<<" F[ w= "<< w_index <<" , l= "<< o <<" , l_= "<< oo <<" ] = "<< setprecision(15) << f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals] << endl; // if(o==oo){ //std::cout << w_index <<"\t"<< o <<"\t"<< oo <<"\t"<< imag(iw) <<"\t"<< setprecision(15) << f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals] << endl; if(rank==0){ delta_init << w_index+1 <<"\t"<< o+1 <<"\t"<< oo+1 <<"\t"<< imag(iw) <<"\t"<< setprecision(17) << fixed << f_iw_ptr[o+oo*num_orbitals+w_index*num_orbitals*num_orbitals] << endl; } } } } if(rank==0 && verbo>0) std::cout <<" == F(iw) Initialized == "<< endl << endl; triqs::clef::placeholder<0> om_; auto g0_iw = gf<imfreq>{{beta, Fermion, Nfreq}, {num_orbitals,num_orbitals}}; g0_iw(om_) << om_ + mu - delta_iw(om_); //calculate G0(iw)^-1 matrix if(rank==0 && verbo>0) std::cout <<" == G0(iw)^-1 Initialized == "<< endl << endl; if(tot_not){ solver.G0_iw()[0] = triqs::gfs::inverse( g0_iw ); //inverse G0(iw) matrix and affect to solver }else{ for (int i = 0; i < nspin; ++i){ solver.G0_iw()[i] = triqs::gfs::inverse( g0_iw ); } } if(rank==0 && verbo>0) std::cout <<" == G0(iw)^-1 Inverted => G0(iw) Constructed == "<< endl << endl; // if(rank==0){ //Output Test of none interacting G0 // ofstream G0_up, G0_down; // G0_up.open("<API key>"); // G0_up << "# w_index l l' Im(iw) Real(G0) Im(G0)\n" << endl; // //Report G0_iw // int compteur = 0; // for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ // auto iw = w_mesh.index_to_point(w_index); // for(int oo = 0; oo < num_orbitals; ++oo){ // for(int o = 0; o < num_orbitals; ++o){ // G0_up << fixed << w_index <<"\t"<< o <<"\t"<< oo <<"\t"<< fixed<< imag(iw) <<"\t"<< real(solver.G0_iw()[0].data()(w_index,o,oo)) <<"\t"<< imag(solver.G0_iw()[0].data()(w_index,o,oo)) << endl; // compteur++; if(rank==0 && verbo>0) std::cout <<" == Solver Parametrization == "<< endl << endl; // Solver parameters auto paramCTQMC = solve_parameters_t(H, n_cycles); paramCTQMC.max_time = -1; paramCTQMC.random_name = ""; paramCTQMC.random_seed = 123 * rank + 567;//seed; paramCTQMC.length_cycle = cycle_length; paramCTQMC.n_warmup_cycles = ntherm; paramCTQMC.verbosity=verbo; paramCTQMC.measure_g_l = leg_measure; //paramCTQMC.move_double = true; // paramCTQMC.make_histograms=hist; if(rank==0 && verbo>0) std::cout <<" == Starting Solver [node "<< rank <<"] == "<< endl << endl; // Solve! solver.solve(paramCTQMC); if(rank==0 && verbo>0) std::cout <<" == Reporting == "<< endl << endl; // Report some stuff // if(rank==0){ // ofstream glegendre, g_iw; // g_iw.open("g_iw"); //Report G_iw int compteur = 0; //g_iw << fixed << setprecision(17) << w_index << "\t"; for(int oo = 0; oo < num_orbitals; ++oo){ for(int o = 0; o < num_orbitals; ++o){ for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ //Pour une frequence donnee auto iw = w_mesh.index_to_point(w_index); g_iw_ptr[compteur] = solver.G0_iw()[0].data()(w_index,o,oo); //g_iw << fixed<< setprecision(17) << solver.G0_iw()[0].data()(w_index,o,oo); compteur++; } } //g_iw << endl; } //Report G_tau compteur = 0; for(int oo = 0; oo < num_orbitals; ++oo){ for(int o = 0; o < num_orbitals; ++o){ for(int tau = 0; tau < n_tau; ++tau){ g_tau[compteur]= solver.G_tau()[0].data()(tau,o,oo); compteur++; } } } //Report G(l) if( leg_measure ){ compteur = 0; for(int oo = 0; oo < num_orbitals; ++oo){ for(int o = 0; o < num_orbitals; ++o){ for(int l = 0; l < n_l; ++l){ gl[compteur]= solver.G_l()[0].data()(l,o,oo); compteur++; } } } } //Write G(tau) if( rank==0 && wrt_files ){ ofstream gtau; gtau.open("Gtau_triqs.dat"); double _tau_=0.0; for(int tau = 0; tau < n_tau; ++tau){ _tau_=((tau*beta)/n_tau)*27.2113845; //en Harthree gtau << fixed << setprecision(17) <<_tau_ << "\t"; for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ gtau << fixed<< setprecision(17) << solver.G_tau()[0].data()(tau,o,oo) <<"\t"; } } gtau << endl; } ofstream g_iw; g_iw.open("giw"); for(std::size_t w_index = 0; w_index < w_mesh.size(); ++w_index){ auto iw = w_mesh.index_to_point(w_index); for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ g_iw << fixed << setprecision(17) << solver.G0_iw()[0].data()(w_index,o,oo); } } g_iw << endl; } } //Write U(i,j) if( rank==0 && wrt_files ){ ofstream umat; umat.open("umat"); for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ umat <<"U( "<< o+1 <<" , "<< oo+1 <<" )= "<< fixed << setprecision(17) << umat_ij[o+(oo*num_orbitals)] <<endl; } } } if( leg_measure && rank==0 && wrt_files ){ ofstream g_l; g_l.open("gl"); for(int l = 0; l < n_l; ++l){ for(int o = 0; o < num_orbitals; ++o){ for(int oo = 0; oo < num_orbitals; ++oo){ g_l << fixed << setprecision(17) << solver.G_l()[0].data()(l,o,oo) <<"\t"; } } g_l << endl; } } if(rank==0 && verbo>0) std::cout <<" == CTHYB-QMC Process Finished [node "<< rank <<"] == "<< endl << endl; } // Hamiltonian Initialization with precalculate coeff (J=0 and U(i,j)) many_body_operator<double> init_Hamiltonian( double *eps, int nflavor, double *U){ many_body_operator<double> H; double coeff; for(int i = 0; i < nflavor; ++i) for(int j = 0; j < nflavor; ++j){ //cas diago principale: if(i==j){ H += eps[i] * n("tot",i) ; } else{ coeff = double(U[i+j*nflavor])*0.5; //cout << "U = "<< U[i+j*nflavor] <<" /2 = "<< coeff <<endl; H += coeff * n("tot",i) * n("tot",j); } } return H; } // Hamiltonian Initialization with precalculated coeff U(i,j,k,l) in "tot" notation many_body_operator<double> <API key>( double *eps, int nflavor, double *U){ many_body_operator<double> H; double coeff; for(int i = 0; i < nflavor; ++i) for(int j = 0; j < nflavor; ++j){ if(i==j){ H += eps[i] * n("tot",i) ; //Levels On diagonal Hamiltonian Matrix } for(int k = 0; k < nflavor; ++k) for(int l = 0; l < nflavor; ++l){ //cas diago principale: coeff = 0.5 * double( U[i+j*nflavor+k*nflavor*nflavor+l*nflavor*nflavor*nflavor] ); H += coeff * c_dag("tot",i)*c_dag("tot",j)*c("tot",l)*c("tot",k); //changing l <-> k order index to be in accordance with the Abinit definition } } return H; } // Hamiltonian Initialization with precalculated coeff U(i,j,k,l) in "up" and "down" notation many_body_operator<double> <API key>( double *eps, int nflavor, double *U ){ many_body_operator<double> H; double coeff; for(int i = 0; i < nflavor; ++i) for(int j = 0; j < nflavor; ++j){ if(i==j){ H += eps[i] * ( n("up",i) + n("down",i) ); //Levels On diagonal Hamiltonian Matrix } for(int k = 0; k < nflavor; ++k) for(int l = 0; l < nflavor; ++l){ coeff = 0.5 * double(U[i+j*nflavor+k*nflavor*nflavor+l*nflavor*nflavor*nflavor]); // for(int s = 0; s < nspin; ++s) // for(int s1 = 0; s1 < nspin; ++s1){ H += coeff * c_dag("up",i) * c_dag("down",j) * c("up",l) * c("down",k); H += coeff * c_dag("down",i) * c_dag("up",j) * c("down",l) * c("up",k); } } return H; }
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the $capabilities = array( 'block/fn_marking:myaddinstance' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), '<API key>' => 'moodle/my:manageblocks' ), 'block/fn_marking:addinstance' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), '<API key>' => 'moodle/site:manageblocks' ), 'block/fn_marking:viewblock' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'user' => CAP_PREVENT, 'guest' => CAP_PREVENT, 'student' => CAP_PREVENT, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'block/fn_marking:viewreadonly' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'user' => CAP_PREVENT, 'guest' => CAP_PREVENT, 'student' => CAP_PREVENT, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ) );
// Search script generated by doxygen // The code in this file is loosly based on main.js, part of Natural Docs, var <API key> = { 0: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111001110111111111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 1: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011010000001010110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 2: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111100010001110111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 3: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000111111111001110111101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 4: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101111111001110111110111100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 5: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010010000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 6: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011110000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", 7: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "files", 3: "functions", 4: "variables", 5: "typedefs", 6: "defines", 7: "pages" }; function convertToId(search) { var result = ''; for (i=0;i<search.length;i++) { var c = search.charAt(i); var cn = c.charCodeAt(0); if (c.match(/[a-z0-9]/)) { result+=c; } else if (cn<16) { result+="_0"+cn.toString(16); } else { result+="_"+cn.toString(16); } } return result; } function getXPos(item) { var x = 0; if (item.offsetWidth) { while (item && item!=document.body) { x += item.offsetLeft; item = item.offsetParent; } } return x; } function getYPos(item) { var y = 0; if (item.offsetWidth) { while (item && item!=document.body) { y += item.offsetTop; item = item.offsetParent; } } return y; } /* A class handling everything associated with the search panel. Parameters: name - The name of the global variable that will be storing this instance. Is needed to be able to set timeouts. resultPath - path to use for external files */ function SearchBox(name, resultsPath, inFrame, label) { if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); } this.name = name; this.resultsPath = resultsPath; this.keyTimeout = 0; this.keyTimeoutLength = 500; this.<API key> = 300; this.lastSearchValue = ""; this.lastResultsPage = ""; this.hideTimeout = 0; this.searchIndex = 0; this.searchActive = false; this.insideFrame = inFrame; this.searchLabel = label; this.DOMSearchField = function() { return document.getElementById("MSearchField"); } this.DOMSearchSelect = function() { return document.getElementById("MSearchSelect"); } this.<API key> = function() { return document.getElementById("MSearchSelectWindow"); } this.<API key> = function() { return document.getElementById("MSearchResults"); } this.<API key> = function() { return document.getElementById("<API key>"); } this.DOMSearchClose = function() { return document.getElementById("MSearchClose"); } this.DOMSearchBox = function() { return document.getElementById("MSearchBox"); } // Called when focus is added or removed from the search field. this.OnSearchFieldFocus = function(isActive) { this.Activate(isActive); } this.OnSearchSelectShow = function() { var searchSelectWindow = this.<API key>(); var searchField = this.DOMSearchSelect(); if (this.insideFrame) { var left = getXPos(searchField); var top = getYPos(searchField); left += searchField.offsetWidth + 6; top += searchField.offsetHeight; // show search selection popup searchSelectWindow.style.display='block'; left -= searchSelectWindow.offsetWidth; searchSelectWindow.style.left = left + 'px'; searchSelectWindow.style.top = top + 'px'; } else { var left = getXPos(searchField); var top = getYPos(searchField); top += searchField.offsetHeight; // show search selection popup searchSelectWindow.style.display='block'; searchSelectWindow.style.left = left + 'px'; searchSelectWindow.style.top = top + 'px'; } // stop selection hide timer if (this.hideTimeout) { clearTimeout(this.hideTimeout); this.hideTimeout=0; } return false; // to avoid "image drag" default event } this.OnSearchSelectHide = function() { this.hideTimeout = setTimeout(this.name +".<API key>()", this.<API key>); } // Called when the content of the search field is changed. this.OnSearchFieldChange = function(evt) { if (this.keyTimeout) // kill running timer { clearTimeout(this.keyTimeout); this.keyTimeout = 0; } var e = (evt) ? evt : window.event; // for IE if (e.keyCode==40 || e.keyCode==13) { if (e.shiftKey==1) { this.OnSearchSelectShow(); var win=this.<API key>(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { child.focus(); return; } } return; } else if (window.frames.MSearchResults.searchResults) { var elem = window.frames.MSearchResults.searchResults.NavNext(0); if (elem) elem.focus(); } } else if (e.keyCode==27) // Escape out of the search field { this.DOMSearchField().blur(); this.<API key>().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.lastSearchValue = ''; this.Activate(false); return; } // strip whitespaces var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); if (searchValue != this.lastSearchValue) // search value has changed { if (searchValue != "") // non-empty search { // set timer for search update this.keyTimeout = setTimeout(this.name + '.Search()', this.keyTimeoutLength); } else // empty search field { this.<API key>().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.lastSearchValue = ''; } } } this.SelectItemCount = function(id) { var count=0; var win=this.<API key>(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { count++; } } return count; } this.SelectItemSet = function(id) { var i,j=0; var win=this.<API key>(); for (i=0;i<win.childNodes.length;i++) { var child = win.childNodes[i]; // get span within a if (child.className=='SelectItem') { var node = child.firstChild; if (j==id) { node.innerHTML='&#8226;'; } else { node.innerHTML='&#160;'; } j++; } } } // Called when an search filter selection is made. // set item with index id as the active item this.OnSelectItem = function(id) { this.searchIndex = id; this.SelectItemSet(id); var searchValue = this.DOMSearchField().value.replace(/ +/g, ""); if (searchValue!="" && this.searchActive) // something was found -> do a search { this.Search(); } } this.OnSearchSelectKey = function(evt) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down { this.searchIndex++; this.OnSelectItem(this.searchIndex); } else if (e.keyCode==38 && this.searchIndex>0) { this.searchIndex this.OnSelectItem(this.searchIndex); } else if (e.keyCode==13 || e.keyCode==27) { this.OnSelectItem(this.searchIndex); this.<API key>(); this.DOMSearchField().focus(); } return false; } // Closes the results window. this.CloseResultsWindow = function() { this.<API key>().style.display = 'none'; this.DOMSearchClose().style.display = 'none'; this.Activate(false); } this.<API key> = function() { this.<API key>().style.display = 'none'; } // Performs a search. this.Search = function() { this.keyTimeout = 0; // strip leading whitespace var searchValue = this.DOMSearchField().value.replace(/^ +/, ""); var code = searchValue.toLowerCase().charCodeAt(0); var hexCode; if (code<16) { hexCode="0"+code.toString(16); } else { hexCode=code.toString(16); } var resultsPage; var <API key>; var hasResultsPage; if (<API key>[this.searchIndex].charAt(code) == '1') { resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html'; <API key> = resultsPage+'?'+escape(searchValue); hasResultsPage = true; } else // nothing available for this search term { resultsPage = this.resultsPath + '/nomatches.html'; <API key> = resultsPage; hasResultsPage = false; } window.frames.MSearchResults.location = <API key>; var <API key> = this.<API key>(); if (<API key>.style.display!='block') { var domSearchBox = this.DOMSearchBox(); this.DOMSearchClose().style.display = 'inline'; if (this.insideFrame) { var <API key> = this.<API key>(); <API key>.style.position = 'relative'; <API key>.style.display = 'block'; var width = document.body.clientWidth - 8; // the -8 is for IE :-( <API key>.style.width = width + 'px'; <API key>.style.width = width + 'px'; } else { var <API key> = this.<API key>(); var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth; var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1; <API key>.style.display = 'block'; left -= <API key>.offsetWidth; <API key>.style.top = top + 'px'; <API key>.style.left = left + 'px'; } } this.lastSearchValue = searchValue; this.lastResultsPage = resultsPage; } // Activates or deactivates the search panel, resetting things to // their default values if necessary. this.Activate = function(isActive) { if (isActive || // open it this.<API key>().style.display == 'block' ) { this.DOMSearchBox().className = 'MSearchBoxActive'; var searchField = this.DOMSearchField(); if (searchField.value == this.searchLabel) // clear "Search" term upon entry { searchField.value = ''; this.searchActive = true; } } else if (!isActive) // directly remove the panel { this.DOMSearchBox().className = 'MSearchBoxInactive'; this.DOMSearchField().value = this.searchLabel; this.searchActive = false; this.lastSearchValue = '' this.lastResultsPage = ''; } } } // The class that handles everything on the search results page. function SearchResults(name) { // The number of matches from the last run of <Search()>. this.lastMatchCount = 0; this.lastKey = 0; this.repeatOn = false; // Toggles the visibility of the passed element ID. this.FindChildElement = function(id) { var parentElement = document.getElementById(id); var element = parentElement.firstChild; while (element && element!=parentElement) { if (element.nodeName == 'DIV' && element.className == 'SRChildren') { return element; } if (element.nodeName == 'DIV' && element.hasChildNodes()) { element = element.firstChild; } else if (element.nextSibling) { element = element.nextSibling; } else { do { element = element.parentNode; } while (element && element!=parentElement && !element.nextSibling); if (element && element!=parentElement) { element = element.nextSibling; } } } } this.Toggle = function(id) { var element = this.FindChildElement(id); if (element) { if (element.style.display == 'block') { element.style.display = 'none'; } else { element.style.display = 'block'; } } } // Searches for the passed string. If there is no parameter, // it takes it from the URL query. // Always returns true, since other documents may try to call it // and that may or may not be possible. this.Search = function(search) { if (!search) // get search word from URL { search = window.location.search; search = search.substring(1); // Remove the leading '?' search = unescape(search); } search = search.replace(/^ +/, ""); // strip leading spaces search = search.replace(/ +$/, ""); // strip trailing spaces search = search.toLowerCase(); search = convertToId(search); var resultRows = document.<API key>("div"); var matches = 0; var i = 0; while (i < resultRows.length) { var row = resultRows.item(i); if (row.className == "SRResult") { var rowMatchName = row.id.toLowerCase(); rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_' if (search.length<=rowMatchName.length && rowMatchName.substr(0, search.length)==search) { row.style.display = 'block'; matches++; } else { row.style.display = 'none'; } } i++; } document.getElementById("Searching").style.display='none'; if (matches == 0) // no results { document.getElementById("NoMatches").style.display='block'; } else // at least one result { document.getElementById("NoMatches").style.display='none'; } this.lastMatchCount = matches; return true; } // return the first item with index index or higher that is visible this.NavNext = function(index) { var focusItem; while (1) { var focusName = 'Item'+index; focusItem = document.getElementById(focusName); if (focusItem && focusItem.parentNode.parentNode.style.display=='block') { break; } else if (!focusItem) // last element { break; } focusItem=null; index++; } return focusItem; } this.NavPrev = function(index) { var focusItem; while (1) { var focusName = 'Item'+index; focusItem = document.getElementById(focusName); if (focusItem && focusItem.parentNode.parentNode.style.display=='block') { break; } else if (!focusItem) // last element { break; } focusItem=null; index } return focusItem; } this.ProcessKeys = function(e) { if (e.type == "keydown") { this.repeatOn = false; this.lastKey = e.keyCode; } else if (e.type == "keypress") { if (!this.repeatOn) { if (this.lastKey) this.repeatOn = true; return false; // ignore first keypress after keydown } } else if (e.type == "keyup") { this.lastKey = 0; this.repeatOn = false; } return this.lastKey!=0; } this.Nav = function(evt,itemIndex) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==13) return true; if (!this.ProcessKeys(e)) return false; if (this.lastKey==38) { var newIndex = itemIndex-1; var focusItem = this.NavPrev(newIndex); if (focusItem) { var child = this.FindChildElement(focusItem.parentNode.parentNode.id); if (child && child.style.display == 'block') // children visible { var n=0; var tmpElem; while (1) // search for last child { tmpElem = document.getElementById('Item'+newIndex+'_c'+n); if (tmpElem) { focusItem = tmpElem; } else // found it! { break; } n++; } } } if (focusItem) { focusItem.focus(); } else // return focus to search field { parent.document.getElementById("MSearchField").focus(); } } else if (this.lastKey==40) // Down { var newIndex = itemIndex+1; var focusItem; var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem && elem.style.display == 'block') // children visible { focusItem = document.getElementById('Item'+itemIndex+'_c0'); } if (!focusItem) focusItem = this.NavNext(newIndex); if (focusItem) focusItem.focus(); } else if (this.lastKey==39) // Right { var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem) elem.style.display = 'block'; } else if (this.lastKey==37) // Left { var item = document.getElementById('Item'+itemIndex); var elem = this.FindChildElement(item.parentNode.parentNode.id); if (elem) elem.style.display = 'none'; } else if (this.lastKey==27) // Escape { parent.searchBox.CloseResultsWindow(); parent.document.getElementById("MSearchField").focus(); } else if (this.lastKey==13) // Enter { return true; } return false; } this.NavChild = function(evt,itemIndex,childIndex) { var e = (evt) ? evt : window.event; // for IE if (e.keyCode==13) return true; if (!this.ProcessKeys(e)) return false; if (this.lastKey==38) { if (childIndex>0) { var newIndex = childIndex-1; document.getElementById('Item'+itemIndex+'_c'+newIndex).focus(); } else // already at first child, jump to parent { document.getElementById('Item'+itemIndex).focus(); } } else if (this.lastKey==40) // Down { var newIndex = childIndex+1; var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex); if (!elem) // last child, jump to parent next parent { elem = this.NavNext(itemIndex+1); } if (elem) { elem.focus(); } } else if (this.lastKey==27) // Escape { parent.searchBox.CloseResultsWindow(); parent.document.getElementById("MSearchField").focus(); } else if (this.lastKey==13) // Enter { return true; } return false; } } function setKeyActions(elem,action) { elem.setAttribute('onkeydown',action); elem.setAttribute('onkeypress',action); elem.setAttribute('onkeyup',action); } function setClassAttr(elem,attr) { elem.setAttribute('class',attr); elem.setAttribute('className',attr); } function createResults() { var results = document.getElementById("SRResults"); for (var e=0; e<searchData.length; e++) { var id = searchData[e][0]; var srResult = document.createElement('div'); srResult.setAttribute('id','SR_'+id); setClassAttr(srResult,'SRResult'); var srEntry = document.createElement('div'); setClassAttr(srEntry,'SREntry'); var srLink = document.createElement('a'); srLink.setAttribute('id','Item'+e); setKeyActions(srLink,'return searchResults.Nav(event,'+e+')'); setClassAttr(srLink,'SRSymbol'); srLink.innerHTML = searchData[e][1][0]; srEntry.appendChild(srLink); if (searchData[e][1].length==2) // single result { srLink.setAttribute('href',searchData[e][1][1][0]); if (searchData[e][1][1][1]) { srLink.setAttribute('target','_parent'); } var srScope = document.createElement('span'); setClassAttr(srScope,'SRScope'); srScope.innerHTML = searchData[e][1][1][2]; srEntry.appendChild(srScope); } else // multiple results { srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")'); var srChildren = document.createElement('div'); setClassAttr(srChildren,'SRChildren'); for (var c=0; c<searchData[e][1].length-1; c++) { var srChild = document.createElement('a'); srChild.setAttribute('id','Item'+e+'_c'+c); setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')'); setClassAttr(srChild,'SRScope'); srChild.setAttribute('href',searchData[e][1][c+1][0]); if (searchData[e][1][c+1][1]) { srChild.setAttribute('target','_parent'); } srChild.innerHTML = searchData[e][1][c+1][2]; srChildren.appendChild(srChild); } srEntry.appendChild(srChildren); } srResult.appendChild(srEntry); results.appendChild(srResult); } }
#include "entrymanager.h" #include <QDateTime> #include <QSqlDatabase> #include <QSqlQuery> #include <QVariant> #include <QDebug> using namespace Core; EntryManager::~EntryManager() { clear(); } void EntryManager::close(int entryId) { Entry* entry = getEntry(entryId); if (!entry) return; delete entry; m_entries.erase(entryId); } void EntryManager::clear() { for (auto entry : m_entries) { save(entry.first); delete entry.second; } m_entries.clear(); } bool EntryManager::save(int entryId) const { Entry* entry = m_entries.at(entryId); if (!entry->isModified) return true; entry->timestamp = QDateTime().toTime_t(); entry->isModified = false; QSqlDatabase db = QSqlDatabase::database(); QSqlQuery query(db); query.prepare(QStringLiteral("UPDATE entries SET content = ?, timestamp = ? WHERE id= ?")); query.addBindValue(entry->content); query.addBindValue(entry->timestamp); query.addBindValue(entryId); return query.exec(); } bool EntryManager::load(int entryId) { QSqlDatabase db = QSqlDatabase::database(); QSqlQuery query(db); query.prepare(QStringLiteral("SELECT id, content, timestamp FROM entries WHERE id= ?")); query.addBindValue(entryId); if (!query.exec()) return false; query.next(); Entry* entry = new Entry; entry->id = query.value(0).toInt(); entry->content = query.value(1).toString(); entry->timestamp = query.value(2).toUInt(); m_entries.insert(std::make_pair<>(entry->id, entry)); return true; } Entry* EntryManager::getEntry(int entryId) { auto it = m_entries.find(entryId); if (it == m_entries.end()) if (!load(entryId)) return nullptr; return m_entries.at(entryId); }
# Rain_Water_Trapping def trappedWater(a, size) : # left[i] stores height of tallest bar to the to left of it including itself left = [0] * size # Right [i] stores height of tallest bar to the to right of it including itself right = [0] * size # Initialize result waterVolume = 0 # filling left (list/array) left[0] = a[0] for i in range( 1, size): left[i] = max(left[i-1], a[i]) # filling right (list/array) right[size - 1] = a[size - 1] for i in range(size - 2, - 1, - 1): right[i] = max(right[i + 1], a[i]); # Calculating volume of the accumulated water element by element for i in range(0, size): waterVolume += min(left[i],right[i]) - a[i] return waterVolume # main program arr =[] n = int(input()) #input the number of towers for i in range(n): arr.append(int(input())) #storing length of each tower in array print("Maximum water that can be accumulated is ", trappedWater(arr, len(arr))) #Input: #Output: #The maximum water trapped is 6
using System.Reflection; using System.Runtime.CompilerServices; namespace System.Security.Principal { public interface IIdentity { string AuthenticationType { get; } bool IsAuthenticated { get; } string Name { get; } } }
package ch.hevs.silab.structuredsim.interfaces; import java.util.List; /** * Name : IManageModifier * <p> * Description : Class to manage the modifier * <p> * Date : 25 July 2017 * @version 1.0 * @author Audrey Dupont */ public interface IManageModifier { /** * Method to initiate the modifier class inside a List */ public List<AModifier> <API key>(); }
## Contribution If you want to add any enhancement feature or have found any bug and want to work on it, please open a new issue regarding that and put a message "I would like to work on it." And make sure every pull request should reference to an issue. # Points on how to make pull request * You need to fork this repository to your account. * Clone it using ``` git clone https://github.com/FOSSEE/eSim.git ``` * Always create a new branch before making any changes. You can create new branch using ```git branch <branch-name> ``` * Checkout into your new branch using ```git checkout <branch-name>``` * Make changes to code and once you are done use ```git add <path to file changed or added>```. Now commit changes with proper message using ```git commit -m "Your message"```. * After commiting your changes push your changes to your forked repository using ```git push origin <branch-name>``` Finally create a pull request from github. There should be only one commit per pull request. * Please follow below guidelines for your commit message : * Commit message should be like : Fixes issue #[issue_number] - one line message of work you did. * After commit message, there should be a commit body where you can mention what you did in short or in detail. Please follow above method to file pull requests.
var __v=[ { "Id": 2046, "Chapter": 630, "Name": "c++", "Sort": 0 } ]
#ifdef _MSC_VER #pragma once #endif #ifndef <API key> #define <API key> #include <ogdf/basic/EdgeArray.h> #include <ogdf/layered/CrossingsMatrix.h> #include <ogdf/simultaneous/<API key>.h> namespace ogdf { //! The split heuristic for 2-layer crossing minimization. class OGDF_EXPORT SplitHeuristic : public <API key> { public: //! Initializes crossing minimization for hierarchy \a H. void init (const Hierarchy &H); //! Calls the split heuristic for level \a L. void call (Level &L); //! Calls the median heuristic for level \a L (simultaneous drawing). void call (Level &L, const EdgeArray<unsigned int> *edgeSubGraph); //! Does some clean-up after calls. void cleanup (); private: CrossingsMatrix *m_cm; Array<node> buffer; void recCall(Level&, int low, int high); }; }// end namespace ogdf #endif
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Mon May 06 00:15:52 EDT 2013 --> <title>Uses of Class org.spongycastle.asn1.x509.ReasonFlags</title> <meta name="date" content="2013-05-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.spongycastle.asn1.x509.ReasonFlags"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/spongycastle/asn1/x509/class-use/ReasonFlags.html" target="_top">Frames</a></li> <li><a href="ReasonFlags.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.spongycastle.asn1.x509.ReasonFlags" class="title">Uses of Class<br>org.spongycastle.asn1.x509.ReasonFlags</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.spongycastle.asn1.x509">org.spongycastle.asn1.x509</a></td> <td class="colLast"> <div class="block">Support classes useful for encoding and processing X.509 certificates.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.spongycastle.asn1.x509"> </a> <h3>Uses of <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a> in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a> declared as <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>private <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong"><API key>.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/<API key>.html#onlySomeReasons">onlySomeReasons</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>(package private) <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong">DistributionPoint.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/DistributionPoint.html#reasons">reasons</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a> that return <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong"><API key>.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/<API key>.html#getOnlySomeReasons()">getOnlySomeReasons</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></code></td> <td class="colLast"><span class="strong">DistributionPoint.</span><code><strong><a href="../../../../../org/spongycastle/asn1/x509/DistributionPoint.html#getReasons()">getReasons</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../org/spongycastle/asn1/x509/package-summary.html">org.spongycastle.asn1.x509</a> with parameters of type <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../org/spongycastle/asn1/x509/DistributionPoint.html#DistributionPoint(org.spongycastle.asn1.x509.<API key>, org.spongycastle.asn1.x509.ReasonFlags, org.spongycastle.asn1.x509.GeneralNames)">DistributionPoint</a></strong>(<a href="../../../../../org/spongycastle/asn1/x509/<API key>.html" title="class in org.spongycastle.asn1.x509"><API key></a>&nbsp;distributionPoint, <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a>&nbsp;reasons, <a href="../../../../../org/spongycastle/asn1/x509/GeneralNames.html" title="class in org.spongycastle.asn1.x509">GeneralNames</a>&nbsp;cRLIssuer)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../org/spongycastle/asn1/x509/<API key>.html#<API key>(org.spongycastle.asn1.x509.<API key>, boolean, boolean, org.spongycastle.asn1.x509.ReasonFlags, boolean, boolean)"><API key></a></strong>(<a href="../../../../../org/spongycastle/asn1/x509/<API key>.html" title="class in org.spongycastle.asn1.x509"><API key></a>&nbsp;distributionPoint, boolean&nbsp;<API key>, boolean&nbsp;onlyContainsCACerts, <a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">ReasonFlags</a>&nbsp;onlySomeReasons, boolean&nbsp;indirectCRL, boolean&nbsp;<API key>)</code> <div class="block">Constructor from given details.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/spongycastle/asn1/x509/ReasonFlags.html" title="class in org.spongycastle.asn1.x509">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/spongycastle/asn1/x509/class-use/ReasonFlags.html" target="_top">Frames</a></li> <li><a href="ReasonFlags.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
<?php $plugin->version = 2012060700; //EOF
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="fr"> <context> <name></name> <message id="<API key>"> <location filename="asteroid-timer.desktop.h" line="6"/> <source>Timer</source> <translation>Timer</translation> </message> </context> </TS>
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- #ifndef _DEFINES_H #define _DEFINES_H #include <AP_HAL_Boards.h> // Just so that it's completely clear... #define ENABLED 1 #define DISABLED 0 // this avoids a very common config error #define ENABLE ENABLED #define DISABLE DISABLED // Flight modes #define YAW_HOLD 0 // heading hold at heading in control_yaw but allow input from pilot #define YAW_ACRO 1 // pilot controlled yaw using rate controller #define YAW_LOOK_AT_NEXT_WP 2 // point towards next waypoint (no pilot input accepted) #define <API key> 3 // point towards a location held in yaw_look_at_WP (no pilot input accepted) #define YAW_CIRCLE 4 // point towards a location held in yaw_look_at_WP (no pilot input accepted) #define YAW_LOOK_AT_HOME 5 // point towards home (no pilot input accepted) #define YAW_LOOK_AT_HEADING 6 // point towards a particular angle (not pilot input accepted) #define YAW_LOOK_AHEAD 7 // WARNING! CODE IN DEVELOPMENT NOT PROVEN #define YAW_DRIFT 8 #define YAW_RESETTOARMEDYAW 9 // point towards heading at time motors were armed #define ROLL_PITCH_STABLE 0 // pilot input roll, pitch angles #define ROLL_PITCH_ACRO 1 // pilot inputs roll, pitch rotation rates in body frame #define ROLL_PITCH_AUTO 2 // no pilot input. autopilot roll, pitch is sent to stabilize controller inputs #define <API key> 3 // pilot inputs roll, pitch angles which are mixed with optical flow based position controller lean anbles #define ROLL_PITCH_DRIFT 4 #define ROLL_PITCH_LOITER 5 // pilot inputs the desired horizontal velocities #define ROLL_PITCH_SPORT 6 // pilot inputs roll, pitch rotation rates in earth frame #define ROLL_PITCH_AUTOTUNE 7 // description of new roll-pitch mode #define ROLL_PITCH_HYBRID 8 // ST-JD pilot input roll, pitch angles when sticks are moved #define THROTTLE_MANUAL 0 // manual throttle mode - pilot input goes directly to motors #define <API key> 1 // mostly manual throttle but with some tilt compensation #define THROTTLE_HOLD 2 // alt hold plus pilot input of climb rate #define THROTTLE_AUTO 3 // auto pilot altitude controller with target altitude held in next_WP.alt #define THROTTLE_LAND 4 // landing throttle controller #define <API key> 5 // pilot manually controlled throttle for traditional helicopters // sonar - for use with CONFIG_SONAR_SOURCE #define SONAR_SOURCE_ADC 1 #define <API key> 2 // Ch6, Ch7 and Ch8 aux switch control #define <API key> 1800 // pwm value above which the ch7 or ch8 option will be invoked #define <API key> 1200 // pwm value below which the ch7 or ch8 option will be disabled #define <API key> 1800 #define CH6_PWM_TRIGGER_LOW 1200 #define <API key> 0 // aux switch disabled #define <API key> 1 // deprecated #define AUX_SWITCH_FLIP 2 // flip #define <API key> 3 // change to simple mode #define AUX_SWITCH_RTL 4 // change to RTL flight mode #define <API key> 5 // save current position as level #define <API key> 6 // deprecated #define AUX_SWITCH_SAVE_WP 7 // save mission waypoint or RTL if in auto mode #define <API key> 8 // depending upon CH6 position Flip (if ch6 is low), RTL (if ch6 in middle) or Save WP (if ch6 is high) #define <API key> 9 // trigger camera servo or relay #define AUX_SWITCH_SONAR 10 // allow enabling or disabling sonar in flight which helps avoid surface tracking when you are far above the ground #define AUX_SWITCH_FENCE 11 // allow enabling or disabling fence in flight #define <API key> 12 // changes yaw to be same as when quad was armed #define <API key> 13 // change to simple mode in middle, super simple at top #define <API key> 14 // low = disabled, middle = leveled, high = leveled and limited #define AUX_SWITCH_SPRAYER 15 // enable/disable the crop sprayer #define AUX_SWITCH_AUTO 16 // change to auto flight mode #define AUX_SWITCH_AUTOTUNE 17 // auto tune #define AUX_SWITCH_LAND 18 // change to LAND flight mode // values used by the ap.ch7_opt and ap.ch8_opt flags #define AUX_SWITCH_LOW 0 // indicates auxiliar switch is in the low position (pwm <1200) #define AUX_SWITCH_MIDDLE 1 // indicates auxiliar switch is in the middle position (pwm >1200, <1800) #define AUX_SWITCH_HIGH 2 // indicates auxiliar switch is in the high position (pwm >1800) // Frame types #define UNDEFINED_FRAME 0 #define QUAD_FRAME 1 #define TRI_FRAME 2 #define HEXA_FRAME 3 #define Y6_FRAME 4 #define OCTA_FRAME 5 #define HELI_FRAME 6 #define OCTA_QUAD_FRAME 7 #define SINGLE_FRAME 8 #define PLUS_FRAME 0 #define X_FRAME 1 #define V_FRAME 2 // LED output #define NORMAL_LEDS 0 #define SAVE_TRIM_LEDS 1 // Internal defines, don't edit and expect things to work #define TRUE 1 #define FALSE 0 #define ToRad(x) radians(x) // *pi/180 #define ToDeg(x) degrees(x) // *180/pi #define DEBUG 0 #define LOITER_RANGE 60 // for calculating power outside of loiter radius #define T6 1000000 #define T7 10000000 // GPS type codes - use the names, not the numbers #define GPS_PROTOCOL_NONE -1 #define GPS_PROTOCOL_NMEA 0 #define GPS_PROTOCOL_SIRF 1 #define GPS_PROTOCOL_UBLOX 2 #define GPS_PROTOCOL_IMU 3 #define GPS_PROTOCOL_MTK 4 #define GPS_PROTOCOL_HIL 5 #define GPS_PROTOCOL_MTK19 6 #define GPS_PROTOCOL_AUTO 7 // HIL enumerations #define HIL_MODE_DISABLED 0 #define HIL_MODE_ATTITUDE 1 #define HIL_MODE_SENSORS 2 // Altitude status definitions #define REACHED_ALT 0 #define DESCENDING 1 #define ASCENDING 2 // Auto Pilot modes #define STABILIZE 0 // hold level position #define ACRO 1 // rate control #define ALT_HOLD 2 // AUTO control #define AUTO 3 // AUTO control #define GUIDED 4 // AUTO control #define LOITER 5 // Hold a single location #define RTL 6 // AUTO control #define CIRCLE 7 // AUTO control #define POSITION 8 // AUTO control #define LAND 9 // AUTO control #define OF_LOITER 10 // Hold a single location using optical flow sensor #define DRIFT 11 // DRIFT mode (Note: 12 is no longer used) #define SPORT 13 // earth frame rate control #define HYBRID 14 // ST-JD Hybrid mode = Loiter with direct stick commands #define NUM_MODES 15 // CH_6 Tuning #define CH6_NONE 0 // no tuning performed #define <API key> 1 // stabilize roll/pitch angle controller's P term #define <API key> 4 // body frame roll/pitch rate controller's P term #define <API key> 5 // body frame roll/pitch rate controller's I term #define <API key> 21 // body frame roll/pitch rate controller's D term #define <API key> 3 // stabilize yaw heading controller's P term #define CH6_YAW_RATE_KP 6 // body frame yaw rate controller's P term #define CH6_YAW_RATE_KD 26 // body frame yaw rate controller's D term #define <API key> 14 // altitude hold controller's P term (alt error to desired rate) #define <API key> 7 // throttle rate controller's P term (desired rate to acceleration or motor output) #define <API key> 37 // throttle rate controller's D term (desired rate to acceleration or motor output) #define <API key> 34 // accel based throttle controller's P term #define <API key> 35 // accel based throttle controller's I term #define <API key> 36 // accel based throttle controller's D term #define <API key> 12 // loiter distance controller's P term (position error to speed) #define CH6_LOITER_RATE_KP 22 // loiter rate controller's P term (speed error to tilt angle) #define CH6_LOITER_RATE_KI 28 // loiter rate controller's I term (speed error to tilt angle) #define CH6_LOITER_RATE_KD 23 // loiter rate controller's D term (speed error to tilt angle) #define CH6_WP_SPEED 10 // maximum speed to next way point (0 to 10m/s) #define CH6_ACRO_RP_KP 25 // acro controller's P term. converts pilot input to a desired roll, pitch or yaw rate #define CH6_ACRO_YAW_KP 40 // acro controller's P term. converts pilot input to a desired roll, pitch or yaw rate #define CH6_RELAY 9 // switch relay on if ch6 high, off if low #define <API key> 13 // TradHeli specific external tail gyro gain #define CH6_OPTFLOW_KP 17 // optical flow loiter controller's P term (position error to tilt angle) #define CH6_OPTFLOW_KI 18 // optical flow loiter controller's I term (position error to tilt angle) #define CH6_OPTFLOW_KD 19 // optical flow loiter controller's D term (position error to tilt angle) #define CH6_AHRS_YAW_KP 30 // ahrs's compass effect on yaw angle (0 = very low, 1 = very high) #define CH6_AHRS_KP 31 // accelerometer effect on roll/pitch angle (0=low) #define CH6_INAV_TC 32 // inertial navigation baro/accel and gps/accel time constant (1.5 = strong baro/gps correction on accel estimatehas very strong does not correct accel estimate, 7 = very weak correction) #define CH6_DECLINATION 38 // compass declination in radians #define CH6_CIRCLE_RATE 39 // circle turn rate in degrees (hard coded to about 45 degrees in either direction) #define CH6_SONAR_GAIN 41 // sonar gain // Acro Trainer types #define <API key> 0 #define <API key> 1 #define <API key> 2 // Commands - Note that APM now uses a subset of the MAVLink protocol // commands. See enum MAV_CMD in the GCS_Mavlink library #define CMD_BLANK 0 // there is no command stored in the mem location // requested #define NO_COMMAND 0 // Navigation modes held in nav_mode variable #define NAV_NONE 0 #define NAV_CIRCLE 1 #define NAV_LOITER 2 #define NAV_WP 3 #define NAV_HYBRID 4 // ST-JD: nav mode, used for initialisation on nav mode change // Yaw behaviours during missions - possible values for WP_YAW_BEHAVIOR parameter #define <API key> 0 // auto pilot will never control yaw during missions or rtl (except for DO_CONDITIONAL_YAW command received) #define <API key> 1 // auto pilot will face next waypoint or home during rtl #define <API key> 2 // auto pilot will face next waypoint except when doing RTL at which time it will stay in it's last #define <API key> 3 // auto pilot will look ahead during missions and rtl (primarily meant for traditional helicotpers) // Waypoint options #define <API key> 1 #define <API key> 2 #define WP_OPTION_YAW 4 #define <API key> 8 #define WP_OPTION_RELATIVE 16 //#define WP_OPTION_ 32 //#define WP_OPTION_ 64 #define WP_OPTION_NEXT_CMD 128 // RTL state #define RTL_STATE_START 0 #define <API key> 1 #define <API key> 2 #define <API key> 3 #define <API key> 4 #define RTL_STATE_LAND 5 // LAND state #define <API key> 0 #define <API key> 1 //repeating events #define RELAY_TOGGLE 5 // GCS Message ID's NOTE: to ensure we never block on sending MAVLink messages please keep each MSG_ to a single MAVLink message. If need be create new MSG_ IDs for additional messages on the same stream enum ap_message { MSG_HEARTBEAT, MSG_ATTITUDE, MSG_LOCATION, <API key>, <API key>, <API key>, <API key>, MSG_VFR_HUD, MSG_RADIO_OUT, MSG_RADIO_IN, MSG_RAW_IMU1, MSG_RAW_IMU2, MSG_RAW_IMU3, MSG_GPS_RAW, MSG_SYSTEM_TIME, MSG_SERVO_OUT, MSG_NEXT_WAYPOINT, MSG_NEXT_PARAM, MSG_STATUSTEXT, MSG_LIMITS_STATUS, MSG_AHRS, MSG_SIMSTATE, MSG_HWSTATUS, MSG_RETRY_DEFERRED // this must be last }; // Logging parameters #define TYPE_AIRSTART_MSG 0x00 #define <API key> 0x01 #define LOG_ATTITUDE_MSG 0x01 #define LOG_MODE_MSG 0x03 #define <API key> 0x04 #define LOG_NAV_TUNING_MSG 0x05 #define LOG_PERFORMANCE_MSG 0x06 #define LOG_CMD_MSG 0x08 #define LOG_CURRENT_MSG 0x09 #define LOG_STARTUP_MSG 0x0A #define LOG_OPTFLOW_MSG 0x0C #define LOG_EVENT_MSG 0x0D #define LOG_PID_MSG 0x0E #define LOG_COMPASS_MSG 0x0F #define LOG_INAV_MSG 0x11 #define LOG_CAMERA_MSG 0x12 #define LOG_ERROR_MSG 0x13 #define LOG_DATA_INT16_MSG 0x14 #define LOG_DATA_UINT16_MSG 0x15 #define LOG_DATA_INT32_MSG 0x16 #define LOG_DATA_UINT32_MSG 0x17 #define LOG_DATA_FLOAT_MSG 0x18 #define LOG_AUTOTUNE_MSG 0x19 #define <API key> 0x1A #define LOG_INDEX_MSG 0xF0 #define MAX_NUM_LOGS 50 #define <API key> (1<<0) #define <API key> (1<<1) #define MASK_LOG_GPS (1<<2) #define MASK_LOG_PM (1<<3) #define MASK_LOG_CTUN (1<<4) #define MASK_LOG_NTUN (1<<5) #define MASK_LOG_RCIN (1<<6) #define MASK_LOG_IMU (1<<7) #define MASK_LOG_CMD (1<<8) #define MASK_LOG_CURRENT (1<<9) #define MASK_LOG_RCOUT (1<<10) #define MASK_LOG_OPTFLOW (1<<11) #define MASK_LOG_PID (1<<12) #define MASK_LOG_COMPASS (1<<13) #define MASK_LOG_INAV (1<<14) #define MASK_LOG_CAMERA (1<<15) // DATA - event logging #define DATA_MAVLINK_FLOAT 1 #define DATA_MAVLINK_INT32 2 #define DATA_MAVLINK_INT16 3 #define DATA_MAVLINK_INT8 4 #define DATA_AP_STATE 7 #define <API key> 9 #define DATA_ARMED 10 #define DATA_DISARMED 11 #define DATA_AUTO_ARMED 15 #define DATA_TAKEOFF 16 #define DATA_LAND_COMPLETE 18 #define DATA_NOT_LANDED 28 #define DATA_LOST_GPS 19 #define DATA_BEGIN_FLIP 21 #define DATA_END_FLIP 22 #define DATA_EXIT_FLIP 23 #define DATA_SET_HOME 25 #define DATA_SET_SIMPLE_ON 26 #define DATA_SET_SIMPLE_OFF 27 #define <API key> 29 #define <API key> 30 #define DATA_AUTOTUNE_OFF 31 #define <API key> 32 #define <API key> 33 #define <API key> 34 #define <API key> 35 #define <API key> 36 #define <API key> 37 #define DATA_SAVE_TRIM 38 #define DATA_SAVEWP_ADD_WP 39 #define <API key> 40 #define DATA_FENCE_ENABLE 41 #define DATA_FENCE_DISABLE 42 #define <API key> 43 #define <API key> 44 #define <API key> 45 // RADIANS #define RADX100 0.000174532925f #define DEGX100 5729.57795f // EEPROM addresses #define EEPROM_MAX_ADDR 4096 // parameters get the first 1536 bytes of EEPROM, remainder is for waypoints #define WP_START_BYTE 0x600 // where in memory home WP is stored + all other #define WP_SIZE 15 // fence points are stored at the end of the EEPROM #define MAX_FENCEPOINTS 6 #define FENCE_WP_SIZE sizeof(Vector2l) #define FENCE_START_BYTE (EEPROM_MAX_ADDR-(MAX_FENCEPOINTS*FENCE_WP_SIZE)) #define MAX_WAYPOINTS ((FENCE_START_BYTE - WP_START_BYTE) / WP_SIZE) - 1 // safe // mark a function as not to be inlined #define NOINLINE __attribute__((noinline)) // IMU selection #define CONFIG_IMU_OILPAN 1 #define CONFIG_IMU_MPU6000 2 #define CONFIG_IMU_SITL 3 #define CONFIG_IMU_PX4 4 #define CONFIG_IMU_FLYMAPLE 5 #define AP_BARO_BMP085 1 #define AP_BARO_MS5611 2 #define AP_BARO_PX4 3 #define AP_BARO_MS5611_SPI 1 #define AP_BARO_MS5611_I2C 2 // Error message sub systems and error codes #define <API key> 1 #define <API key> 2 #define <API key> 3 #define <API key> 4 #define <API key> 5 #define <API key> 6 #define <API key> 7 #define <API key> 8 #define <API key> 9 #define <API key> 10 #define ERROR_SUBSYSTEM_GPS 11 #define <API key> 12 // general error codes #define <API key> 0 #define <API key> 1 // subsystem specific error codes -- radio #define <API key> 2 // subsystem specific error codes -- failsafe_thr, batt, gps #define <API key> 0 #define <API key> 1 // subsystem specific error codes -- compass #define <API key> 2 // subsystem specific error codes -- gps #define <API key> 2 // subsystem specific error codes -- main #define <API key> 1 // subsystem specific error codes -- crash checker #define <API key> 1 // Arming Check Enable/Disable bits #define ARMING_CHECK_NONE 0x00 #define ARMING_CHECK_ALL 0x01 #define ARMING_CHECK_BARO 0x02 #define <API key> 0x04 #define ARMING_CHECK_GPS 0x08 #define ARMING_CHECK_INS 0x10 #define <API key> 0x20 #define ARMING_CHECK_RC 0x40 #define <API key> 0x80 // Radio failsafe definitions (FS_THR parameter) #define FS_THR_DISABLED 0 #define <API key> 1 #define <API key> 2 #define <API key> 3 // Battery failsafe definitions (FS_BATT_ENABLE parameter) #define FS_BATT_DISABLED 0 // battery failsafe disabled #define FS_BATT_LAND 1 // switch to LAND mode on battery failsafe #define FS_BATT_RTL 2 // switch to RTL mode on battery failsafe // GPS Failsafe definitions (FS_GPS_ENABLE parameter) #define FS_GPS_DISABLED 0 // GPS failsafe disabled #define FS_GPS_LAND 1 // switch to LAND mode on GPS Failsafe #define FS_GPS_ALTHOLD 2 // switch to ALTHOLD mode on GPS failsafe #define <API key> 3 // switch to LAND mode on GPS failsafe even if in a manual flight mode like Stabilize #endif // _DEFINES_H
using System; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.Core; using Geekbot.Core.Database; using Geekbot.Core.Database.Models; using Geekbot.Core.ErrorHandling; using Geekbot.Core.Extensions; using Geekbot.Core.<API key>; using Geekbot.Core.<API key>; using Localization = Geekbot.Core.Localization; namespace Geekbot.Bot.Commands.Randomness { public class Ship : GeekbotCommandBase { private readonly <API key> <API key>; private readonly DatabaseContext _database; public Ship(DatabaseContext database, IErrorHandler errorHandler, <API key> <API key>, <API key> <API key>) : base(errorHandler, <API key>) { _database = database; <API key> = <API key>; } [Command("Ship", RunMode = RunMode.Async)] [Summary("Ask the Shipping meter")] public async Task Command([Summary("@user1")] IUser user1, [Summary("@user2")] IUser user2) { try { var userKeys = user1.Id < user2.Id ? new Tuple<long, long>(user1.Id.AsLong(), user2.Id.AsLong()) : new Tuple<long, long>(user2.Id.AsLong(), user1.Id.AsLong()); var dbval = _database.Ships.FirstOrDefault(s => s.FirstUserId.Equals(userKeys.Item1) && s.SecondUserId.Equals(userKeys.Item2)); var shippingRate = 0; if (dbval == null) { shippingRate = <API key>.Next(1, 100); _database.Ships.Add(new ShipsModel() { FirstUserId = userKeys.Item1, SecondUserId = userKeys.Item2, Strength = shippingRate }); await _database.SaveChangesAsync(); } else { shippingRate = dbval.Strength; } var reply = $":heartpulse: **{Localization.Ship.Matchmaking}** :heartpulse:\r\n"; reply += $":two_hearts: {user1.Mention} :heart: {user2.Mention} :two_hearts:\r\n"; reply += $"0% [{BlockCounter(shippingRate)}] 100% - {DeterminateSuccess(shippingRate)}"; await ReplyAsync(reply); } catch (Exception e) { await ErrorHandler.<API key>(e, Context); } } private string DeterminateSuccess(int rate) { return (rate / 20) switch { 0 => Localization.Ship.NotGoingToHappen, 1 => Localization.Ship.NotSuchAGoodIdea, 2 => Localization.Ship.ThereMightBeAChance, 3 => Localization.Ship.CouldWork, 4 => Localization.Ship.ItsAMatch, _ => "nope" }; } private string BlockCounter(int rate) { var amount = rate / 10; Console.WriteLine(amount); var blocks = ""; for (var i = 1; i <= 10; i++) if (i <= amount) { blocks += ":<API key>:"; if (i == amount) blocks += $" {rate}% "; } else { blocks += ":<API key>:"; } return blocks; } } }
class <API key> < ActiveRecord::Migration def change create_join_table :ip4_networks, :locations do |t| t.index [:ip4_network_id,:location_id], unique: true, name: '<API key>' end end end
using System; using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using NSubstitute; using NUnit.Framework; using Ploeh.AutoFixture.NUnit3; using Selkie.EasyNetQ; using Selkie.NUnit.Extensions; using Selkie.Services.Common.Messages; using Selkie.Windsor; namespace Selkie.Services.Racetracks.Tests { [<API key>] [TestFixture] internal sealed class ServiceTests { [Theory] [AutoNSubstituteData] public void <API key>([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act var sut = new Service(Substitute.For <ISelkieBus>(), Substitute.For <ISelkieLogger>(), Substitute.For <<API key>>()); // assert Assert.NotNull(sut); } [Theory] [AutoNSubstituteData] public void <API key>([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act service.Initialize(); string subscriptionId = service.GetType().ToString(); // assert bus.Received().SubscribeAsync(subscriptionId, Arg.Any <Action <PingRequestMessage>>()); } [Theory] [AutoNSubstituteData] public void <API key>([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act service.Start(); // assert bus.Received().Publish(Arg.Is <<API key>>(x => x.ServiceName == Service.ServiceName)); } [Theory] [AutoNSubstituteData] public void <API key>([NotNull] [Frozen] ISelkieBus bus, [NotNull] Service service) { // assemble // act service.Stop(); // assert bus.Received().Publish(Arg.Is <<API key>>(x => x.ServiceName == Service.ServiceName)); } } }
<!doctype html> <html lang="{{ .Site.Language.Lang }}" class="no-js"> <head> {{ partial "head.html" . }} </head> <body class="td-{{ .Kind }}"> <header> {{ partial "navbar.html" . }} </header> <div class="container-fluid td-outer"> <div class="td-main"> <div class="row flex-xl-nowrap"> <aside class="col-12 col-md-3 col-xl-2 td-sidebar d-print-none"> {{ partial "sidebar.html" . }} </aside> <aside class="d-none d-xl-block col-xl-2 td-sidebar-toc d-print-none"> {{ partial "page-meta-links.html" . }} {{ partial "toc.html" . }} {{ partial "<API key>.html" . }} </aside> <main class="col-12 col-md-9 col-xl-8 pl-md-5" role="main"> {{ partial "version-banner.html" . }} {{ if not .Site.Params.ui.breadcrumb_disable }}{{ partial "breadcrumb.html" . }}{{ end }} {{ block "main" . }}{{ end }} </main> </div> </div> {{ partial "footer.html" . }} </div> {{ partial "scripts.html" . }} </body> </html>
// This file is part of the go-ethereum library. // The go-ethereum library is free software: you can redistribute it and/or modify // (at your option) any later version. // The go-ethereum library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the package types import ( "bytes" "fmt" "io" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/rlp" ) type Receipt struct { PostState []byte CumulativeGasUsed *big.Int Bloom Bloom TxHash common.Hash ContractAddress common.Address logs state.Logs GasUsed *big.Int } func NewReceipt(root []byte, cumulativeGasUsed *big.Int) *Receipt { return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumulativeGasUsed)} } func (self *Receipt) SetLogs(logs state.Logs) { self.logs = logs } func (self *Receipt) Logs() state.Logs { return self.logs } func (self *Receipt) EncodeRLP(w io.Writer) error { return rlp.Encode(w, []interface{}{self.PostState, self.CumulativeGasUsed, self.Bloom, self.logs}) } func (self *Receipt) DecodeRLP(s *rlp.Stream) error { var r struct { PostState []byte CumulativeGasUsed *big.Int Bloom Bloom TxHash common.Hash ContractAddress common.Address Logs state.Logs GasUsed *big.Int } if err := s.Decode(&r); err != nil { return err } self.PostState, self.CumulativeGasUsed, self.Bloom, self.TxHash, self.ContractAddress, self.logs, self.GasUsed = r.PostState, r.CumulativeGasUsed, r.Bloom, r.TxHash, r.ContractAddress, r.Logs, r.GasUsed return nil } type ReceiptForStorage Receipt func (self *ReceiptForStorage) EncodeRLP(w io.Writer) error { storageLogs := make([]*state.LogForStorage, len(self.logs)) for i, log := range self.logs { storageLogs[i] = (*state.LogForStorage)(log) } return rlp.Encode(w, []interface{}{self.PostState, self.CumulativeGasUsed, self.Bloom, self.TxHash, self.ContractAddress, storageLogs, self.GasUsed}) } func (self *Receipt) RlpEncode() []byte { bytes, err := rlp.EncodeToBytes(self) if err != nil { fmt.Println("TMP -- RECEIPT ENCODE ERROR", err) } return bytes } func (self *Receipt) Cmp(other *Receipt) bool { if bytes.Compare(self.PostState, other.PostState) != 0 { return false } return true } func (self *Receipt) String() string { return fmt.Sprintf("receipt{med=%x cgas=%v bloom=%x logs=%v}", self.PostState, self.CumulativeGasUsed, self.Bloom, self.logs) } type Receipts []*Receipt func (self Receipts) RlpEncode() []byte { bytes, err := rlp.EncodeToBytes(self) if err != nil { fmt.Println("TMP -- RECEIPTS ENCODE ERROR", err) } return bytes } func (self Receipts) Len() int { return len(self) } func (self Receipts) GetRlp(i int) []byte { return common.Rlp(self[i]) }
/** * \file SDL_clipboard.h * * Include file for SDL clipboard handling */ #ifndef _SDL_clipboard_h #define _SDL_clipboard_h #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Function prototypes */ /** * \brief Put UTF-8 text into the clipboard * * \sa <API key>() */ extern DECLSPEC int SDLCALL <API key>(const char *text); /** * \brief Get UTF-8 text from the clipboard, which must be freed with SDL_free() * * \sa <API key>() */ extern DECLSPEC char * SDLCALL <API key>(void); /** * \brief Returns a flag indicating whether the clipboard exists and contains a text string that is non-empty * * \sa <API key>() */ extern DECLSPEC SDL_bool SDLCALL <API key>(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* _SDL_clipboard_h */ /* vi: set ts=4 sw=4 expandtab: */
package draw.basic; import java.awt.*; import java.awt.image.*; import java.io.*; import java.util.Arrays; import java.util.List; import javax.imageio.*; import javax.swing.*; public class ScreenImage { private static List<String> imageTypes = Arrays.asList( ImageIO.<API key>()); /** * Create a BufferedImage for Swing components. The entire component will be * captured to an image. * * @param component Swing component to create the image from. * @return image The image for the given region. */ public static BufferedImage createImage(JComponent component) { Dimension dim = component.getSize(); if (dim.width == 0 || dim.height == 0) { dim = component.getPreferredSize(); component.setSize(dim); } Rectangle region = new Rectangle(0, 0, dim.width, dim.height); return ScreenImage.createImage(component, region); } /** * Create a BufferedImage for Swing components. All or part of the component * can be captured to an image. * * @param component Swing component to create the image from. * @param region The region of the component to be captured to an image. * @return image The image for the given region. */ public static BufferedImage createImage(JComponent component, Rectangle region) { if (!component.isDisplayable()) { Dimension dim = component.getSize(); if (dim.width == 0 || dim.height == 0) { dim = component.getPreferredSize(); component.setSize(dim); } layoutComponent(component); } BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); // Paint a background for non-opaque components. if (!component.isOpaque()) { g2d.setColor(component.getBackground()); g2d.fillRect(region.x, region.y, region.width, region.height); } g2d.translate(-region.x, -region.y); component.paint(g2d); g2d.dispose(); return image; } /** * Convenience method to create a BufferedImage of the desktop. * * @param fileName Name of file to be created or null. * @return image The image for the given region. * @exception AWTException * @exception IOException */ public static BufferedImage createDesktopImage() throws AWTException, IOException { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle region = new Rectangle(0, 0, dim.width, dim.height); return ScreenImage.createImage(region); } /** * Create a BufferedImage for AWT components. * * @param component AWT component to create image from * @return image the image for the given region * @exception AWTException see Robot class constructors */ public static BufferedImage createImage(Component component) throws AWTException { Point p = new Point(0, 0); SwingUtilities.<API key>(p, component); Rectangle region = component.getBounds(); region.x = p.x; region.y = p.y; return ScreenImage.createImage(region); } /** * Create a BufferedImage from a rectangular region on the screen. This will * include Swing components JFrame, JDialog and JWindow which all extend * from Component, not JComponent. * * @param Region region on the screen to create image from * @return Image the image for the given region * @exception AWTException see Robot class constructors */ public static BufferedImage createImage(Rectangle region) throws AWTException { BufferedImage image = new Robot().createScreenCapture(region); return image; } /** * Write a BufferedImage to a File. * * @param Image image to be written. * @param FileName name of file to be created. * @exception IOException if an error occurs during writing. */ public static void writeImage(BufferedImage image, String fileName) throws IOException { if (fileName == null) { return; } int offset = fileName.lastIndexOf("."); if (offset == -1) { String message = "file type was not specified"; throw new IOException(message); } String fileType = fileName.substring(offset + 1); if (imageTypes.contains(fileType)) { ImageIO.write(image, fileType, new File(fileName)); } else { String message = "unknown writer file type (" + fileType + ")"; throw new IOException(message); } } /** * A recursive layout call on the component. * * @param component Component object. */ static void layoutComponent(Component component) { synchronized (component.getTreeLock()) { component.doLayout(); if (component instanceof Container) { for (Component child : ((Container) component).getComponents()) { layoutComponent(child); } } } } }
title: " Scrapy " layout: post date: 2018-02-24 22:48 tag: - blog: true author: Topaz summary: "BeautifulSoup Xpath" permalink: Spiders-Scrapy-01 <h1 class="title"> Scrapy </h1> <h2> Table of Contents </h2> - [Scrapy ]( - []( - []( - []( - []( - [HtmlXpathSelector]( - [ Scrapy ]( - [Scrapy ]( <a style="color: <h2 id="c1"> Scrapy </h2> ScrapyTwisted, <h2 id="c2"> </h2> {% highlight raw %} - (Scrapy), () - (Scheduler), , . URL, , - (Downloader), (Scrapytwisted) - (Spiders), , (Item) ,Scrapy - (Pipeline) - (Downloader Middlewares) ScrapyScrapy - (Spider Middlewares)Scrapy - (Scheduler Middewares)ScrapyScrapy {% endhighlight %} <h2 id="c3"> </h2> {% highlight raw %} 1. (URL) 2. URL(Request) 3. (Response) 4. Response 5. Item, 6. URL,URL {% endhighlight %} <h2 id="c4"> </h2> # Linux & Mac {% highlight python %} pip3 install scrapy {% endhighlight %} # Windows {% highlight python %} pip3 install wheel - twisted http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted - pip3 install Twisted-17.5.<API key>.whl - scrapy pip3 install scrapy - pywin32 https://sourceforge.net/projects/pywin32/files/ {% endhighlight %} <h2 id="c5"> </h2> {% highlight python %} scrapy startproject [] scrapy genspider [-t template] <name> <domain> scrapy list scrapy crawl [] scrapy genspider -l scrapy genspider -d [] {% endhighlight %} <h2 id="c6"> HtmlXpathSelector </h2> HtmlXpathSelector Scrapy HTMLXPath“”“”XPathHTML - BeautifulSoup - lxml ElementTree XMLHTML {% highlight python %} from scrapy.selector import Selector, HtmlXPathSelector from scrapy.http import HtmlResponse html = """ <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <ul> <li class="item-"><a id='i12' href="link.html">first item</a></li> <li class="item-0"><a id='i2' href="llink.html">first item</a></li> <li class="item-1"><a href="llink2.html">second item<span>vv</span></a></li> </ul> <div><a href="llink2.html">second item</a></div> </body> </html> """ response = HtmlResponse(url='http://example.com', body=html,encoding='utf-8') hxs = Selector(response) hxs = Selector(response=response).xpath(' #ida hxs = Selector(response=response).xpath('//a[@id]') #linkhref hxs = Selector(response=response).xpath('//a[starts-with(@href,"link")]' ) #linkhref hxs = Selector(response=response).xpath('//a[contains(@href, "link")]') hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]') hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/text()').extract() hxs = Selector(response=response).xpath('//a[re:test(@id, "i\d+")]/@href').extract() hxs = Selector(response=response).xpath('/html/body/ul/li/a/@href').extract() hxs = Selector(response=response).xpath('//body/ul/li/a/@href').extract_first() {% endhighlight %} <h2 id="c7"> Scrapy </h2> {% highlight raw %} cutetopaz/ scrapy.cfg #settings.py cutetopaz/ __init__.py items.py # DjangoModel pipelines.py settings.py spiders/ __init__.py xiaohuar.py {% endhighlight %} # xiaohuar.py {% highlight python %} import scrapy import hashlib scrapy.selector import Selector scrapy.http.request import Request scrapy.http.cookies import CookieJar scrapy import FormRequest ..items import XiaoHuarItem class XiaoHuarSpider(scrapy.Spider): name = "hira" allowed_domains = ["xiaohuar.com"] start_urls = ["http: has_request_set = {} def parse(self, response): hxs = Selector(response) items = hxs.select('//div[@class="item_list infinite_scroll"]/div') for item in items: src = item.xpath('.//div[@class="img"]/a/img/@src').extract_first() name = item.xpath('.//div[@class="img"]/span/text()').extract_first() school = item.xpath('.//div[@class="img"]/div[@class="btns"]/a/text()').extract_first() url = "http: obj = XiaoHuarItem(name=name,school=school, url=url) yield obj urls = hxs.xpath('//a[re:test(@href, "http://www.xiaohuar.com/ list-1-\d+.html")]/@href').extract() for url in urls: print("here is url:",url) key = self.md5(url) print('key!!!!!',key) if key in self.has_request_set: # print('',self.has_request_set) pass else: self.has_request_set[key] = url req = Request(url=url,method='GET',callback=self.parse) yield req @staticmethod def md5(val): ha = hashlib.md5() ha.update(bytes(val, encoding='utf-8')) key = ha.hexdigest() return key {% endhighlight %} # items.py {% highlight python %} import scrapy class CutetopazItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass class XiaoHuarItem(scrapy.Item): name = scrapy.Field() school = scrapy.Field() url = scrapy.Field() {% endhighlight %} # pipelines.py {% highlight python %} import json import os import requests class JsonPipeline(object): '''settings.py''' def __init__(self): self.file = open('xiaohua.txt', 'w') def process_item(self, item, spider): v = json.dumps(dict(item), ensure_ascii=False) #item ==> <class 'cutetopaz.items.XiaoHuarItem'> dict(item) ==> <class 'dict'> itemdict()is not JSON serializable self.file.write(v) self.file.write('\n') self.file.flush() return item #jsonitem class FilePipeline(object): def __init__(self): if not os.path.exists('imgs'): os.makedirs('imgs') def process_item(self, item, spider): response = requests.get(item['url'], stream=True) print('',response.__attrs__) file_name = '%s_%s.jpg' % (item['name'], item['school']) with open(os.path.join('imgs', file_name), mode='wb') as f: f.write(response.content) return item {% endhighlight %} # settings.py {% highlight python %} ITEM_PIPELINES = { 'cutetopaz.pipelines.JsonPipeline': 100, 'cutetopaz.pipelines.FilePipeline': 300, } {% endhighlight %} <h2 id="c8"> Scrapy </h2> {% highlight raw %} 1.spiderscommands 2. crawlall.py 3.settings.py COMMANDS_MODULE = '.' 4.scrapy crawlall {% endhighlight %} {% highlight python %} from scrapy.commands import ScrapyCommand from scrapy.utils.project import <API key> class Command(ScrapyCommand): requires_project = True def syntax(self): return '[options]' def short_desc(self): return 'Runs all of the spiders' def run(self, args, opts): spider_list = self.crawler_process.spiders.list() for name in spider_list: self.crawler_process.crawl(name, **opts.__dict__) self.crawler_process.start() {% endhighlight %} {% highlight python %} from scrapy import signals class MyExtension(object): def __init__(self, value): self.value = value @classmethod def from_crawler(cls, crawler): val = crawler.settings.getint('MMMM') ext = cls(val) crawler.signals.connect(ext.spider_opened, signal=signals.spider_opened) crawler.signals.connect(ext.spider_closed, signal=signals.spider_closed) return ext def spider_opened(self, spider): print('open') def spider_closed(self, spider): print('close') {% endhighlight %} Scrapy scrapy.dupefilter.RFPDupeFilter {% highlight raw %} DUPEFILTER_CLASS = 'scrapy.dupefilter.RFPDupeFilter' DUPEFILTER_DEBUG = False JOBDIR = "/root/" # /root/requests.seen {% endhighlight %}
@extends('admin.layout') @section('styles') <link href="/assets/css/pdfexport.css" rel="stylesheet"> @stop @section('content') <div class="container"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <p><a href="{{ url('admin/stavkeposla/show',[$evidencija->id]) }}" class="btn btn-warning pull-right"><i class="fa <API key>"></i> Natrag</a></p> <h4>Pregled stavke ponude</h4> </div> <div class="panel-body"> <div class="col-md-4 col-md-offset-5"> <button class="btn btn-primary" id="create_pdf"><i class="fa fa-file-pdf-o" aria-hidden="true"></i> Pretvori u PDF</button> </div> </div> </div> </div> </div> <page size="A4"> <div id="target"> <div class="row"> <div class="col-xs-12"> <div class="row top-head"> <div class="col-xs-3 head-left"> <img src="/assets/images/lukic-logo.png" alt="Waterrproofing co"> <h2>Mob. 098 111 222</h2> </div> <div class="col-xs-6 head-center"> <address> <h1>WATERPROOFING CO</h1> <h2>Zagreb <span>Ilica BB</span></h2> <h2>OIB:72818256208</h2> <h2><span>Žiro račun:</span> IBAN <API key></h2> </address> </div> <div class="col-xs-3 head-right"> <img src="/assets/images/lukic-logo.png" alt="Waterrproofing co"> <h2>Tel fax 01 111 22 33</h2> </div> </div><!--top-head <hr> <div class="row top-adddress"> <div class="col-xs-6 head-adddress-left"> <p>Mjesto rada: {{ $evidencija->narucitelj_adresa }} </p> </div> <div class="col-xs-6 head-adddress-right"> <address class="pull-right"> <p><strong>{{ $evidencija->mjesto_rada }}</strong></p> <p><strong>{{ $evidencija->narucitelj_adresa }}</strong></p> <p><strong>OIB: {{ $evidencija->narucitelj_oib }}</strong></p> </address> </div> </div><!--top-adddress <div class="row invoice"> <div class="col-xs-12"> <h3>STAVKA PONUDE BR: 0{{ $evidencija->id }}.{{ $evidencija->created_at->format('my') }}-1</h3> </div> </div><!--invoice <div class="row stavke"> <div class="col-xs-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><strong>Stavka br: {{ $stavka->broj_stavke }}</strong></h3> <p><strong>Opis radova:</strong> {{ $stavka->opis_radova }}</p> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-condensed stavkamaterijal"> <thead> <tr> <th>Naziv materijala</th> <th>Mjerna jedinica</th> <th>Cijena materijala</th> <th>Potrošnja</th> <th>Materijal</th> <th>Kalkul sat</th> <th>Norma sat</th> <th>Rad</th> <th>Cijena po jm.</th> <th>Ucinak m2 sat</th> </tr> </thead> <tbody> @foreach($stavkeposlovi as $pm) <!-- foreach ($order->lineItems as $line) or some such thing here --> <tr> <td>{{ $pm->naziv_materijala }}</td> <td>{{ $pm->mjerna_jedinica }}</td> <td>{{ $pm->cijena_sa_popustom }}</td> <td>{{ $pm->potrosnja_mat }}</td> <td>{{ $pm->materijal }}</td> <td>{{ $pm->kalkul_sat }}</td> <td>{{ $pm->norma_sat }}</td> <td>{{ $pm->rad }}</td> <td>{{ $pm->cijena_po_jm }}</td> <td>{{ $pm->ucinak_m2_sat }}</td> </tr> @endforeach <tr> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line text-left"><strong>Cijena posla:</strong></td> <td class="no-line text-right">{{ $stavka->cijena_posla }} - kn</td> </tr> <tr> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line"></td> <td class="no-line text-left"><strong>Ukupna cijena:</strong></td> <td class="no-line text-right">{{ $stavka->ukupna_cijena }} - kn</td> </tr> </tbody> </table> </div> </div> </div> <div class="row"> <div class="col-xs-12"> <div class="col-xs-7"> <p>Obračun prema stvarnim količinama.</p> <p>{{ date('d.m.Y') }}</p> </div> <div class="col-xs-4"> <div class="pull-right"> <p class="line"><strong>Direktor</strong></p> <p class="no-line"><strong>Ivica Ivić</strong></p> </div> </div> <div class="col-xs-1"></div> </div> </div> </div> </div><!--/.stavke--> <div class="row end"> </div><!--end </div><!--col-xs-12 </div><!--row </div> </page> @stop @section('scripts') <script src="/assets/js/jspdf.min.js"></script> <script src="http://mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script> <script type="text/javascript" src="//cdn.rawgit.com/niklasvh/html2canvas/0.5.0-alpha2/dist/html2canvas.min.js"></script> <script type="text/javascript"> (function(){ var target = $('#target'), cache_width = target.width(), a4 =[ 595.28, 841.89]; // for a4 size paper width and height $('#create_pdf').on('click',function(){ $('#target').scrollTop(0); createPDF(); }); //create pdf function createPDF(){ getCanvas().then(function(canvas){ var img = canvas.toDataURL("image/png"), doc = new jsPDF({ unit:'px', format:'a4' }); doc.addImage(img, 'JPEG', 20, 20); doc.save('ponuda.pdf'); target.width(cache_width); }); } // create canvas object function getCanvas(){ target.width((a4[0]*1.33333) -60).css('max-width','none'); return html2canvas(target,{ imageTimeout:2000, removeContainer:true }); } }()); </script> @stop
/** * Interface for compliation manager */ #ifndef _MANAGER_H_ #define _MANAGER_H_ #include "ast/ast.h" #include "ir/ir.h" #include "lex/lex.h" #include "lex/symtab.h" #include "util/status.h" /** * Compilation manager structure. Manages data structures necessary for compiles */ typedef struct manager_t { vec_t tokens; symtab_t symtab; lexer_t lexer; token_man_t token_man; fmark_man_t mark_man; trans_unit_t *ast; ir_trans_unit_t *ir; bool parse_destroyed; } manager_t; /** * Initialize a compilation mananger * * @param manager The compilation mananger to initialize */ void man_init(manager_t *manager); /** * Destroy a compilation mananger * * @param manager The compilation mananger to destroy */ void man_destroy(manager_t *manager); /** * Destroy a compilation mananger parsing data structures * * Calling this is optional because destructor destroys these. May be used to * reduce memory usage however. * * @param manager The compilation mananger to destroy ast */ void man_destroy_parse(manager_t *manager); /** * Destroy a compilation mananger's ir * * Calling this is optional because destructor destroys ir. May be used to * reduce memory usage however. * * @param manager The compilation mananger to destroy ir */ void man_destroy_ir(manager_t *manager); status_t man_lex(manager_t *manager, char *filepath); /** * Parse a translation unit from a compilation manager. * * The manager's preprocessor must be set up first * * @param manager The compilation mananger to parse * @param filepath Path to file to parse * @param ast The parsed ast * @return CCC_OK on success, error code on error. */ status_t man_parse(manager_t *manager, trans_unit_t **ast); /** * Parse an expression from a compilation manager. * * The manager's preprocessor must be set up first * * @param manager The compilation mananger to parse * @param expr The parsed expression * @return CCC_OK on success, error code on error. */ status_t man_parse_expr(manager_t *manager, expr_t **expr); /** * Translate the ast in a manager * * The manager must have a vaild ast from man_parse * * @param manager The compilation mananger to use * @return Returns the ir tree */ ir_trans_unit_t *man_translate(manager_t *manager); /** * Print the tokens from a compilation manager * * The manager's preprocessor must be set up first * * @param manager The compilation mananger to use * @return CCC_OK on success, error code on error. */ status_t man_dump_tokens(manager_t *manager); #endif /* _MANAGER_H_ */
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model common\models\Sparesused */ $this->title = 'Create Sparesused'; $this->params['breadcrumbs'][] = ['label' => 'Sparesuseds', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="sparesused-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
{% extends "base_nav.html" %} {% load humanize %} {% load i18n %} {% load staticfiles %} {% block "title" %}{% trans "Review Access Request" %}{% endblock %} {% block "css" %} <link href="{% static 'css/secrets.css' %}" rel="stylesheet"> {% endblock %} {% block "content" %} <script type="text/javascript"> $(function () { $("[data-toggle='tooltip']").tooltip({container: 'body'}); }); </script> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1>{% trans "Review Access Request" %}</h1> <br> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="secret-attributes panel"> <br> <table class="table-responsive"> <tr> <td>{% trans "Requester" %}</td> <td> {{ access_request.requester }} </td> </tr> <tr> <td>{% trans "Secret" %}</td> <td> <a href="{{ access_request.secret.get_absolute_url }}">{{ access_request.secret.name }}</a> </td> </tr> <tr> <td>{% trans "Requested" %}</td> <td> <span data-toggle="tooltip" data-placement="top" title="{{ access_request.created|date:"Y-m-d H:i:s" }}"> {{ access_request.created|naturalday:"Y-m-d" }} </span> </td> </tr> {% if access_request.reason_request %} <tr> <td>{% trans "Reason" %}</td> <td> {{ access_request.reason_request }} </td> </tr> {% endif %} </table> <br> </div> </div> </div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form role="form" method="POST" action="{% url "secrets.<API key>" hashid=access_request.hashid action="deny" %}"> {% csrf_token %} <input type="text" class="form-control input-lg" name="reason" placeholder="{% trans "Reason for turning down the request (optional)" %}"> <br> <button type="submit" class="btn btn-danger btn-lg pull-left"> &nbsp; &nbsp; &nbsp; <i class="fa fa-thumbs-down"></i>&nbsp; {% trans "Deny access" %} &nbsp; &nbsp; &nbsp; </button> </form> <form role="form" method="POST" action="{% url "secrets.<API key>" hashid=access_request.hashid action="allow" %}"> {% csrf_token %} <button type="submit" class="btn btn-success btn-lg pull-right"> &nbsp; &nbsp; &nbsp; <i class="fa fa-thumbs-up"></i>&nbsp; {% trans "Allow access" %} &nbsp; &nbsp; &nbsp; </button> </form> </div> </div> </div> {% endblock %}
#include "../../common.h" #include "../../interface/Viewport.h" #include "../../paint/Paint.h" #include "../../paint/Supports.h" #include "../../world/Entity.h" #include "../Track.h" #include "../TrackPaint.h" #include "../Vehicle.h" /** rct2: 0x0076E5C9 */ static void <API key>( paint_session* session, const Ride* ride, uint8_t direction, int8_t xOffset, int8_t yOffset, uint16_t height) { const TileElement* savedTileElement = static_cast<const TileElement*>(session->CurrentlyDrawnItem); rct_ride_entry* rideEntry = get_ride_entry(ride->subtype); Vehicle* vehicle = nullptr; if (rideEntry == nullptr) { return; } height += 7; uint32_t baseImageId = rideEntry->vehicles[0].base_image_id; if (ride->lifecycle_flags & <API key> && ride->vehicles[0] != SPRITE_INDEX_NULL) { vehicle = GetEntity<Vehicle>(ride->vehicles[0]); session->InteractionType = <API key>::Entity; session->CurrentlyDrawnItem = vehicle; } uint32_t frameNum = (direction * 88) % 216; if (vehicle != nullptr) { frameNum += (vehicle->sprite_direction >> 3) << 4; frameNum += vehicle->Pitch; frameNum = frameNum % 216; } uint32_t imageColourFlags = session->TrackColours[SCHEME_MISC]; if (imageColourFlags == IMAGE_TYPE_REMAP) { imageColourFlags = <API key>(ride->vehicle_colours[0].Body, ride->vehicle_colours[0].Trim); } uint32_t structureFrameNum = frameNum % 24; uint32_t imageId = (baseImageId + structureFrameNum) | imageColourFlags; <API key>( session, imageId, { xOffset, yOffset, height }, { 24, 24, 48 }, { xOffset + 16, yOffset + 16, height }); rct_drawpixelinfo* dpi = &session->DPI; if (dpi->zoom_level < 1 && ride->lifecycle_flags & <API key> && vehicle != nullptr) { for (int32_t i = 0; i < vehicle->num_peeps; i += 2) { imageColourFlags = <API key>(vehicle->peep_tshirt_colours[i], vehicle->peep_tshirt_colours[i + 1]); uint32_t peepFrameNum = (frameNum + i * 12) % 216; imageId = (baseImageId + 24 + peepFrameNum) | imageColourFlags; <API key>(session, imageId, xOffset, yOffset, 24, 24, 48, height, xOffset + 16, yOffset + 16, height); } } session->CurrentlyDrawnItem = savedTileElement; session->InteractionType = <API key>::Ride; } /** rct2: 0x0076D858 */ static void paint_twist( paint_session* session, const Ride* ride, uint8_t trackSequence, uint8_t direction, int32_t height, const TrackElement& trackElement) { if (ride == nullptr) return; trackSequence = track_map_3x3[direction][trackSequence]; const uint8_t edges = edges_3x3[trackSequence]; uint32_t imageId; <API key>(session, (direction & 1), 0, height, session->TrackColours[SCHEME_MISC]); StationObject* stationObject = <API key>(ride); <API key>(session, edges, session->TrackColours[SCHEME_MISC], height, floorSpritesCork, stationObject); switch (trackSequence) { case 7: if (<API key>(EDGE_SW, session->MapPosition, trackElement, ride, session->CurrentRotation)) { imageId = SPR_FENCE_ROPE_SW | session->TrackColours[SCHEME_MISC]; <API key>(session, imageId, { 0, 0, height }, { 1, 28, 7 }, { 29, 0, height + 3 }); } if (<API key>(EDGE_SE, session->MapPosition, trackElement, ride, session->CurrentRotation)) { imageId = SPR_FENCE_ROPE_SE | session->TrackColours[SCHEME_MISC]; <API key>(session, imageId, { 0, 0, height }, { 28, 1, 7 }, { 0, 29, height + 3 }); } break; default: <API key>( session, edges, session->MapPosition, trackElement, ride, session->TrackColours[SCHEME_MISC], height, fenceSpritesRope, session->CurrentRotation); break; } switch (trackSequence) { case 1: <API key>(session, ride, direction, 32, 32, height); break; case 3: <API key>(session, ride, direction, 32, -32, height); break; case 5: <API key>(session, ride, direction, 0, -32, height); break; case 6: <API key>(session, ride, direction, -32, 32, height); break; case 7: <API key>(session, ride, direction, -32, -32, height); break; case 8: <API key>(session, ride, direction, -32, 0, height); break; } int32_t cornerSegments = 0; switch (trackSequence) { case 1: cornerSegments = SEGMENT_B4 | SEGMENT_C8 | SEGMENT_CC; break; case 3: cornerSegments = SEGMENT_CC | SEGMENT_BC | SEGMENT_D4; break; case 6: cornerSegments = SEGMENT_C8 | SEGMENT_B8 | SEGMENT_D0; break; case 7: cornerSegments = SEGMENT_D0 | SEGMENT_C0 | SEGMENT_D4; break; } <API key>(session, cornerSegments, height + 2, 0x20); <API key>(session, SEGMENTS_ALL & ~cornerSegments, 0xFFFF, 0); <API key>(session, height + 64, 0x20); } /** * rct2: 0x0076D658 */ <API key> <API key>(int32_t trackType) { if (trackType != TrackElemType::FlatTrack3x3) { return nullptr; } return paint_twist; }
<!DOCTYPE html PUBLIC "- <html> <head> <title>Singular 2-0-4 Manual: D.5.8.6 is_reg</title> <meta name="description" content="Singular 2-0-4 Manual: D.5.8.6 is_reg"> <meta name="keywords" content="Singular 2-0-4 Manual: D.5.8.6 is_reg"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="texi2html"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <! @import "sing_tex4ht_tex.css"; a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} pre.display {font-family: serif} pre.format {font-family: serif} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: serif; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: serif; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:pre} span.nolinebreak {white-space:pre} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} </style> </head> <body lang="en" background="../singular_images/Mybg.png"> <a name="is_005freg"></a> <table border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td align="left"> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr valign="top" align="left"> <td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="is_005fis.html#is_005fis" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.8.5 is_is" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="is_005fregs.html#is_005fregs" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.8.7 is_regs" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_005flib.html#sing_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.8 sing_lib" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> </tr> <tr valign="top" align="left"> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr> </table> </td> <td align="left"> <a name="is_005freg-1"></a> <h4 class="subsubsection">D.5.8.6 is_reg</h4> <a name="index-is_005freg"></a> <p>Procedure from library <code>sing.lib</code> (see <a href="sing_005flib.html#sing_005flib">sing_lib</a>). </p> <dl compact="compact"> <dt><strong>Usage:</strong></dt> <dd><p>is_reg(f,id); f poly, id ideal or module </p> </dd> <dt><strong>Return:</strong></dt> <dd><p>1 if multiplication with f is injective modulo id, 0 otherwise </p> </dd> <dt><strong>Note:</strong></dt> <dd><p>let R be the basering and id a submodule of R^n. The procedure checks injectivity of multiplication with f on R^n/id. The basering may be a quotient ring </p> </dd> </dl> <p><strong>Example:</strong> </p><div class="smallexample"> <pre class="smallexample">LIB &quot;sing.lib&quot;; ring r = 32003,(x,y),ds; ideal i = x8,y8; ideal j = (x+y)^4; i = intersect(i,j); poly f = xy; is_reg(f,i); &rarr; 0 </pre></div> </td> </tr> </table> <hr> <table class="header" cellpadding="1" cellspacing="1" border="0"> <tr><td valign="middle" align="left"> <a href="index.htm"><img src="../singular_images/<API key>.png" width="50" border="0" alt="Top"></a> </td> <td valign="middle" align="left"><a href="is_005fis.html#is_005fis" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.8.5 is_is" align="middle"></a></td> <td valign="middle" align="left"><a href="is_005fregs.html#is_005fregs" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.8.7 is_regs" align="middle"></a></td> <td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td> <td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_005flib.html#sing_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.8 sing_lib" align="middle"></a></td> <td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td> <td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td> <td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td> </tr></table> <font size="-1"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; User manual for <a href="http: generated by <a href="http: </font> </body> </html>
use vars qw(%result_texis %result_texts %result_trees %result_errors %result_indices %result_sectioning %result_nodes %result_menus %result_floats %result_converted %<API key> %result_elements %<API key>); use utf8; $result_trees{'<API key>'} = { 'contents' => [ { 'contents' => [], 'parent' => {}, 'type' => 'text_root' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => '<API key>' }, { 'parent' => {}, 'text' => 'ToP' }, { 'parent' => {}, 'text' => ' ', 'type' => 'spaces_at_end' } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'node', 'contents' => [ { 'parent' => {}, 'text' => ' ', 'type' => 'empty_line' }, { 'contents' => [ { 'args' => [ { 'contents' => [ { 'parent' => {}, 'text' => 'TOP' } ], 'parent' => {}, 'type' => 'brace_command_arg' } ], 'cmdname' => 'xref', 'contents' => [], 'extra' => { '<API key>' => [ [ {} ] ], 'label' => {}, 'node_argument' => { 'node_content' => [ {} ], 'normalized' => 'Top' } }, 'line_nr' => { 'file_name' => '', 'line_nr' => 3, 'macro' => '' }, 'parent' => {} }, { 'parent' => {}, 'text' => '. ' }, { 'args' => [ { 'contents' => [ { 'parent' => {}, 'text' => 'tOP' } ], 'parent' => {}, 'type' => 'brace_command_arg' } ], 'cmdname' => 'xref', 'contents' => [], 'extra' => { '<API key>' => [ [ {} ] ], 'label' => {}, 'node_argument' => { 'node_content' => [ {} ], 'normalized' => 'Top' } }, 'line_nr' => {}, 'parent' => {} }, { 'parent' => {}, 'text' => '. ' } ], 'parent' => {}, 'type' => 'paragraph' }, { 'parent' => {}, 'text' => ' ', 'type' => 'empty_line' }, { 'cmdname' => 'menu', 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => '<API key>' }, { 'args' => [ { 'parent' => {}, 'text' => '* ', 'type' => '<API key>' }, { 'contents' => [ { 'parent' => {}, 'text' => 'tOP' } ], 'parent' => {}, 'type' => 'menu_entry_node' }, { 'parent' => {}, 'text' => '::', 'type' => '<API key>' }, { 'contents' => [ { 'contents' => [ { 'parent' => {}, 'text' => ' ' } ], 'parent' => {}, 'type' => 'preformatted' } ], 'parent' => {}, 'type' => '<API key>' } ], 'extra' => { '<API key>' => {}, 'menu_entry_node' => { 'node_content' => [ {} ], 'normalized' => 'Top' } }, 'line_nr' => { 'file_name' => '', 'line_nr' => 6, 'macro' => '' }, 'parent' => {}, 'type' => 'menu_entry' }, { 'args' => [ { 'contents' => [ { 'extra' => { 'command' => {} }, 'parent' => {}, 'text' => ' ', 'type' => '<API key>' }, { 'parent' => {}, 'text' => 'menu' }, { 'parent' => {}, 'text' => ' ', 'type' => 'spaces_at_end' } ], 'parent' => {}, 'type' => 'misc_line_arg' } ], 'cmdname' => 'end', 'extra' => { 'command' => {}, 'command_argument' => 'menu', 'text_arg' => 'menu' }, 'line_nr' => { 'file_name' => '', 'line_nr' => 7, 'macro' => '' }, 'parent' => {} } ], 'extra' => { 'end_command' => {} }, 'line_nr' => { 'file_name' => '', 'line_nr' => 5, 'macro' => '' }, 'parent' => {} } ], 'extra' => { 'node_content' => [ {} ], 'nodes_manuals' => [ { 'node_content' => [], 'normalized' => 'Top' } ], 'normalized' => 'Top' }, 'line_nr' => { 'file_name' => '', 'line_nr' => 1, 'macro' => '' }, 'parent' => {} } ], 'type' => 'document_root' }; $result_trees{'<API key>'}{'contents'}[0]{'parent'} = $result_trees{'<API key>'}; $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]{'contents'}[2]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'extra'}{'<API key>'}[0][0] = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'extra'}{'label'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'extra'}{'node_argument'}{'node_content'}[0] = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'args'}[0]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[1]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'extra'}{'<API key>'}[0][0] = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'extra'}{'label'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'extra'}{'node_argument'}{'node_content'}[0] = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'args'}[0]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'line_nr'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[0]{'line_nr'}; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[2]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'contents'}[3]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[1]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[2]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[0]{'extra'}{'command'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[2]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'contents'}[0]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'extra'}{'<API key>'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'extra'}{'menu_entry_node'}{'node_content'}[0] = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'args'}[1]{'contents'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[1]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[0]{'extra'}{'command'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[1]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'contents'}[2]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'args'}[0]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'extra'}{'command'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'extra'}{'end_command'} = $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'contents'}[2]; $result_trees{'<API key>'}{'contents'}[1]{'contents'}[3]{'parent'} = $result_trees{'<API key>'}{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'extra'}{'node_content'}[0] = $result_trees{'<API key>'}{'contents'}[1]{'args'}[0]{'contents'}[1]; $result_trees{'<API key>'}{'contents'}[1]{'extra'}{'nodes_manuals'}[0]{'node_content'} = $result_trees{'<API key>'}{'contents'}[1]{'extra'}{'node_content'}; $result_trees{'<API key>'}{'contents'}[1]{'parent'} = $result_trees{'<API key>'}; $result_texis{'<API key>'} = '@node ToP @xref{TOP}. @xref{tOP}. @menu * tOP:: @end menu '; $result_texts{'<API key>'} = ' . . * tOP:: '; $result_sectioning{'<API key>'} = {}; $result_nodes{'<API key>'} = { 'cmdname' => 'node', 'extra' => { 'normalized' => 'Top' }, 'menu_child' => {}, 'menus' => [ { 'cmdname' => 'menu', 'extra' => { 'end_command' => { 'cmdname' => 'end', 'extra' => { 'command' => {}, 'command_argument' => 'menu', 'text_arg' => 'menu' } } } } ], 'node_next' => {}, 'node_prev' => {}, 'node_up' => { 'extra' => { 'manual_content' => [ { 'text' => 'dir' } ], 'top_node_up' => {} }, 'type' => 'top_node_up' } }; $result_nodes{'<API key>'}{'menu_child'} = $result_nodes{'<API key>'}; $result_nodes{'<API key>'}{'menus'}[0]{'extra'}{'end_command'}{'extra'}{'command'} = $result_nodes{'<API key>'}{'menus'}[0]; $result_nodes{'<API key>'}{'node_next'} = $result_nodes{'<API key>'}; $result_nodes{'<API key>'}{'node_prev'} = $result_nodes{'<API key>'}; $result_nodes{'<API key>'}{'node_up'}{'extra'}{'top_node_up'} = $result_nodes{'<API key>'}; $result_menus{'<API key>'} = { 'cmdname' => 'node', 'extra' => { 'normalized' => 'Top' }, 'menu_child' => {}, 'menu_up' => {}, 'menu_up_hash' => { 'Top' => 1 } }; $result_menus{'<API key>'}{'menu_child'} = $result_menus{'<API key>'}; $result_menus{'<API key>'}{'menu_up'} = $result_menus{'<API key>'}; $result_errors{'<API key>'} = [ { 'error_line' => ':1: warning: For `ToP\', up in menu `ToP\' and up `(dir)\' don\'t match ', 'file_name' => '', 'line_nr' => 1, 'macro' => '', 'text' => 'For `ToP\', up in menu `ToP\' and up `(dir)\' don\'t match', 'type' => 'warning' } ]; $result_converted{'info'}->{'<API key>'} = 'This is , produced by tp version from . File: , Node: Top, Next: Top, Prev: Top, Up: (dir) *Note ToP::. *Note ToP::. * Menu: * tOP:: Tag Table: Node: Top41 End Tag Table '; 1;
package org.dmfs.xmlserializer; import java.io.IOException; import java.io.Writer; /** * An abstract XML node. * * @author Marten Gajda <marten@dmfs.org> */ public abstract class XmlAbstractNode { /** * State for new nodes. */ final static int STATE_NEW = 0; /** * State indicating the node has been opened and the start tag has been opened. */ final static int <API key> = 1; /** * State indication the node has been opened and the start tag has been closed, but the end tag is not written yet. */ final static int <API key> = 2; /** * State indication the node has been closed (i.e. the end tag has been written). */ final static int STATE_CLOSED = 3; /** * The state of a node, initialized with {@link STATE_NEW}. */ int state = STATE_NEW; /** * The depth at which this node is located in the XML tree. Until this node has been added to a tree it is considered to be the root element. */ private int mDepth = 0; /** * Set the depth of this node (i.e. at which level it is located in the XML node tree). * * @param depth * The depth. */ void setDepth(int depth) { mDepth = depth; } /** * Get the depth of this node (i.e. at which level it is located in the XML node tree). * * @return The depth. */ final int getDepth() { return mDepth; } /** * Assign the {@link <API key>} that belongs to this XML tree. * * @param namespaceRegistry * The {@link <API key>} of this XMl tree. * @throws <API key> */ abstract void <API key>(<API key> namespaceRegistry) throws <API key>; /** * Open this node for writing to a {@link Writer} * * @param out * The {@link Writer} to write to. * @throws IOException * @throws <API key> * @throws <API key> */ abstract void open(Writer out) throws IOException, <API key>, <API key>; /** * Close this node, flushing out all unwritten content. * * @throws IOException * @throws <API key> * @throws <API key> */ abstract void close() throws IOException, <API key>, <API key>; }
<? include('global.php'); ?> <? // asp2php (vbscript) converted on Sat Apr 25 20:59:49 2015 $CODEPAGE="1252";?> <? require("Connections/connrumbo.php"); ?> <? $Siniestros__DDcia="%"; if (($_POST["Cia"]!="")) { $Siniestros__DDcia=$_POST["Cia"]; } ?> <? // $Siniestros is of type "ADODB.Recordset" echo $MM_connrumbo_STRING; echo "SELECT Abonados.Nombre, Abonados.Apellido1, Abonados.Apellido2, Siniestro.Compañia as cpropia, Contrarios.Compañia as cia, Siniestro.Fase, Fases.Texto, Siniestro.Id, Siniestro.[Fecha Siniestro] FROM Fases INNER JOIN ((Abonados INNER JOIN Siniestro ON Abonados.Id = Siniestro.Abonado) INNER JOIN Contrarios ON Siniestro.Id = Contrarios.Siniestro) ON Fases.Id = Siniestro.Fase WHERE (((Contrarios.Compañia)like '%"+str_replace("'","''",$Siniestros__DDcia)+"%') AND ((Siniestro.Fase)<70)) ORDER BY Siniestro.Fase"; echo 0; echo 2; echo 1; $rs=mysql_query(); $Siniestros_numRows=0; ?> <? $Repeat1__numRows=-1; $Repeat1__index=0; $Siniestros_numRows=$Siniestros_numRows+$Repeat1__numRows; ?> <html> <head> <title>Listado por Cia. Contraria</title> </head> <body bgcolor="#FFFFFF" background="Imagenes/fondo.gif" bgproperties="fixed" text="#000000" topmargin="30"> <script language="JavaScript" src="menu.js"></script> <table width="100%" border="1" cellspacing="0" bordercolor="#000000"> <tr bgcolor="#CCCCCC"> <td>Nombre</td> <td>Fecha de siniestro </td> <td>Compa&ntilde;ia</td> <td>Fase</td> </tr> <? while((($Repeat1__numRows!=0) && (!($Siniestros==0)))) { ?> <tr> <td><a href="Siniestro.asp?Id=<? echo (->$Item["Id"]->$Value);?>"><? echo (->$Item["Nombre"]->$Value);?>&nbsp;<? echo (->$Item["Apellido1"]->$Value);?>&nbsp;<? echo (->$Item["Apellido2"]->$Value);?></a></td> <td><? echo (->$Item["Fecha Siniestro"]->$Value);?></td> <td><? echo (->$Item["cia"]->$Value);?></td> <td><? echo (->$Item["Texto"]->$Value);?></td> </tr> <? $Repeat1__index=$Repeat1__index+1; $Repeat1__numRows=$Repeat1__numRows-1; $Siniestros=mysql_fetch_array($Siniestros_query); $Siniestros_BOF=0; } ?> </table> </body> </html> <? $Siniestros=null; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http: <html > <head><title>1.1.1.0 <API key>.py</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="TeX4ht (http: <meta name="originator" content="TeX4ht (http: <!-- html,index=2,3,4,5,next --> <meta name="src" content="mammult_doc.tex"> <meta name="date" content="2015-10-19 17:14:00"> <link rel="stylesheet" type="text/css" href="mammult_doc.css"> </head><body > <!--l. 3--><div class="crosslinks"><p class="noindent">[<a href="mammult_docsu5.html" >next</a>] [<a href="mammult_docsu3.html" >prev</a>] [<a href="mammult_docsu3.html#tailmammult_docsu3.html" >prev-tail</a>] [<a href="#tailmammult_docsu4.html">tail</a>] [<a href="mammult_docsu1.html#mammult_docsu4.html" >up</a>] </p></div> <h5 class="subsubsectionHead"><a id="x8-70001.1.1"></a><span class="cmtt-10x-x-109">node</span><span class="cmtt-10x-x-109">_activity</span><span class="cmtt-10x-x-109">_vectors.py</span></h5> <!--l. 3--><p class="noindent" ><span class="cmbx-10x-x-109">NAME</span> <!--l. 3--><p class="indent" > <span class="cmbx-10x-x-109">node</span><span class="cmbx-10x-x-109">_activity</span><span class="cmbx-10x-x-109">_vectors.py </span>- compute the activity vectors of all the nodes of a multiplex. <!--l. 3--><p class="noindent" ><span class="cmbx-10x-x-109">SYNOPSYS</span> <!--l. 3--><p class="indent" > <span class="cmbx-10x-x-109">node</span><span class="cmbx-10x-x-109">_activity</span><span class="cmbx-10x-x-109">_vectors.py </span><span class="cmmi-10x-x-109">&#x003C;</span><span class="cmitt-10x-x-109">layer1</span><span class="cmmi-10x-x-109">&#x003E; </span><span class="cmitt-10x-x-109">[</span><span class="cmmi-10x-x-109">&#x003C;</span><span class="cmitt-10x-x-109">layer2</span><span class="cmmi-10x-x-109">&#x003E; </span><span class="cmitt-10x-x-109">...]</span> <!--l. 15--><p class="noindent" ><span class="cmbx-10x-x-109">DESCRIPTION</span> <!--l. 15--><p class="indent" > Compute and print on output the activity vectors of the nodes of a multiplex network, whose layers are given as input in the files <span class="cmti-10x-x-109">layer1</span>, <span class="cmti-10x-x-109">layer2</span>, etc. <!--l. 15--><p class="indent" > Each input file contains the (undirected) edge list of a layer, and each line is in the format: <!--l. 15--><p class="indent" > &#x00A0; <span class="cmti-10x-x-109">src</span><span class="cmti-10x-x-109">_ID dest</span><span class="cmti-10x-x-109">_ID</span> <!--l. 15--><p class="indent" > where <span class="cmti-10x-x-109">src</span><span class="cmti-10x-x-109">_ID </span>and <span class="cmti-10x-x-109">dest</span><span class="cmti-10x-x-109">_ID </span>are the IDs of the two endpoints of an edge. <!--l. 26--><p class="noindent" ><span class="cmbx-10x-x-109">OUTPUT</span> <!--l. 26--><p class="indent" > The program prints on <span class="cmtt-10x-x-109">stdout </span>a list of lines, where the n-th line contains the activity vector of the n-th node, i.e. a bit-string where each bit is set to &#8220;1&#8221; if the node is active on the corresponding layer, and to &#8220;0&#8221; otherwise. <!--l. 26--><p class="noindent" >As usual, node IDs start from zero and proceed sequentially, without gaps, i.e., if a node ID is not present in any of the layer files given as input, the program considers it as being isolated on all the layers, and will print on output a bit-string of zeros. <!--l. 28--><p class="noindent" ><span class="cmbx-10x-x-109">REFERENCE</span> <!--l. 28--><p class="indent" > V. Nicosia, V. Latora, &#8220;Measuring and modeling correlations in multiplex networks&#8221;, <span class="cmti-10x-x-109">Phys. Rev. E </span><span class="cmbx-10x-x-109">92</span>, 032805 (2015). <!--l. 28--><p class="indent" > Link to paper: <a href="http://journals.aps.org/pre/abstract/10.1103/PhysRevE.92.032805" class="url" ><span class="cmtt-10x-x-109">http://journals.aps.org/pre/abstract/10.1103/PhysRevE.92.032805</span></a> <!--l. 3--><div class="crosslinks"><p class="noindent">[<a href="mammult_docsu5.html" >next</a>] [<a href="mammult_docsu3.html" >prev</a>] [<a href="mammult_docsu3.html#tailmammult_docsu3.html" >prev-tail</a>] [<a href="mammult_docsu4.html" >front</a>] [<a href="mammult_docsu1.html#mammult_docsu4.html" >up</a>] </p></div> <!--l. 3--><p class="indent" > <a id="tailmammult_docsu4.html"></a> </body></html>
#ifndef <API key> #define <API key> #ifdef __cplusplus define extern "C" { #endif #include <ert/util/hash.h> #include <ert/config/config_schema_item.h> #include <ert/config/config_path_elm.h> typedef struct <API key> <API key>; <API key> * <API key>( const <API key> * schema , const <API key> * cwd); void <API key>(<API key> * node , const char * value); void <API key>(<API key> * node , const stringlist_type * token_list); char * <API key>(const <API key> * node, const char * sep); void <API key>(<API key> * node); void <API key>(void * arg); const char * <API key>( <API key> * node , const char * sep ); const char * <API key>(const <API key> * node , int index); bool <API key>(const <API key> * node , int index); int <API key>(const <API key> * node , int index); double <API key>(const <API key> * node , int index); const char * <API key>(<API key> * node , int index); const char * <API key>( <API key> * node , int index); const char * <API key>( <API key> * node , int index); const stringlist_type * <API key>( const <API key> * node ); const char * <API key>(const <API key> * node , int index); int <API key>( const <API key> * node ); const char * <API key>( const <API key> * node ); void <API key>( const <API key> * node ); const <API key> * <API key>( const <API key> * node ); void <API key>( const <API key> * node , hash_type * opt_hash , int elm_offset); void <API key>( const <API key> * node , FILE * stream ); #ifdef __cplusplus } #endif #endif
package beseenium.controller.ActionFactory; import java.net.<API key>; import java.util.HashMap; import java.util.Map; import beseenium.controller.ActionDataFactory.ActionDataFactory; import beseenium.controller.ActionFactory.elementActions.MakeClear; import beseenium.controller.ActionFactory.elementActions.MakeClick; import beseenium.controller.ActionFactory.elementActions.MakeGetAttribute; import beseenium.controller.ActionFactory.elementActions.MakeGetCssValue; import beseenium.controller.ActionFactory.elementActions.MakeGetLocation; import beseenium.controller.ActionFactory.elementActions.MakeGetSize; import beseenium.controller.ActionFactory.elementActions.MakeGetTagName; import beseenium.controller.ActionFactory.elementActions.MakeGetText; import beseenium.controller.ActionFactory.elementActions.MakeIsDisplayed; import beseenium.controller.ActionFactory.elementActions.MakeIsEnabled; import beseenium.controller.ActionFactory.elementActions.MakeIsSelected; import beseenium.controller.ActionFactory.elementActions.MakeSendKeys; import beseenium.controller.ActionFactory.elementActions.MakeSubmit; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.findElementsBy.<API key>; import beseenium.controller.ActionFactory.navigateActions.MakeNavigateBack; import beseenium.controller.ActionFactory.navigateActions.MakeNavigateForward; import beseenium.controller.ActionFactory.navigateActions.MakeRefreshPage; import beseenium.controller.ActionFactory.pageActions.MakeBrowserQuit; import beseenium.controller.ActionFactory.pageActions.MakeGetPageSrc; import beseenium.controller.ActionFactory.pageActions.MakeGetTitle; import beseenium.controller.ActionFactory.pageActions.MakeGetURL; import beseenium.controller.ActionFactory.pageActions.MakePageClose; import beseenium.controller.ActionFactory.pageActions.MakePageGet; import beseenium.exceptions.<API key>.<API key>; import beseenium.exceptions.actionExceptions.<API key>; import beseenium.model.action.AbstractAction; /** * this class is a factory for creating actions, it uses a factory method * style pattern and a map implementation. * @author JPC Hanson * */ public class ActionFactory { /** the map to store the actions in **/ private Map<String, MakeAction> actionMap; /** internal ActionDataFactory reference **/ private ActionDataFactory actionDataFactory; /** * default constructor creates and populates internal map * @param actionDataFactory * @throws <API key> * @throws <API key> * */ public ActionFactory(ActionDataFactory actionDataFactory) throws <API key>, <API key> { super(); this.actionDataFactory = actionDataFactory; this.actionMap = new HashMap<String, MakeAction>(); this.populateActionMap(); } /** * creates an Action * @return AbstractAction * @throws <API key> * @throws <API key> */ public AbstractAction makeAction(String actionKey) throws <API key> { if(this.actionMap.containsKey(actionKey)) {return this.actionMap.get(actionKey).makeAction();} else {throw new <API key>("you cannot instanciate this type of Action '" +actionKey+ "' Check your spelling, or refer to documentation");} } /** * creates all possible actions and populates the map with them. * @throws <API key> * */ private void populateActionMap() throws <API key> { // //Page Actions this.actionMap.put( "PageGet", new MakePageGet(actionDataFactory)); this.actionMap.put( "GetPageSrc", new MakeGetPageSrc(actionDataFactory)); this.actionMap.put( "BrowserQuit", new MakeBrowserQuit(actionDataFactory)); this.actionMap.put( "GetTitle", new MakeGetTitle(actionDataFactory)); this.actionMap.put( "GetURL", new MakeGetURL(actionDataFactory)); this.actionMap.put( "PageClose", new MakePageClose(actionDataFactory)); // //Navigation Actions this.actionMap.put( "NavigateBack", new MakeNavigateBack(actionDataFactory)); this.actionMap.put( "NavigateForward", new MakeNavigateForward(actionDataFactory)); this.actionMap.put( "RefreshPage", new MakeRefreshPage(actionDataFactory)); // //Find Element Actions this.actionMap.put( "FindElementsByClass", new <API key>(actionDataFactory)); this.actionMap.put( "FindElementsByCss", new <API key>(actionDataFactory)); this.actionMap.put( "FindElementsById", new <API key>(actionDataFactory)); this.actionMap.put( "<API key>", new <API key>(actionDataFactory)); this.actionMap.put( "FindElementsByName", new <API key>(actionDataFactory)); this.actionMap.put( "<API key>", new <API key>(actionDataFactory)); this.actionMap.put( "<API key>", new <API key>(actionDataFactory)); this.actionMap.put( "FindElementsByXpath", new <API key>(actionDataFactory)); // //Element Actions this.actionMap.put( "Clear", new MakeClear(actionDataFactory)); this.actionMap.put( "Click", new MakeClick(actionDataFactory)); this.actionMap.put( "GetAttribute", new MakeGetAttribute(actionDataFactory)); this.actionMap.put( "GetCssValue", new MakeGetCssValue(actionDataFactory)); this.actionMap.put( "GetLocation", new MakeGetLocation(actionDataFactory)); this.actionMap.put( "GetSize", new MakeGetSize(actionDataFactory)); this.actionMap.put( "GetTagName", new MakeGetTagName(actionDataFactory)); this.actionMap.put( "GetText", new MakeGetText(actionDataFactory)); this.actionMap.put( "IsDisplayed", new MakeIsDisplayed(actionDataFactory)); this.actionMap.put( "IsEnabled", new MakeIsEnabled(actionDataFactory)); this.actionMap.put( "IsSelected", new MakeIsSelected(actionDataFactory)); this.actionMap.put( "SendKeys", new MakeSendKeys(actionDataFactory)); this.actionMap.put( "Submit", new MakeSubmit(actionDataFactory)); } }
package proyectomio.controlador.operaciones; import proyectomio.accesoDatos.Controlador_BD; import proyectomio.modelo.Consulta; /** * * @author root */ public class <API key> { private final Controlador_BD CONTROLADOR_BD = new Controlador_BD(); public Consulta <API key>(int id_conductor) { if (id_conductor != 0) { Consulta consulta = new Consulta(); consulta = CONTROLADOR_BD.consultarBD("SELECT * FROM bus_empleado inner join bus on bus_empleado.placa_bus = bus.placa inner join ruta on ruta.id_ruta = bus.id_ruta where bus_empleado.id_empleado = " + id_conductor); return consulta; } else{ Consulta consulta = new Consulta(); consulta = CONTROLADOR_BD.consultarBD("SELECT * FROM (bus_empleado inner join bus on bus_empleado.placa_bus = bus.placa) inner join ruta on ruta.id_ruta = bus.id_ruta;"); return consulta; } } }
#include <cstdio> #include <vector> #include <utility> #include <algorithm> using namespace std; pair<int, int> <API key>(const vector<vector<int> > & adjList, int startV, const vector<int> & weightOfVertex); int main(void) { int T, numV, numE, u, v, caseId; vector<vector<int> > adjList; vector<int> emptyList, weightOfVertex; scanf("%d", &T); pair<int, int> maxLearnAndDest; caseId = 1; while(caseId <= T) { scanf("%d %d", &numV, &numE); adjList.assign(numV, emptyList); weightOfVertex.assign(numV, 0); for(v = 0; v < numV; v++) scanf("%d", &weightOfVertex[v]); for(int e = 0; e < numE; e++) { scanf("%d %d", &u, &v); adjList[u].push_back(v); } maxLearnAndDest = <API key>(adjList, 0, weightOfVertex); printf("Case %d: %d %d\n", caseId, maxLearnAndDest.first, maxLearnAndDest.second); caseId++; } return 0; } pair<int, int> <API key>(const vector<vector<int> > & adjList, int startV, const vector<int> & weightOfVertex) { int v = startV, totalWeight, maxNeighborInd; totalWeight = weightOfVertex[startV]; while(adjList[v].size() > 0) { maxNeighborInd = 0; for(int ind = 1; ind < (int) adjList[v].size(); ind++) if(weightOfVertex[adjList[v][ind]] > weightOfVertex[adjList[v][maxNeighborInd]]) maxNeighborInd = ind; totalWeight += weightOfVertex[adjList[v][maxNeighborInd]]; v = adjList[v][maxNeighborInd]; } return make_pair(totalWeight, v); }
<?php // For more information, see licence.txt in the main folder // This is a simple page to create accounts. // Due to the need of reading conf files this script has to be located // inside the Aura web folder, or you have to adjust some paths. include '../shared/Conf.class.php'; include '../shared/MabiDb.class.php'; $conf = new Conf(); $conf->load('../../conf/database.conf'); $db = new MabiDb(); $db->init($conf->get('database.host'), $conf->get('database.user'), $conf->get('database.pass'), $conf->get('database.db')); $succs = false; $error = ''; $user = ''; $pass = ''; $pass2 = ''; if(isset($_POST['register'])) { $user = $_POST['user']; $pass = $_POST['pass']; $pass2 = $_POST['pass2']; if(!preg_match('~^[a-z0-9]{4,20}$~i', $user)) $error = 'Invalid username (4-20 characters).'; else if($pass !== $pass2) $error = 'Passwords don\'t match.'; else if(!preg_match('~^[a-z0-9]{6,24}$~i', $pass)) $error = 'Invalid password (6-24 characters).'; else if($db->accountExists($user)) $error = 'Username already exists.'; else { $db->createAccount($user, $pass); $succs = true; } } ?> <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Register - Aura</title> <link rel="stylesheet" href="../shared/css/reset.css" media="all" /> <link rel="stylesheet" href="style.css" media="all" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <!--[if IE]> <script src="../shared/js/ie.js"></script> <![endif] </head> <body> <a href="<?php echo basename(__FILE__) ?>"><img src="../shared/images/logo_white.png" alt="Aura"/></a> <?php if(!$succs): ?> <?php if(!empty($error)): ?> <div class="notice"> <?php echo $error ?> </div> <?php endif; ?> <form method="post" action="<?php echo basename(__FILE__) ?>"> <table> <tr> <td class="desc">Username</td> <td class="inpt"><input type="text" name="user" value="<?php echo $user ?>"/></td> </tr> <tr> <td class="desc">Password</td> <td class="inpt"><input type="password" name="pass" value="<?php echo $pass ?>"/></td> </tr> <tr> <td class="desc">Password Repeat</td> <td class="inpt"><input type="password" name="pass2" value="<?php echo $pass2 ?>"/></td> </tr> <tr> <td class="desc"></td> <td class="inpt"><input type="submit" name="register" value="Register"/></td> </tr> </table> </form> <?php else: ?> <div class="notice"> <?php echo 'Account created successfully!' ?> </div> <?php endif; ?> </body> </html>
<!DOCTYPE html> <html lang="fr"> <html> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="./assets/css/mail.css"/> </head> <body bgcolor="#E6E6FA"> <?php include 'back-submit-mail.php';?> <h1 class="first">&nbsp;</h1> <?php // define variables and set to empty values $fnameErr = $lnameErr = $emailErr = $websiteErr = ""; $fname = $lname = $email = $subject = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["fname"])) { $fnameErr = "Firts name is required"; } else { $fname = test_input($_POST["fname"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$fname)) { $fnameErr = "Only letters and white space allowed"; } } if (empty($_POST["lname"])) { $lnameErr = "Last name is required"; } else { $lname = test_input($_POST["lname"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$lname)) { $lnameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, <API key>)) { $emailErr = "Invalid email format"; } } if (empty($_POST["subject"])) { $subject = ""; } else { $subject = test_input($_POST["subject"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <!-- Form content --> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <span class="error">*<?php echo $fnameErr;?></span> <label for="fname">Prénom</label> <input type="text" id="fname" name="fname" placeholder="Votre prénom..."> <span class="error">*<?php echo $lnameErr;?></span> <label for="lname">Nom</label> <input type="text" id="lname" name="lname" placeholder="Votre nom..."> <span class="error">*<?php echo $emailErr;?></span> <label for="mail">Email</label> <input type="text" id="mail" name="email" placeholder="Votre email..."> <label for="country">Pays</label> <select id="country" name="country"> <option value="australia">Belgium</option> <option value="usa">USA</option> <option value="canada">Canada</option> </select> <label for="subject">Sujet</label> <textarea id="subject" name="subject" placeholder="Ecrivez quelque chose..." style="height:200px"></textarea> </form> <?php echo $fname; echo "<br>"; echo $lname; echo "<br>"; echo $email; echo "<br>"; echo $subject; echo "<br>"; ?> </body> </html>
**A small bundle to create endless running commands with Symfony.** These endless running commands are very easy to daemonize with something like Upstart or systemd. ## Why do I need this? Because you want to create long running PHP/Symfony processes! For example to send mails with large attachment, process (delayed) payments or generate large PDF reports. They query the database or read from a message queue and do their job. This bundle makes it very easy to create such processes as Symfony commands. ## How to install? Use composer to include it into your Symfony project: `composer require wrep/<API key>` What version to use? Symfony did make some breaking changes, so you should make sure to use a compatible bundle version: * Version 2.1.* for Symfony 4.0 and higher * Version 2.0.* for Symfony 3.0 - 3.4 * Version 1.3.* for Symfony 2.8 When upgrading, please consult the [changelog](Changelog.md) to see what could break your code. ## How to use? Just create a Symfony command that extends from `EndlessCommand` and off you go. Here is a minimal example: php namespace Acme\DemoBundle\Command; use Wrep\Daemonizable\Command\EndlessCommand; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputInterface; class MinimalDemoCommand extends EndlessCommand { // This is just a normal Command::configure() method protected function configure() { $this->setName('acme:minimaldemo') ->setDescription('An EndlessCommand implementation example'); } // Execute will be called in a endless loop protected function execute(InputInterface $input, OutputInterface $output) { // Tell the user what we're going to do. // This will be a NullOutput if the user doesn't want any output at all, // so you don't have to do any checks, just always write to the output. $output->write('Updating timestamp... '); // Do some work file_put_contents( '/tmp/acme-timestamp.txt', time() ); // Tell the user we're done $output->writeln('done'); } } Run it with `php app/console acme:minimaldemo`. An [example with all the bells and whistles](examples/ExampleCommand.php) is also available and gives a good overview of best practices and how to do some basic things. ## How to daemonize? Alright, now we have an endless running command *in the foreground*. Usefull for debugging, useless in production! So how do we make this thing a real daemon? You should use [systemd](http: If you can't use Upstart or systemd, you can use `.lock` file with [LockHandler](http: An [example Upstart script](examples/example-daemon.conf) is available, place your script in `/etc/init/` and start the daemon with `start example-daemon`. The name of the `.conf`-file will be the name of the daemon. A systemd example is not yet available, but it shouldn't be that hard to [figure out](http://patrakov.blogspot.nl/2011/01/<API key>.html). ## Command line switches A few switches are available by default to make life somewhat easier: * Use `-q` to suppress all output * Use `--run-once` to only run the command once, usefull for debugging * Use `--detect-leaks` to print a memory usage report after each run, read more in the next section ## Memory usage and leaks Memory usage is very important for long running processes. Symfony is not the smallest framework around and if you leak some memory in your execute method your daemon will crash! The `EndlessCommand` classes have been checked for memory leaks, but you should also check your own code. How to prevent leaks? Always start your command with the `-e prod --no-debug` flags. This disables all debugging features of Symfony that will eat up more and more memory. Do not use Monolog in Symfony 2.2 and lower, there is a [bug in the MonologBundle](https: Make sure you cleanup in the `execute`-method, make sure you're not appending data to an array every iteration or leave sockets/file handles open for example. In case you are using the fingers-crossed handler in Monolog, this will also be a source of memory leaks. The idea of this handler is to keep all below-threshold log entries in memory and only flush those in case of an above-threshold entry. You can still use the fingers-crossed handler as long as you manually flush it at the end of the `execute`-method: foreach ($this->getContainer()->get('logger')->getHandlers() as $handler) { if ($handler instanceof <API key>) { $handler->clear(); } } Detecting memory leaks Run your command with the `--detect-leaks` flag. Remember that debug mode will eat memory so you'll need to run with `-e prod --no-debug --detect-leaks` for accurate reports. After each iteration a memory report like this is printed on your console: == MEMORY USAGE == Peak: 30038.86 KByte stable (0.000 %) Cur.: 29856.46 KByte stable (0.000 %) The first 3 iterations may be unstable in terms of memory usage, but after that it should be stable. *Even a slight increase of memory usage will crash your daemon over time!* If you see an increase/stable/decrease loop you're probably save. It could be the garabage collector not cleaning up, you can fix this by using unset on variables to cleanup the memory yourself. Busting some myths Calling `gc_collect_cycles()` will not help to resolve leaks. PHP will cleanup memory right in time all by itself, calling this method may slow down leaking memory, but will not solve it. Also it makes spotting leaks harder, so just don't use it. If you run Symfony in production and non-debug mode it will not leak memory and you do not have to disable any SQL loggers. The only leak I runned into is the one in the MonologBundle mentioned above. Working with Doctrine For reasons <API key> clears after each Iteration Doctrine's EntityManager. Be aware of that. You can override finishIteration() to avoid this behaviour but you have to handle the EM on your own then.
{-# LANGUAGE ScopedTypeVariables #-} import Bench import Bench.Triangulations main = print (qVertexSolBench trs)
// Copyleft RIME Developers // 2013-04-18 GONG Chen <chen.sst@gmail.com> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <rime/dict/table_db.h> #include <rime/dict/user_db.h> // Rime table entry format: // phrase <Tab> code [ <Tab> weight ] // for multi-syllable phrase, code is a space-separated list of syllables // weight is a double precision float, defaulting to 0.0 namespace rime { static bool <API key>(const Tsv& row, std::string* key, std::string* value) { if (row.size() < 2 || row[0].empty() || row[1].empty()) { return false; } std::string code(row[1]); boost::algorithm::trim(code); *key = code + " \t" + row[0]; UserDbValue v; if (row.size() >= 3 && !row[2].empty()) { try { v.commits = boost::lexical_cast<int>(row[2]); const double kS = 1e8; v.dee = (v.commits + 1) / kS; } catch (...) { } } *value = v.Pack(); return true; } static bool <API key>(const std::string& key, const std::string& value, Tsv* tsv) { Tsv& row(*tsv); // key ::= code <space> <Tab> phrase boost::algorithm::split(row, key, boost::algorithm::is_any_of("\t")); if (row.size() != 2 || row[0].empty() || row[1].empty()) return false; UserDbValue v(value); if (v.commits < 0) // deleted entry return false; boost::algorithm::trim(row[0]); // remove trailing space row[0].swap(row[1]); row.push_back(boost::lexical_cast<std::string>(v.commits)); return true; } const TextFormat TableDb::format = { <API key>, <API key>, "Rime table", }; TableDb::TableDb(const std::string& name) : TextDb(name + ".txt", "tabledb", TableDb::format) { } // StableDb StableDb::StableDb(const std::string& name) : TableDb(name) {} bool StableDb::Open() { if (loaded()) return false; if (!Exists()) { LOG(INFO) << "stabledb '" << name() << "' does not exist."; return false; } return TableDb::OpenReadOnly(); } } // namespace rime
import React from 'react'; import { mount } from 'enzyme'; import { Link, HashRouter as Router } from 'react-router-dom'; import { Button } from 'react-bootstrap'; import BackHomeButton from '../BackHomeButton'; describe('<BackHomeButton/>', () => { it('<BackHomeButton /> should render <Router/>', () => { const component = mount(<BackHomeButton />); expect(component.find(Router)).toHaveLength(1); }); it('<BackHomeButton /> should render <Link/> with correct props', () => { const component = mount(<BackHomeButton />); expect(component.find(Router)).toHaveLength(1); expect(component.find(Link)).toHaveLength(1); const props = component.find(Link).props(); expect(props).toEqual({ to: '/', children: expect.anything() }); expect(component.find(Link)).toHaveLength(1); }); it('<BackHomeButton /> should render <Button/> with correct props', () => { const component = mount(<BackHomeButton />); expect(component.find(Router)).toHaveLength(1); expect(component.find(Link)).toHaveLength(1); expect(component.find(Button)).toHaveLength(1); const ButtonProps = component.find(Button).props(); expect(ButtonProps).toEqual({ variant: 'primary', children: 'Back Home', active: false, disabled: false, type: 'button', }); }); });
'use strict'; var Ose = require('ose'); var M = Ose.class(module, './index'); /** Docs {{{1 * @submodule bb.pagelet */ /** * @caption Dashboard pagelet * * @readme * Pagelet for creating dashboard content. * * @class bb.lib.pagelet.dashboard * @type class * @extends bb.lib.pagelet */ // Public {{{1 exports.loadData = function(cb) { /** * Has a new list widget created and appends it to the main pagelet * element. It also calls the "Ose.ui.dashboard()" * method. "Ose.ui.dashboard()" governs what is diaplayed on the * dashboard. * * @method loadData */ if (cb) { this.doAfterDisplay = cb; } this.$('header').html('Dashboard'); this.$() .empty() .append(this.newWidget('list', 'list')) ; if (Ose.ui.configData.dashboard) { this.addContents(Ose.ui.configData.dashboard); } if (Ose.ui.dashboard) { Ose.ui.dashboard(this, this.afterDisplay.bind(this)); } else { this.afterDisplay(); } }; exports.addContent = function(caption, stateObj) { /** * Adds an item to the dashboard. * * @param caption {String} Text to be displayed * @param stateObj {Object} State object that should be displayed when the user taps on this item. */ return this.addItem(caption, Ose.ui.bindContent(stateObj)); }; exports.addContents = function(data) { /** * Adds items to the dashboard. * * @param data {Array} Array of items */ for (var i = 0; i < data.length; i++) { var item = data[i]; this.addContent(item.caption, item.data); } }; exports.addItem = function(caption, onTap) { /** * Adds an item to the dashboard. * * @param caption {String} Text to be displayed * @param onTap {Function} Function to be called when the user taps on this item. */ return this.$('list > ul').append( this.newWidget('listItem', null, { tap: onTap, caption: caption }) ); }; exports.addPagelet = function(params, cb) { /** * Adds an item to the dashboardk. * * @param caption {String} Text to be displayed * @param cb {Function} Function to be called when the user taps on this item. */ var result = this.newPagelet(params); $('<li>') .append(result.html()) .appendTo(this.$('list > ul')) ; result.loadData(); cb(); // TODO Send "cb" to loadData. return result; }; exports.verifyStateObj = function(data) { /** * Verifies that data correspond to the displayed pagelet. * * @param data {Object} State object to be compared * * @returns {Boolean} Whether data correspond to the displayed pagelet * @method verifyStateObj */ return data.pagelet === 'dashboard'; };
#ifndef QUEUE_H #define QUEUE_H #include <ext/struct/Node.h> #include <ext/struct/List.h> #ifdef __cplusplus extern "C" { #endif typedef struct list queue; struct EngineQueue { queue * (*createEmpty)(int(*cmp)(void *a, void *b), char *(*toString)(void *a), void (*destroy)(void *a)); int (*add)(queue *list, void *data); int (*edit)(queue *list, void *oldElement, void *newElement); int (*del)(queue *list); void (*walk)(queue *list, void (*fnct)(void *data, void *extra), void *extra); void * (*search)(queue *list, void *data); char * (*toString)(queue *list); void ** (*toArray)(queue *list, int * count); void (*fromArray)(queue *list, void **, int count); void (*destroy)(queue *list); } Queue; void initQueue(); #ifdef __cplusplus } #endif #endif /* QUEUE_H */
/* * * Mouse driver * */ #include <kernel/system.h> #include <kernel/logging.h> #include <kernel/pipe.h> #include <kernel/module.h> #include <kernel/mouse.h> #include <kernel/args.h> static uint8_t mouse_cycle = 0; static uint8_t mouse_byte[4]; #define PACKETS_IN_PIPE 1024 #define DISCARD_POINT 32 #define MOUSE_IRQ 12 #define MOUSE_PORT 0x60 #define MOUSE_STATUS 0x64 #define MOUSE_ABIT 0x02 #define MOUSE_BBIT 0x01 #define MOUSE_WRITE 0xD4 #define MOUSE_F_BIT 0x20 #define MOUSE_V_BIT 0x08 #define MOUSE_DEFAULT 0 #define MOUSE_SCROLLWHEEL 1 #define MOUSE_BUTTONS 2 static int8_t mouse_mode = MOUSE_DEFAULT; static fs_node_t * mouse_pipe; void (*ps2_mouse_alternate)(void) = NULL; static void mouse_wait(uint8_t a_type) { uint32_t timeout = 100000; if (!a_type) { while (--timeout) { if ((inportb(MOUSE_STATUS) & MOUSE_BBIT) == 1) { return; } } debug_print(INFO, "mouse timeout"); return; } else { while (--timeout) { if (!((inportb(MOUSE_STATUS) & MOUSE_ABIT))) { return; } } debug_print(INFO, "mouse timeout"); return; } } static void mouse_write(uint8_t write) { mouse_wait(1); outportb(MOUSE_STATUS, MOUSE_WRITE); mouse_wait(1); outportb(MOUSE_PORT, write); } static uint8_t mouse_read(void) { mouse_wait(0); char t = inportb(MOUSE_PORT); return t; } static int mouse_handler(struct regs *r) { uint8_t status = inportb(MOUSE_STATUS); while ((status & MOUSE_BBIT) && (status & MOUSE_F_BIT)) { if (ps2_mouse_alternate) { ps2_mouse_alternate(); break; } int8_t mouse_in = inportb(MOUSE_PORT); switch (mouse_cycle) { case 0: mouse_byte[0] = mouse_in; if (!(mouse_in & MOUSE_V_BIT)) break; ++mouse_cycle; break; case 1: mouse_byte[1] = mouse_in; ++mouse_cycle; break; case 2: mouse_byte[2] = mouse_in; if (mouse_mode == MOUSE_SCROLLWHEEL || mouse_mode == MOUSE_BUTTONS) { ++mouse_cycle; break; } goto finish_packet; case 3: mouse_byte[3] = mouse_in; goto finish_packet; } goto read_next; finish_packet: mouse_cycle = 0; /* We now have a full mouse packet ready to use */ <API key> packet; packet.magic = MOUSE_MAGIC; int x = mouse_byte[1]; int y = mouse_byte[2]; if (x && mouse_byte[0] & (1 << 4)) { /* Sign bit */ x = x - 0x100; } if (y && mouse_byte[0] & (1 << 5)) { /* Sign bit */ y = y - 0x100; } if (mouse_byte[0] & (1 << 6) || mouse_byte[0] & (1 << 7)) { /* Overflow */ x = 0; y = 0; } packet.x_difference = x; packet.y_difference = y; packet.buttons = 0; if (mouse_byte[0] & 0x01) { packet.buttons |= LEFT_CLICK; } if (mouse_byte[0] & 0x02) { packet.buttons |= RIGHT_CLICK; } if (mouse_byte[0] & 0x04) { packet.buttons |= MIDDLE_CLICK; } if (mouse_mode == MOUSE_SCROLLWHEEL && mouse_byte[3]) { if ((int8_t)mouse_byte[3] > 0) { packet.buttons |= MOUSE_SCROLL_DOWN; } else if ((int8_t)mouse_byte[3] < 0) { packet.buttons |= MOUSE_SCROLL_UP; } } <API key> bitbucket; while (pipe_size(mouse_pipe) > (int)(DISCARD_POINT * sizeof(packet))) { read_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&bitbucket); } write_fs(mouse_pipe, 0, sizeof(packet), (uint8_t *)&packet); read_next: break; } irq_ack(MOUSE_IRQ); return 1; } static int ioctl_mouse(fs_node_t * node, int request, void * argp) { if (request == 1) { mouse_cycle = 0; return 0; } return -1; } static int mouse_install(void) { debug_print(NOTICE, "Initializing PS/2 mouse interface"); uint8_t status, result; IRQ_OFF; while ((inportb(0x64) & 1)) { inportb(0x60); } mouse_pipe = make_pipe(sizeof(<API key>) * PACKETS_IN_PIPE); mouse_wait(1); outportb(MOUSE_STATUS, 0xA8); mouse_read(); mouse_wait(1); outportb(MOUSE_STATUS, 0x20); mouse_wait(0); status = inportb(0x60) | 3; mouse_wait(1); outportb(MOUSE_STATUS, 0x60); mouse_wait(1); outportb(MOUSE_PORT, status); mouse_write(0xF6); mouse_read(); mouse_write(0xF4); mouse_read(); /* Try to enable scroll wheel (but not buttons) */ if (!args_present("nomousescroll")) { mouse_write(0xF2); mouse_read(); result = mouse_read(); mouse_write(0xF3); mouse_read(); mouse_write(200); mouse_read(); mouse_write(0xF3); mouse_read(); mouse_write(100); mouse_read(); mouse_write(0xF3); mouse_read(); mouse_write(80); mouse_read(); mouse_write(0xF2); mouse_read(); result = mouse_read(); if (result == 3) { mouse_mode = MOUSE_SCROLLWHEEL; } } /* keyboard scancode set */ mouse_wait(1); outportb(MOUSE_PORT, 0xF0); mouse_wait(1); outportb(MOUSE_PORT, 0x02); mouse_wait(1); mouse_read(); irq_install_handler(MOUSE_IRQ, mouse_handler, "ps2 mouse"); IRQ_RES; uint8_t tmp = inportb(0x61); outportb(0x61, tmp | 0x80); outportb(0x61, tmp & 0x7F); inportb(MOUSE_PORT); while ((inportb(0x64) & 1)) { inportb(0x60); } mouse_pipe->flags = FS_CHARDEVICE; mouse_pipe->ioctl = ioctl_mouse; vfs_mount("/dev/mouse", mouse_pipe); return 0; } static int mouse_uninstall(void) { /* TODO */ return 0; } MODULE_DEF(ps2mouse, mouse_install, mouse_uninstall);
#include<bits/stdc++.h> using namespace std; typedef long long LL; LL n,m,A,B,C; LL solve1(LL x,LL y){ LL ans=0; ans+=y*max(max(A,B),C); if(x%2==1){ ans+=max((x-1)*(A+C)/2,(x-1)*B); }else{ ans+=max((x-2)*(A+C)/2,(x-2)*B); ans+=max(B,min(A,C)); } return ans; } LL solve2(LL x,LL y){ LL ans=0; ans+=x*min(min(A,B),C); if(y%2==1){ ans+=min((y-1)*(A+C)/2,(y-1)*B); }else{ ans+=min((y-2)*(A+C)/2,(y-2)*B); ans+=min(B,max(A,C)); } return ans; } int main(){ int T;cin>>T; for(int t=1;t<=T;t++){ cin>>n>>m; cin>>A>>B>>C; printf("Case #%d: %lld %lld\n",t,solve1(m+1,n-m-1),solve2(m-1,n-m+1)); } return 0; }
package io.github.notsyncing.cowherd.files; import io.github.notsyncing.cowherd.Cowherd; import io.github.notsyncing.cowherd.commons.<API key>; import io.github.notsyncing.cowherd.commons.RouteType; import io.github.notsyncing.cowherd.models.ActionMethodInfo; import io.github.notsyncing.cowherd.models.RouteInfo; import io.github.notsyncing.cowherd.models.UploadFileInfo; import io.github.notsyncing.cowherd.routing.RouteManager; import io.github.notsyncing.cowherd.server.CowherdLogger; import io.github.notsyncing.cowherd.utils.StringUtils; import io.vertx.core.Vertx; import io.vertx.core.file.FileSystem; import java.io.File; import java.io.IOException; import java.lang.reflect.<API key>; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDate; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; public class FileStorage { private Map<Enum, Path> storagePaths = new ConcurrentHashMap<>(); private FileSystem fs; private CowherdLogger log = CowherdLogger.getInstance(this); public FileStorage(Vertx vertx) { init(vertx); } public FileStorage() throws <API key>, <API key>, <API key> { this(Cowherd.dependencyInjector.getComponent(Vertx.class)); } protected void init(Vertx vertx) { try { fs = vertx.fileSystem(); } catch (Exception e) { log.e("Failed to create file storage", e); } } /** * * @param tag * @param path * @throws IOException */ public void registerStoragePath(Enum tag, String path) throws IOException { registerStoragePath(tag, Paths.get(path)); } /** * * @param tag * @param path * @throws IOException */ public void registerStoragePath(Enum tag, Path path) throws IOException { if (storagePaths.containsKey(tag)) { log.w("Tag " + tag + " already registered to path " + storagePaths.get(tag) + ", will be overwritten to " + path); } storagePaths.put(tag, path); if (!Files.exists(path)) { Path p = Files.createDirectories(path); log.i("Created storage path " + p + " for tag " + tag); } else { log.i("Registered storage path " + path + " to tag " + tag); } } /** * * @param tag * @return */ public Path getStoragePath(Enum tag) { return storagePaths.get(tag); } /** * * @param file * @param tag * @param newFileName null * @param noRemoveOld true * @return CompletableFuture */ public CompletableFuture<Path> storeFile(Path file, Enum tag, String newFileName, boolean noRemoveOld) { CompletableFuture<Path> f = new CompletableFuture<>(); String fileName = newFileName == null ? file.getFileName().toString() : newFileName; Path store = storagePaths.get(tag); Path to; if (store == null) { f.<API key>(new Exception("Storage tag " + tag + " not registered!")); return f; } if (<API key>.isStoreFilesByDate()) { LocalDate date = LocalDate.now(); to = store.resolve(String.valueOf(date.getYear())).resolve(String.valueOf(date.getMonthValue())) .resolve(String.valueOf(date.getDayOfMonth())); try { Files.createDirectories(to); } catch (Exception e) { f.<API key>(e); return f; } to = to.resolve(fileName); } else { to = store.resolve(fileName); } final Path finalTo = to; fs.copy(file.toString(), to.toString(), r -> { if (r.succeeded()) { if (noRemoveOld) { f.complete(store.relativize(finalTo)); } else { fs.delete(file.toString(), r2 -> { if (r2.succeeded()) { f.complete(finalTo); } else { f.<API key>(r2.cause()); } }); } } else { f.<API key>(r.cause()); } }); return f; } /** * * @param file * @param tag * @param newFileName null * @param noRemoveOld true * @return CompletableFuture */ public CompletableFuture<Path> storeFile(File file, Enum tag, String newFileName, boolean noRemoveOld) { return storeFile(file.toPath(), tag, newFileName, noRemoveOld); } /** * * @param file * @param tag * @param newFileName null * @param noRemoveOld true * @return CompletableFuture */ public CompletableFuture<Path> storeFile(String file, Enum tag, String newFileName, boolean noRemoveOld) { return storeFile(Paths.get(file), tag, newFileName, noRemoveOld); } /** * * @param file * @param tag * @param newFileName null * @param noRemoveOld true * @return CompletableFuture */ public CompletableFuture<Path> storeFile(UploadFileInfo file, Enum tag, String newFileName, boolean noRemoveOld) { if (file == null) { return CompletableFuture.completedFuture(null); } return storeFile(file.getFile(), tag, newFileName, noRemoveOld); } /** * * @param file * @param tag * @return CompletableFuture */ public CompletableFuture<Path> storeFile(UploadFileInfo file, Enum tag) { if (file == null) { return CompletableFuture.completedFuture(null); } if ((StringUtils.isEmpty(file.getFilename())) && ((file.getFile() == null) || (file.getFile().length() <= 0))) { return CompletableFuture.completedFuture(null); } return storeFile(file.getFile(), tag, file.getFilename(), false); } /** * * @param file * @param tag * @return CompletableFuture */ public CompletableFuture<Path> <API key>(UploadFileInfo file, Enum tag) { if (file == null) { return CompletableFuture.completedFuture(null); } if ((StringUtils.isEmpty(file.getFilename())) && ((file.getFile() == null) || (file.getFile().length() <= 0))) { return CompletableFuture.completedFuture(null); } String fn = file.getFilename(); int e = fn.lastIndexOf('.'); String ext = e > 0 ? fn.substring(e) : ""; String filename = UUID.randomUUID().toString() + ext; return storeFile(file.getFile(), tag, filename, false); } /** * * @param tag * @param file * @return */ public Path resolveFile(Enum tag, Path file) { return storagePaths.get(tag).resolve(file); } /** * * @param tag * @param file * @return */ public Path relativize(Enum tag, Path file) { return getStoragePath(tag).relativize(file); } private void addServerRoute(RouteInfo route) { Method m; try { m = <API key>.class.getMethod("getFile", Enum.class, String.class); } catch (<API key> e) { log.e("No action for file storage!", e); return; } RouteManager.addRoute(route, new ActionMethodInfo(m)); } /** * * @param tag * @param routeRegex path */ public void registerServerRoute(Enum tag, String routeRegex) { RouteInfo info = new RouteInfo(); info.setPath(routeRegex); info.setType(RouteType.Http); info.setOtherParameters(new Object[] { tag }); addServerRoute(info); } public void <API key>(Enum tag, String route) { RouteInfo info = new RouteInfo(); info.setPath(route); info.setType(RouteType.Http); info.setOtherParameters(new Object[] { tag }); info.setFastRoute(true); addServerRoute(info); } public void removeStoragePathIf(Predicate<Enum> predicate) { storagePaths.entrySet().removeIf(e -> predicate.test(e.getKey())); } }
#include <linux/kprobes.h> #include <linux/kernel.h> #include <linux/kdebug.h> #include <linux/mutex.h> #include <linux/bitmap.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/perf_event.h> #include <linux/atomic.h> #include <asm/traps.h> #include <asm/stack.h> #include <asm/pmc.h> #include <hv/hypervisor.h> #define TILE_MAX_COUNTERS 4 #define PERF_COUNT_0_IDX 0 #define PERF_COUNT_1_IDX 1 #define <API key> 2 #define <API key> 3 struct cpu_hw_events { int n_events; struct perf_event *events[TILE_MAX_COUNTERS]; /* counter order */ struct perf_event *event_list[TILE_MAX_COUNTERS]; /* enabled order */ int assign[TILE_MAX_COUNTERS]; unsigned long active_mask[BITS_TO_LONGS(TILE_MAX_COUNTERS)]; unsigned long used_mask; }; /* TILE arch specific performance monitor unit */ struct tile_pmu { const char *name; int version; const int *hw_events; /* generic hw events table */ /* generic hw cache events table */ const int (*cache_events)[<API key>] [<API key>] [<API key>]; int (*map_hw_event)(u64); /*method used to map hw events */ int (*map_cache_event)(u64); /*method used to map cache events */ u64 max_period; /* max sampling period */ u64 cntval_mask; /* counter width mask */ int cntval_bits; /* counter width */ int max_events; /* max generic hw events in map */ int num_counters; /* number base + aux counters */ int num_base_counters; /* number base counters */ }; DEFINE_PER_CPU(u64, perf_irqs); static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events); #define TILE_OP_UNSUPP (-1) #ifndef __tilegx__ /* TILEPro hardware events map */ static const int tile_hw_event_map[] = { [<API key>] = 0x01, /* ONE */ [<API key>] = 0x06, /* MP_BUNDLE_RETIRED */ [<API key>] = TILE_OP_UNSUPP, [<API key>] = TILE_OP_UNSUPP, [<API key>] = 0x16, /* <API key> */ [<API key>] = 0x14, /* <API key> */ [<API key>] = TILE_OP_UNSUPP, }; #else /* TILEGx hardware events map */ static const int tile_hw_event_map[] = { [<API key>] = 0x181, /* ONE */ [<API key>] = 0xdb, /* INSTRUCTION_BUNDLE */ [<API key>] = TILE_OP_UNSUPP, [<API key>] = TILE_OP_UNSUPP, [<API key>] = 0xd9, /* <API key> */ [<API key>] = 0xda, /* <API key> */ [<API key>] = TILE_OP_UNSUPP, }; #endif #define C(x) <API key> /* * Generalized hw caching related hw_event table, filled * in on a per model basis. A value of -1 means * 'not supported', any other value means the * raw hw_event ID. */ #ifndef __tilegx__ /* TILEPro hardware cache event map */ static const int <API key>[<API key>] [<API key>] [<API key>] = { [C(L1D)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x21, /* RD_MISS */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x22, /* WR_MISS */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x12, /* <API key> */ [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x1d, /* TLB_CNT */ [C(RESULT_MISS)] = 0x20, /* TLB_EXCEPTION */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x13, /* MP_ITLB_HIT_ISSUED */ [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, }; #else /* TILEGx hardware events map */ static const int <API key>[<API key>] [<API key>] [<API key>] = { [C(L1D)] = { /* * Like some other architectures (e.g. ARM), the performance * counters don't differentiate between read and write * accesses/misses, so this isn't strictly correct, but it's the * best we can do. Writes and reads get combined. */ [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x44, /* RD_MISS */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0x45, /* WR_MISS */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(DTLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = 0x40, /* TLB_CNT */ [C(RESULT_MISS)] = 0x43, /* TLB_EXCEPTION */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = 0x40, /* TLB_CNT */ [C(RESULT_MISS)] = 0x43, /* TLB_EXCEPTION */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0xd4, /* ITLB_MISS_INT */ }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = 0xd4, /* ITLB_MISS_INT */ }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = TILE_OP_UNSUPP, [C(RESULT_MISS)] = TILE_OP_UNSUPP, }, }, }; #endif static atomic_t tile_active_events; static DEFINE_MUTEX(<API key>); static int tile_map_hw_event(u64 config); static int <API key>(u64 config); static int tile_pmu_handle_irq(struct pt_regs *regs, int fault); /* * To avoid new_raw_count getting larger then pre_raw_count * in <API key>(), we limit the value of max_period to 2^31 - 1. */ static const struct tile_pmu tilepmu = { #ifndef __tilegx__ .name = "tilepro", #else .name = "tilegx", #endif .max_events = ARRAY_SIZE(tile_hw_event_map), .map_hw_event = tile_map_hw_event, .hw_events = tile_hw_event_map, .map_cache_event = <API key>, .cache_events = &<API key>, .cntval_bits = 32, .cntval_mask = (1ULL << 32) - 1, .max_period = (1ULL << 31) - 1, .num_counters = TILE_MAX_COUNTERS, .num_base_counters = TILE_BASE_COUNTERS, }; static const struct tile_pmu *tile_pmu __read_mostly; /* * Check whether perf event is enabled. */ int tile_perf_enabled(void) { return atomic_read(&tile_active_events) != 0; } /* * Read Performance Counters. */ static inline u64 read_counter(int idx) { u64 val = 0; /* __insn_mfspr() only takes an immediate argument */ switch (idx) { case PERF_COUNT_0_IDX: val = __insn_mfspr(SPR_PERF_COUNT_0); break; case PERF_COUNT_1_IDX: val = __insn_mfspr(SPR_PERF_COUNT_1); break; case <API key>: val = __insn_mfspr(<API key>); break; case <API key>: val = __insn_mfspr(<API key>); break; default: WARN_ON_ONCE(idx > <API key> || idx < PERF_COUNT_0_IDX); } return val; } /* * Write Performance Counters. */ static inline void write_counter(int idx, u64 value) { /* __insn_mtspr() only takes an immediate argument */ switch (idx) { case PERF_COUNT_0_IDX: __insn_mtspr(SPR_PERF_COUNT_0, value); break; case PERF_COUNT_1_IDX: __insn_mtspr(SPR_PERF_COUNT_1, value); break; case <API key>: __insn_mtspr(<API key>, value); break; case <API key>: __insn_mtspr(<API key>, value); break; default: WARN_ON_ONCE(idx > <API key> || idx < PERF_COUNT_0_IDX); } } /* * Enable performance event by setting * Performance Counter Control registers. */ static inline void <API key>(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; unsigned long cfg, mask; int shift, idx = hwc->idx; /* * prevent early activation from tile_pmu_start() in hw_perf_enable */ if (WARN_ON_ONCE(idx == -1)) { return; } if (idx < tile_pmu->num_base_counters) { cfg = __insn_mfspr(SPR_PERF_COUNT_CTL); } else { cfg = __insn_mfspr(<API key>); } switch (idx) { case PERF_COUNT_0_IDX: case <API key>: mask = TILE_EVENT_MASK; shift = 0; break; case PERF_COUNT_1_IDX: case <API key>: mask = TILE_EVENT_MASK << 16; shift = 16; break; default: WARN_ON_ONCE(idx < PERF_COUNT_0_IDX || idx > <API key>); return; } /* Clear mask bits to enable the event. */ cfg &= ~mask; cfg |= hwc->config << shift; if (idx < tile_pmu->num_base_counters) { __insn_mtspr(SPR_PERF_COUNT_CTL, cfg); } else { __insn_mtspr(<API key>, cfg); } } /* * Disable performance event by clearing * Performance Counter Control registers. */ static inline void <API key>(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; unsigned long cfg, mask; int idx = hwc->idx; if (idx == -1) { return; } if (idx < tile_pmu->num_base_counters) { cfg = __insn_mfspr(SPR_PERF_COUNT_CTL); } else { cfg = __insn_mfspr(<API key>); } switch (idx) { case PERF_COUNT_0_IDX: case <API key>: mask = TILE_PLM_MASK; break; case PERF_COUNT_1_IDX: case <API key>: mask = TILE_PLM_MASK << 16; break; default: WARN_ON_ONCE(idx < PERF_COUNT_0_IDX || idx > <API key>); return; } /* Set mask bits to disable the event. */ cfg |= mask; if (idx < tile_pmu->num_base_counters) { __insn_mtspr(SPR_PERF_COUNT_CTL, cfg); } else { __insn_mtspr(<API key>, cfg); } } /* * Propagate event elapsed time into the generic event. * Can only be executed on the CPU where the event is active. * Returns the delta events processed. */ static u64 <API key>(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int shift = 64 - tile_pmu->cntval_bits; u64 prev_raw_count, new_raw_count; u64 oldval; int idx = hwc->idx; u64 delta; /* * Careful: an NMI might modify the previous event value. * * Our tactic to handle this is to first atomically read and * exchange a new raw count - then add that new-prev delta * count to the generic event atomically: */ again: prev_raw_count = local64_read(&hwc->prev_count); new_raw_count = read_counter(idx); oldval = local64_cmpxchg(&hwc->prev_count, prev_raw_count, new_raw_count); if (oldval != prev_raw_count) { goto again; } /* * Now we have the new raw value and have updated the prev * timestamp already. We can now calculate the elapsed delta * (event-)time and add that to the generic event. * * Careful, not all hw sign-extends above the physical width * of the count. */ delta = (new_raw_count << shift) - (prev_raw_count << shift); delta >>= shift; local64_add(delta, &event->count); local64_sub(delta, &hwc->period_left); return new_raw_count; } /* * Set the next IRQ period, based on the hwc->period_left value. * To be called with the event disabled in hw: */ static int <API key>(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; s64 left = local64_read(&hwc->period_left); s64 period = hwc->sample_period; int ret = 0; /* * If we are way outside a reasonable range then just skip forward: */ if (unlikely(left <= -period)) { left = period; local64_set(&hwc->period_left, left); hwc->last_period = period; ret = 1; } if (unlikely(left <= 0)) { left += period; local64_set(&hwc->period_left, left); hwc->last_period = period; ret = 1; } if (left > tile_pmu->max_period) { left = tile_pmu->max_period; } /* * The hw event starts counting from this event offset, * mark it to be able to extra future deltas: */ local64_set(&hwc->prev_count, (u64) - left); write_counter(idx, (u64)(-left) & tile_pmu->cntval_mask); <API key>(event); return ret; } /* * Stop the event but do not release the PMU counter */ static void tile_pmu_stop(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc = &event->hw; int idx = hwc->idx; if (<API key>(idx, cpuc->active_mask)) { <API key>(event); cpuc->events[hwc->idx] = NULL; WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED); hwc->state |= PERF_HES_STOPPED; } if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) { /* * Drain the remaining delta count out of a event * that we are disabling: */ <API key>(event); hwc->state |= PERF_HES_UPTODATE; } } /* * Start an event (without re-assigning counter) */ static void tile_pmu_start(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int idx = event->hw.idx; if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED))) { return; } if (WARN_ON_ONCE(idx == -1)) { return; } if (flags & PERF_EF_RELOAD) { WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE)); <API key>(event); } event->hw.state = 0; cpuc->events[idx] = event; __set_bit(idx, cpuc->active_mask); <API key>(); <API key>(event); <API key>(event); } /* * Add a single event to the PMU. * * The event is added to the group of enabled events * but only if it can be scehduled with existing events. */ static int tile_pmu_add(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct hw_perf_event *hwc; unsigned long mask; int b, max_cnt; hwc = &event->hw; /* * We are full. */ if (cpuc->n_events == tile_pmu->num_counters) { return -ENOSPC; } cpuc->event_list[cpuc->n_events] = event; cpuc->n_events++; hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED; if (!(flags & PERF_EF_START)) { hwc->state |= PERF_HES_ARCH; } /* * Find first empty counter. */ max_cnt = tile_pmu->num_counters; mask = ~cpuc->used_mask; /* Find next free counter. */ b = find_next_bit(&mask, max_cnt, 0); /* Should not happen. */ if (WARN_ON_ONCE(b == max_cnt)) { return -ENOSPC; } /* * Assign counter to event. */ event->hw.idx = b; __set_bit(b, &cpuc->used_mask); /* * Start if requested. */ if (flags & PERF_EF_START) { tile_pmu_start(event, PERF_EF_RELOAD); } return 0; } /* * Delete a single event from the PMU. * * The event is deleted from the group of enabled events. * If it is the last event, disable PMU interrupt. */ static void tile_pmu_del(struct perf_event *event, int flags) { struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); int i; /* * Remove event from list, compact list if necessary. */ for (i = 0; i < cpuc->n_events; i++) { if (cpuc->event_list[i] == event) { while (++i < cpuc->n_events) { cpuc->event_list[i - 1] = cpuc->event_list[i]; } --cpuc->n_events; cpuc->events[event->hw.idx] = NULL; __clear_bit(event->hw.idx, &cpuc->used_mask); tile_pmu_stop(event, PERF_EF_UPDATE); break; } } /* * If there are no events left, then mask PMU interrupt. */ if (cpuc->n_events == 0) { mask_pmc_interrupts(); } <API key>(event); } /* * Propagate event elapsed time into the event. */ static inline void tile_pmu_read(struct perf_event *event) { <API key>(event); } /* * Map generic events to Tile PMU. */ static int tile_map_hw_event(u64 config) { if (config >= tile_pmu->max_events) { return -EINVAL; } return tile_pmu->hw_events[config]; } /* * Map generic hardware cache events to Tile PMU. */ static int <API key>(u64 config) { unsigned int cache_type, cache_op, cache_result; int code; if (!tile_pmu->cache_events) { return -ENOENT; } cache_type = (config >> 0) & 0xff; if (cache_type >= <API key>) { return -EINVAL; } cache_op = (config >> 8) & 0xff; if (cache_op >= <API key>) { return -EINVAL; } cache_result = (config >> 16) & 0xff; if (cache_result >= <API key>) { return -EINVAL; } code = (*tile_pmu->cache_events)[cache_type][cache_op][cache_result]; if (code == TILE_OP_UNSUPP) { return -EINVAL; } return code; } static void tile_event_destroy(struct perf_event *event) { if (atomic_dec_return(&tile_active_events) == 0) { <API key>(); } } static int __tile_event_init(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; struct hw_perf_event *hwc = &event->hw; int code; switch (attr->type) { case PERF_TYPE_HARDWARE: code = tile_pmu->map_hw_event(attr->config); break; case PERF_TYPE_HW_CACHE: code = tile_pmu->map_cache_event(attr->config); break; case PERF_TYPE_RAW: code = attr->config & TILE_EVENT_MASK; break; default: /* Should not happen. */ return -EOPNOTSUPP; } if (code < 0) { return code; } hwc->config = code; hwc->idx = -1; if (attr->exclude_user) { hwc->config |= TILE_CTL_EXCL_USER; } if (attr->exclude_kernel) { hwc->config |= <API key>; } if (attr->exclude_hv) { hwc->config |= TILE_CTL_EXCL_HV; } if (!hwc->sample_period) { hwc->sample_period = tile_pmu->max_period; hwc->last_period = hwc->sample_period; local64_set(&hwc->period_left, hwc->sample_period); } event->destroy = tile_event_destroy; return 0; } static int tile_event_init(struct perf_event *event) { int err = 0; perf_irq_t old_irq_handler = NULL; if (atomic_inc_return(&tile_active_events) == 1) { old_irq_handler = <API key>(tile_pmu_handle_irq); } if (old_irq_handler) { pr_warn("PMC hardware busy (reserved by oprofile)\n"); atomic_dec(&tile_active_events); return -EBUSY; } switch (event->attr.type) { case PERF_TYPE_RAW: case PERF_TYPE_HARDWARE: case PERF_TYPE_HW_CACHE: break; default: return -ENOENT; } err = __tile_event_init(event); if (err) { if (event->destroy) { event->destroy(event); } } return err; } static struct pmu tilera_pmu = { .event_init = tile_event_init, .add = tile_pmu_add, .del = tile_pmu_del, .start = tile_pmu_start, .stop = tile_pmu_stop, .read = tile_pmu_read, }; /* * PMU's IRQ handler, PMU has 2 interrupts, they share the same handler. */ int tile_pmu_handle_irq(struct pt_regs *regs, int fault) { struct perf_sample_data data; struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events); struct perf_event *event; struct hw_perf_event *hwc; u64 val; unsigned long status; int bit; __this_cpu_inc(perf_irqs); if (!atomic_read(&tile_active_events)) { return 0; } status = pmc_get_overflow(); pmc_ack_overflow(status); for_each_set_bit(bit, &status, tile_pmu->num_counters) { event = cpuc->events[bit]; if (!event) { continue; } if (!test_bit(bit, cpuc->active_mask)) { continue; } hwc = &event->hw; val = <API key>(event); if (val & (1ULL << (tile_pmu->cntval_bits - 1))) { continue; } <API key>(&data, 0, event->hw.last_period); if (!<API key>(event)) { continue; } if (perf_event_overflow(event, &data, regs)) { tile_pmu_stop(event, 0); } } return 0; } static bool __init supported_pmu(void) { tile_pmu = &tilepmu; return true; } int __init init_hw_perf_events(void) { supported_pmu(); perf_pmu_register(&tilera_pmu, "cpu", PERF_TYPE_RAW); return 0; } arch_initcall(init_hw_perf_events); /* Callchain handling code. */ /* * Tile specific backtracing code for perf_events. */ static inline void perf_callchain(struct <API key> *entry, struct pt_regs *regs) { struct KBacktraceIterator kbt; unsigned int i; /* * Get the address just after the "jalr" instruction that * jumps to the handler for a syscall. When we find this * address in a backtrace, we silently ignore it, which gives * us a one-step backtrace connection from the sys_xxx() * function in the kernel to the xxx() function in libc. * Otherwise, we lose the ability to properly attribute time * from the libc calls to the kernel implementations, since * oprofile only considers PCs from backtraces a pair at a time. */ unsigned long handle_syscall_pc = <API key>(); <API key>(&kbt, NULL, regs); kbt.profile = 1; /* * The sample for the pc is already recorded. Now we are adding the * address of the callsites on the stack. Our iterator starts * with the frame of the (already sampled) call site. If our * iterator contained a "return address" field, we could have just * used it and wouldn't have needed to skip the first * frame. That's in effect what the arm and x86 versions do. * Instead we peel off the first iteration to get the equivalent * behavior. */ if (<API key>(&kbt)) { return; } <API key>(&kbt); /* * Set stack depth to 16 for user and kernel space respectively, that * is, total 32 stack frames. */ for (i = 0; i < 16; ++i) { unsigned long pc; if (<API key>(&kbt)) { break; } pc = kbt.it.pc; if (pc != handle_syscall_pc) { <API key>(entry, pc); } <API key>(&kbt); } } void perf_callchain_user(struct <API key> *entry, struct pt_regs *regs) { perf_callchain(entry, regs); } void <API key>(struct <API key> *entry, struct pt_regs *regs) { perf_callchain(entry, regs); }
package com.limelight.binding.input.driver; public interface UsbDriverListener { void <API key>(int controllerId, short buttonFlags, float leftStickX, float leftStickY, float rightStickX, float rightStickY, float leftTrigger, float rightTrigger); void deviceRemoved(int controllerId); void deviceAdded(int controllerId); }
#ifndef __16_SPRI__ #define __16_SPRI__ //#include "src/lib/16_vrs.h" #include "src/lib/16_vl.h" //#include <hw/cpu/cpu.h> //#include <hw/dos/dos.h> #include <hw/vga/vrl.h> #include "src/lib/16_ca.h" #include "src/lib/scroll16.h" *//* /* struct vrs_container{ // Size of a .vrs lob in memory // minus header dword data_size; union{ byte far *buffer; struct vrs_header far *vrs_hdr; }; // Array of corresponding vrl line offsets vrl1_vgax_offset_t **vrl_line_offsets; }; struct vrl_container{ // Size of a .vrl blob in memory // minus header dword data_size; union{ byte far *buffer; struct vrl1_vgax_header far *vrl_header; }; // Pointer to a corresponding vrl line offsets struct vrl1_vgax_offset_t *line_offsets; }; */ /* Read .vrs file into memory * In: * + char *filename - name of the file to load * + struct vrs_container *vrs_cont - pointer to the vrs_container * to load the file into * Out: * + int - 0 on succes, 1 on failure */ void VRS_ReadVRS(char *filename, entity_t *enti, <API key> *gvar); void VRS_LoadVRS(char *filename, entity_t *enti, <API key> *gvar); void VRS_OpenVRS(char *filename, entity_t *enti, boolean rlsw, <API key> *gvar); void VRS_ReadVRL(char *filename, entity_t *enti, <API key> *gvar); void VRS_LoadVRL(char *filename, entity_t *enti, <API key> *gvar); void VRS_OpenVRL(char *filename, entity_t *enti, boolean rlsw, <API key> *gvar); /* Seek and return a specified .vrl blob from .vrs blob in memory * In: * + struct vrs_container *vrs_cont - pointer to the vrs_container * with a loaded .vrs file * + uint16_t id - id of the vrl to retrive * + struct vrl_container * vrl_cont - pointer to vrl_container to load to * Out: * int - operation status * to the requested .vrl blob */ int get_vrl_by_id(struct vrs_container far *vrs_cont, uint16_t id, struct vrl_container *vrl_cont); void DrawVRL (unsigned int x,unsigned int y,struct vrl1_vgax_header *hdr,vrl1_vgax_offset_t *lineoffs/*array hdr->width long*/,unsigned char *data,unsigned int datasz); //moved to 16_tdef.h // struct sprite // // VRS container from which we will extract animation and image data // struct vrs_container *spritesheet; // // Container for a vrl sprite // struct vrl_container *sprite_vrl_cont; // // Current sprite id // int curr_spri_id; // // Index of a current sprite in an animation sequence // int curr_anim_spri; // // Current animation sequence // struct <API key> *curr_anim_list; // // Index of current animation in relevant VRS offsets table // int curr_anim; // // Delay in time units untill we should change sprite // int delay; // // Position of sprite on screen // int x, y; /* Retrive current animation name of sprite * In: * + struct sprite *spri - sprite to retrive current animation sequence name from * Out: * + char* - animation sequence name */ char* get_curr_anim_name(struct sprite *spri); /* Change sprite's current animation to the one given by id * In: * struct sprite *spri - sprite to manipulate on * int id - id of a new animation sequence of th sprite * Out: * int - 0 on success, -1 on error */ int set_anim_by_id(struct sprite *spri, int anim_id); /* Animate sprite, triggering any events and changing indices if necessary * NB: if you want to change animation sequence after a specific sprite is shown, you should call animate_spri first * In: * + struct sprite *spri - sprite to animate */ void animate_spri(entity_t *enti, video_t *video); void print_anim_ids(struct sprite *spri); #endif
namespace DataStoreLib.Utils { using System; using System.Configuration; using System.Diagnostics; using System.Net; using System.Net.Mail; <summary> This class use to send mails </summary> public class MailManager { <summary> Send an email </summary> <param name="toAddress">mail message to-Address</param> <param name="fromAddress">mail message from-Address</param> <param name="subject">mail message subject</param> <param name="body">mail message body</param> public bool SendMail(string toAddress, string fromAddress, string subject, string body) { try { string user = <API key>.AppSettings["User"]; string <API key>.AppSettings["Password"]; string host = <API key>.AppSettings["Host"]; int port = Convert.ToInt32(<API key>.AppSettings["Port"]); bool enableSsl = Convert.ToBoolean(<API key>.AppSettings["EnableSsl"]); /bool <API key> = Convert.ToBoolean(<API key>.AppSettings["<API key>"]); MailMessage mailMessage = new MailMessage(); mailMessage.IsBodyHtml = true; if (string.IsNullOrWhiteSpace(fromAddress)) { mailMessage.From = new MailAddress(<API key>.AppSettings["fromAddress"]); // Key from the config file } else { mailMessage.From = new MailAddress(fromAddress); } mailMessage.To.Add(toAddress); // Key from the config file if (string.IsNullOrWhiteSpace(subject)) { mailMessage.Subject = <API key>.AppSettings["subject"]; // Key from the config file } else { mailMessage.Subject = subject; } mailMessage.Body = body; SmtpClient smtpServer = new SmtpClient(host); // Key the mail server smtpServer.Port = port; smtpServer.Credentials = new NetworkCredential(<API key>.AppSettings["fromAddress"], <API key>.AppSettings["Password"]); smtpServer.EnableSsl = enableSsl; smtpServer.Send(mailMessage); } catch (Exception ex) { Trace.TraceWarning("Sending mail failed: {0}", ex); return false; } return true; } } }
using Terraria; using Terraria.ID; using Terraria.ModLoader; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace TutorialMod.Tiles { public class TutorialBiomeTile : ModTile { public override void SetDefaults() { Main.tileSolid[Type] = true; // Is the tile solid AddMapEntry(new Color(255, 255, 0)); drop = mod.ItemType("TutorialBiomeBlock"); // What item drops after destorying the tile } } }
// Decompiler options: packimports(3) braces deadcode fieldsfirst package net.minecraft.src; import java.util.List; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; // Referenced classes of package net.minecraft.src: // GuiScreen, AchievementList, Achievement, GuiSmallButton, // StatCollector, GuiButton, GameSettings, KeyBinding, // FontRenderer, MathHelper, RenderEngine, Block, // StatFileWriter, RenderItem, RenderHelper public class GuiAchievements extends GuiScreen { private static final int field_27126_s; private static final int field_27125_t; private static final int field_27124_u; private static final int field_27123_v; protected int field_27121_a; protected int field_27119_i; protected int field_27118_j; protected int field_27117_l; protected double field_27116_m; protected double field_27115_n; protected double field_27114_o; protected double field_27113_p; protected double field_27112_q; protected double field_27111_r; private int field_27122_w; private StatFileWriter field_27120_x; public GuiAchievements(StatFileWriter p_i575_1_) { field_27121_a = 256; field_27119_i = 202; field_27118_j = 0; field_27117_l = 0; field_27122_w = 0; field_27120_x = p_i575_1_; char c = '\215'; char c1 = '\215'; field_27116_m = field_27114_o = field_27112_q = AchievementList.field_25195_b.field_25075_a * 24 - c / 2 - 12; field_27115_n = field_27113_p = field_27111_r = AchievementList.field_25195_b.field_25074_b * 24 - c1 / 2; } public void func_6448_a() { field_949_e.clear(); field_949_e.add(new GuiSmallButton(1, field_951_c / 2 + 24, field_950_d / 2 + 74, 80, 20, StatCollector.func_25200_a("gui.done"))); } protected void func_572_a(GuiButton p_572_1_) { if(p_572_1_.field_938_f == 1) { field_945_b.func_6272_a(null); field_945_b.func_6259_e(); } super.func_572_a(p_572_1_); } protected void func_580_a(char p_580_1_, int p_580_2_) { if(p_580_2_ == field_945_b.field_6304_y.field_1570_o.field_1370_b) { field_945_b.func_6272_a(null); field_945_b.func_6259_e(); } else { super.func_580_a(p_580_1_, p_580_2_); } } public void func_571_a(int p_571_1_, int p_571_2_, float p_571_3_) { if(Mouse.isButtonDown(0)) { int i = (field_951_c - field_27121_a) / 2; int j = (field_950_d - field_27119_i) / 2; int k = i + 8; int l = j + 17; if((field_27122_w == 0 || field_27122_w == 1) && p_571_1_ >= k && p_571_1_ < k + 224 && p_571_2_ >= l && p_571_2_ < l + 155) { if(field_27122_w == 0) { field_27122_w = 1; } else { field_27114_o -= p_571_1_ - field_27118_j; field_27113_p -= p_571_2_ - field_27117_l; field_27112_q = field_27116_m = field_27114_o; field_27111_r = field_27115_n = field_27113_p; } field_27118_j = p_571_1_; field_27117_l = p_571_2_; } if(field_27112_q < (double)field_27126_s) { field_27112_q = field_27126_s; } if(field_27111_r < (double)field_27125_t) { field_27111_r = field_27125_t; } if(field_27112_q >= (double)field_27124_u) { field_27112_q = field_27124_u - 1; } if(field_27111_r >= (double)field_27123_v) { field_27111_r = field_27123_v - 1; } } else { field_27122_w = 0; } func_578_i(); func_27109_b(p_571_1_, p_571_2_, p_571_3_); GL11.glDisable(2896); GL11.glDisable(2929); func_27110_k(); GL11.glEnable(2896); GL11.glEnable(2929); } public void func_570_g() { field_27116_m = field_27114_o; field_27115_n = field_27113_p; double d = field_27112_q - field_27114_o; double d1 = field_27111_r - field_27113_p; if(d * d + d1 * d1 < 4D) { field_27114_o += d; field_27113_p += d1; } else { field_27114_o += d * 0.84999999999999998D; field_27113_p += d1 * 0.84999999999999998D; } } protected void func_27110_k() { int i = (field_951_c - field_27121_a) / 2; int j = (field_950_d - field_27119_i) / 2; field_6451_g.func_873_b("Achievements", i + 15, j + 5, 0x404040); } protected void func_27109_b(int p_27109_1_, int p_27109_2_, float p_27109_3_) { int i = MathHelper.func_1108_b(field_27116_m + (field_27114_o - field_27116_m) * (double)p_27109_3_); int j = MathHelper.func_1108_b(field_27115_n + (field_27113_p - field_27115_n) * (double)p_27109_3_); if(i < field_27126_s) { i = field_27126_s; } if(j < field_27125_t) { j = field_27125_t; } if(i >= field_27124_u) { i = field_27124_u - 1; } if(j >= field_27123_v) { j = field_27123_v - 1; } int k = field_945_b.field_6315_n.func_1070_a("/terrain.png"); int l = field_945_b.field_6315_n.func_1070_a("/achievement/bg.png"); int i1 = (field_951_c - field_27121_a) / 2; int j1 = (field_950_d - field_27119_i) / 2; int k1 = i1 + 16; int l1 = j1 + 17; field_923_k = 0.0F; GL11.glDepthFunc(518); GL11.glPushMatrix(); GL11.glTranslatef(0.0F, 0.0F, -200F); GL11.glEnable(3553); GL11.glDisable(2896); GL11.glEnable(32826); GL11.glEnable(2903); field_945_b.field_6315_n.func_1076_b(k); int i2 = i + 288 >> 4; int j2 = j + 288 >> 4; int k2 = (i + 288) % 16; int l2 = (j + 288) % 16; Random random = new Random(); for(int i3 = 0; i3 * 16 - l2 < 155; i3++) { float f = 0.6F - ((float)(j2 + i3) / 25F) * 0.3F; GL11.glColor4f(f, f, f, 1.0F); for(int k3 = 0; k3 * 16 - k2 < 224; k3++) { random.setSeed(1234 + i2 + k3); random.nextInt(); int j4 = random.nextInt(1 + j2 + i3) + (j2 + i3) / 2; int l4 = Block.field_393_F.field_378_bb; if(j4 > 37 || j2 + i3 == 35) { l4 = Block.field_403_A.field_378_bb; } else if(j4 == 22) { if(random.nextInt(2) == 0) { l4 = Block.field_391_ax.field_378_bb; } else { l4 = Block.field_433_aO.field_378_bb; } } else if(j4 == 10) { l4 = Block.field_388_I.field_378_bb; } else if(j4 == 8) { l4 = Block.field_386_J.field_378_bb; } else if(j4 > 4) { l4 = Block.field_338_u.field_378_bb; } else if(j4 > 0) { l4 = Block.field_336_w.field_378_bb; } func_550_b((k1 + k3 * 16) - k2, (l1 + i3 * 16) - l2, l4 % 16 << 4, (l4 >> 4) << 4, 16, 16); } } GL11.glEnable(2929); GL11.glDepthFunc(515); GL11.glDisable(3553); for(int j3 = 0; j3 < AchievementList.field_27388_e.size(); j3++) { Achievement achievement1 = (Achievement)AchievementList.field_27388_e.get(j3); if(achievement1.field_25076_c == null) { continue; } int l3 = (achievement1.field_25075_a * 24 - i) + 11 + k1; int k4 = (achievement1.field_25074_b * 24 - j) + 11 + l1; int i5 = (achievement1.field_25076_c.field_25075_a * 24 - i) + 11 + k1; int l5 = (achievement1.field_25076_c.field_25074_b * 24 - j) + 11 + l1; boolean flag = field_27120_x.func_27183_a(achievement1); boolean flag1 = field_27120_x.func_27181_b(achievement1); char c = Math.sin(((double)(System.currentTimeMillis() % 600L) / 600D) * 3.1415926535897931D * 2D) <= 0.59999999999999998D ? '\202' : '\377'; int i8 = 0xff000000; if(flag) { i8 = 0xff707070; } else if(flag1) { i8 = 65280 + (c << 24); } func_27100_a(l3, i5, k4, i8); func_27099_b(i5, k4, l5, i8); } Achievement achievement = null; RenderItem renderitem = new RenderItem(); RenderHelper.func_41089_c(); GL11.glDisable(2896); GL11.glEnable(32826); GL11.glEnable(2903); for(int i4 = 0; i4 < AchievementList.field_27388_e.size(); i4++) { Achievement achievement2 = (Achievement)AchievementList.field_27388_e.get(i4); int j5 = achievement2.field_25075_a * 24 - i; int i6 = achievement2.field_25074_b * 24 - j; if(j5 < -24 || i6 < -24 || j5 > 224 || i6 > 155) { continue; } if(field_27120_x.func_27183_a(achievement2)) { float f1 = 1.0F; GL11.glColor4f(f1, f1, f1, 1.0F); } else if(field_27120_x.func_27181_b(achievement2)) { float f2 = Math.sin(((double)(System.currentTimeMillis() % 600L) / 600D) * 3.1415926535897931D * 2D) >= 0.59999999999999998D ? 0.8F : 0.6F; GL11.glColor4f(f2, f2, f2, 1.0F); } else { float f3 = 0.3F; GL11.glColor4f(f3, f3, f3, 1.0F); } field_945_b.field_6315_n.func_1076_b(l); int k6 = k1 + j5; int j7 = l1 + i6; if(achievement2.func_27093_f()) { func_550_b(k6 - 2, j7 - 2, 26, 202, 26, 26); } else { func_550_b(k6 - 2, j7 - 2, 0, 202, 26, 26); } if(!field_27120_x.func_27181_b(achievement2)) { float f4 = 0.1F; GL11.glColor4f(f4, f4, f4, 1.0F); renderitem.field_27004_a = false; } GL11.glEnable(2896); GL11.glEnable(2884); renderitem.func_161_a(field_945_b.field_6314_o, field_945_b.field_6315_n, achievement2.field_27097_d, k6 + 3, j7 + 3); GL11.glDisable(2896); if(!field_27120_x.func_27181_b(achievement2)) { renderitem.field_27004_a = true; } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); if(p_27109_1_ >= k1 && p_27109_2_ >= l1 && p_27109_1_ < k1 + 224 && p_27109_2_ < l1 + 155 && p_27109_1_ >= k6 && p_27109_1_ <= k6 + 22 && p_27109_2_ >= j7 && p_27109_2_ <= j7 + 22) { achievement = achievement2; } } GL11.glDisable(2929); GL11.glEnable(3042); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); field_945_b.field_6315_n.func_1076_b(l); func_550_b(i1, j1, 0, 0, field_27121_a, field_27119_i); GL11.glPopMatrix(); field_923_k = 0.0F; GL11.glDepthFunc(515); GL11.glDisable(2929); GL11.glEnable(3553); super.func_571_a(p_27109_1_, p_27109_2_, p_27109_3_); if(achievement != null) { String s = StatCollector.func_25200_a(achievement.func_44020_i()); String s1 = achievement.func_27090_e(); int k5 = p_27109_1_ + 12; int j6 = p_27109_2_ - 4; if(field_27120_x.func_27181_b(achievement)) { int l6 = Math.max(field_6451_g.func_871_a(s), 120); int k7 = field_6451_g.func_27277_a(s1, l6); if(field_27120_x.func_27183_a(achievement)) { k7 += 12; } func_549_a(k5 - 3, j6 - 3, k5 + l6 + 3, j6 + k7 + 3 + 12, 0xc0000000, 0xc0000000); field_6451_g.func_27278_a(s1, k5, j6 + 12, l6, 0xffa0a0a0); if(field_27120_x.func_27183_a(achievement)) { field_6451_g.func_50103_a(StatCollector.func_25200_a("achievement.taken"), k5, j6 + k7 + 4, 0xff9090ff); } } else { int i7 = Math.max(field_6451_g.func_871_a(s), 120); String s2 = StatCollector.func_25199_a("achievement.requires", new Object[] { StatCollector.func_25200_a(achievement.field_25076_c.func_44020_i()) }); int l7 = field_6451_g.func_27277_a(s2, i7); func_549_a(k5 - 3, j6 - 3, k5 + i7 + 3, j6 + l7 + 12 + 3, 0xc0000000, 0xc0000000); field_6451_g.func_27278_a(s2, k5, j6 + 12, i7, 0xff705050); } field_6451_g.func_50103_a(s, k5, j6, field_27120_x.func_27181_b(achievement) ? achievement.func_27093_f() ? -128 : -1 : achievement.func_27093_f() ? 0xff808040 : 0xff808080); } GL11.glEnable(2929); GL11.glEnable(2896); RenderHelper.func_1159_a(); } public boolean func_6450_b() { return true; } static { field_27126_s = AchievementList.field_27392_a * 24 - 112; field_27125_t = AchievementList.field_27391_b * 24 - 112; field_27124_u = AchievementList.field_27390_c * 24 - 77; field_27123_v = AchievementList.field_27389_d * 24 - 77; } }
package org.amahi.anywhere; import android.app.Application; import android.content.Context; import org.amahi.anywhere.activity.<API key>; import org.amahi.anywhere.activity.NavigationActivity; import org.amahi.anywhere.activity.ServerAppActivity; import org.amahi.anywhere.activity.<API key>; import org.amahi.anywhere.activity.<API key>; import org.amahi.anywhere.activity.<API key>; import org.amahi.anywhere.activity.<API key>; import org.amahi.anywhere.activity.ServerFilesActivity; import org.amahi.anywhere.fragment.<API key>; import org.amahi.anywhere.fragment.NavigationFragment; import org.amahi.anywhere.fragment.ServerAppsFragment; import org.amahi.anywhere.fragment.<API key>; import org.amahi.anywhere.fragment.ServerFilesFragment; import org.amahi.anywhere.fragment.<API key>; import org.amahi.anywhere.fragment.SettingsFragment; import org.amahi.anywhere.server.ApiModule; import org.amahi.anywhere.service.AudioService; import org.amahi.anywhere.service.VideoService; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * Application dependency injection module. Includes {@link org.amahi.anywhere.server.ApiModule} and * provides application's {@link android.content.Context} for possible consumers. */ @Module( includes = { ApiModule.class }, injects = { <API key>.class, NavigationActivity.class, ServerAppActivity.class, ServerFilesActivity.class, <API key>.class, <API key>.class, <API key>.class, <API key>.class, NavigationFragment.class, <API key>.class, ServerAppsFragment.class, ServerFilesFragment.class, <API key>.class, <API key>.class, SettingsFragment.class, AudioService.class, VideoService.class } ) class AmahiModule { private final Application application; public AmahiModule(Application application) { this.application = application; } @Provides @Singleton Context provideContext() { return application; } }
package adams.flow.transformer.exiftagoperation; /** * Interface for EXIF tag write operations. * * @author FracPete (fracpete at waikato dot ac dot nz) */ public interface <API key><I, O> extends ExifTagOperation<I, O> { }
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <link href="/Public/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div> <a href="javascript:history.go(-1);" class="btn btn-warning btn-sm pull-right"></a> </div> <div class="clearfix"></div> <h3 class="text-center"></h3> <div class="col-md-4 col-md-offset-4"> <form action="{$smarty.const.__SELF__}" method="post" class="form-horizontal"> <div class="form-group"> <label for="role_name" class="col-md-4 control-label">:</label> <div class="col-md-8"> <input type="text" class="form-control" name="role_name" id="role_name" autofocus> </div> </div> <div class="form-group"> <div class="col-md-8 col-md-offset-4"> <input type="submit" value="" class="btn btn-success btn-sm"> </div> </div> </form> </div> <script id="jqLabel" src="/Public/js/jquery.min.js"></script> <script> if (!window.jQuery) { var jq = document.createElement('script'); jq.src = "https://code.jquery.com/jquery-3.2.1.min.js"; document.body.replaceChild(jq, document.getElementById('jqLabel')); } else { /* do nothing */ } </script> <script src="/Public/bootstrap-3.3.7/js/bootstrap.min.js"></script> </body> </html>
<?php /** * Project form base class. * * @package fynance * @subpackage form * @author Your name here */ abstract class BaseFormPropel extends sfFormPropel { public function setup() { } }
#ifndef qhDEFmerge #define qhDEFmerge 1 #define qh_ANGLEredundant 6.0 #define qh_ANGLEdegen 5.0 #define qh_ANGLEconcave 1.5 typedef enum { /* in sort order for facet_mergeset */ MRGnone= 0, MRGcoplanar, /* centrum coplanar */ MRGanglecoplanar, /* angle coplanar */ /* could detect half concave ridges */ MRGconcave, /* concave ridge */ MRGflip, /* flipped facet. facet1 == facet2 */ MRGridge, /* duplicate ridge (qh_MERGEridge) */ /* degen and redundant go onto degen_mergeset */ MRGdegen, /* degenerate facet (not enough neighbors) facet1 == facet2 */ MRGredundant, /* redundant facet (vertex subset) */ /* <API key> assumes degen < redundant */ MRGmirror, /* mirror facet from qh_triangulate */ ENDmrg } mergeType; #define qh_MERGEapex True typedef struct mergeT mergeT; struct mergeT { /* initialize in qh_appendmergeset */ realT angle; /* angle between normals of facet1 and facet2 */ facetT *facet1; /* will merge facet1 into facet2 */ facetT *facet2; mergeType type; }; #define FOREACHmerge_( merges ) FOREACHsetelement_(mergeT, merges, merge) void qh_premerge (vertexT *apex, realT maxcentrum, realT maxangle); void qh_postmerge (const char *reason, realT maxcentrum, realT maxangle, boolT vneighbors); void qh_all_merges (boolT othermerge, boolT vneighbors); void qh_appendmergeset(facetT *facet, facetT *neighbor, mergeType mergetype, realT *angle); setT *qh_basevertices( facetT *samecycle); void qh_checkconnect (void /* qh new_facets */); boolT qh_checkzero (boolT testall); int qh_compareangle(const void *p1, const void *p2); int qh_comparemerge(const void *p1, const void *p2); int qh_comparevisit (const void *p1, const void *p2); void qh_copynonconvex (ridgeT *atridge); void <API key> (facetT *facet); void <API key> (facetT *facet, facetT *delfacet); vertexT *qh_find_newvertex (vertexT *oldvertex, setT *vertices, setT *ridges); void qh_findbest_test (boolT testcentrum, facetT *facet, facetT *neighbor, facetT **bestfacet, realT *distp, realT *mindistp, realT *maxdistp); facetT *qh_findbestneighbor(facetT *facet, realT *distp, realT *mindistp, realT *maxdistp); void qh_flippedmerges(facetT *facetlist, boolT *wasmerge); void qh_forcedmerges( boolT *wasmerge); void qh_getmergeset(facetT *facetlist); void <API key> (facetT *facetlist); void qh_hashridge (setT *hashtable, int hashsize, ridgeT *ridge, vertexT *oldvertex); ridgeT *qh_hashridge_find (setT *hashtable, int hashsize, ridgeT *ridge, vertexT *vertex, vertexT *oldvertex, int *hashslot); void qh_makeridges(facetT *facet); void qh_mark_dupridges(facetT *facetlist); void qh_maydropneighbor (facetT *facet); int <API key> (void); void qh_merge_nonconvex( facetT *facet1, facetT *facet2, mergeType mergetype); void qh_mergecycle (facetT *samecycle, facetT *newfacet); void qh_mergecycle_all (facetT *facetlist, boolT *wasmerge); void <API key>( facetT *samecycle, facetT *newfacet); void <API key>(facetT *samecycle, facetT *newfacet); void <API key>(facetT *samecycle, facetT *newfacet); void <API key>( facetT *samecycle, facetT *newfacet); void qh_mergefacet(facetT *facet1, facetT *facet2, realT *mindist, realT *maxdist, boolT mergeapex); void qh_mergefacet2d (facetT *facet1, facetT *facet2); void qh_mergeneighbors(facetT *facet1, facetT *facet2); void qh_mergeridges(facetT *facet1, facetT *facet2); void qh_mergesimplex(facetT *facet1, facetT *facet2, boolT mergeapex); void qh_mergevertex_del (vertexT *vertex, facetT *facet1, facetT *facet2); void <API key>(facetT *facet1, facetT *facet2); void qh_mergevertices(setT *vertices1, setT **vertices); setT *<API key> (vertexT *vertex); void qh_newvertices (setT *vertices); boolT qh_reducevertices (void); vertexT *qh_redundant_vertex (vertexT *vertex); boolT <API key> (facetT *facet); vertexT *<API key> (vertexT *vertex, facetT *facet); void <API key>(ridgeT *ridge, vertexT *oldvertex, vertexT *newvertex); void qh_renamevertex(vertexT *oldvertex, vertexT *newvertex, setT *ridges, facetT *oldfacet, facetT *neighborA); boolT qh_test_appendmerge (facetT *facet, facetT *neighbor); boolT qh_test_vneighbors (void /* qh newfacet_list */); void qh_tracemerge (facetT *facet1, facetT *facet2); void qh_tracemerging (void); void qh_updatetested( facetT *facet1, facetT *facet2); setT *qh_vertexridges (vertexT *vertex); void <API key> (vertexT *vertex, facetT *facet, setT **ridges); void qh_willdelete (facetT *facet, facetT *replace); #endif /* qhDEFmerge */
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 5.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by the Perl program only. The format and even # the name or existence of this file are subject to change without notice. # Don't use it directly. # This file returns the 128 code points in Unicode Version 5.2.0 that match # any of the following regular expression constructs: # \p{Block=Kannada} # \p{Blk=Kannada} # \p{Is_Block=Kannada} # \p{Is_Blk=Kannada} # \p{In_Kannada} # Note that contrary to what you might expect, the above is NOT the same # as any of: \p{Kannada}, \p{Is_Kannada} # perluniprops.pod should be consulted for the syntax rules for any of these, # including if adding or subtracting white space, underscore, and hyphen # characters matters or doesn't matter, and other permissible syntactic # variants. Upper/lower case distinctions never matter. # A colon can be substituted for the equals sign, and anything to the left of # the equals (or colon) can be combined with anything to the right. Thus, # for example, # \p{Is_Blk: Kannada} # is also valid. # The format of the lines of this file is: START\tSTOP\twhere START is the # starting code point of the range, in hex; STOP is the ending point, or if # omitted, the range has just one code point. Numbers in comments in # [brackets] indicate how many code points are in the range. return <<'END'; 0C80 0CFF # [128] END
<?php class Sign_in_with_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function get_sign_with($name) { $this->db->select('setting, name'); $this->db->where('code', 'sign_in_with'); $this->db->where('name', $name); $this->db->from($this->db->dbprefix('module')); $query=$this->db->get(); if($query->num_rows() > 0){ $array=array(); $row =$query->row_array(); $setting =unserialize($row['setting']); $array['name'] =$row['name']; $array['id'] =$setting['appid']; $array['secret'] =$setting['appkey']; $array['extra'] =$setting['extra']; return $array; } return FALSE; } public function <API key>() { $this->db->select('*'); $this->db->where('user_id', $_SESSION['user_id']); $this->db->from($this->db->dbprefix('user_sign_in_with')); $query=$this->db->get(); if($query->num_rows() > 0){ return $query->result_array(); } return FALSE; } public function get_sign_withs(){ $this->db->select('setting, name'); $this->db->where('code', 'sign_in_with'); $this->db->order_by('store_order', 'ASC'); $this->db->from($this->db->dbprefix('module')); $query=$this->db->get(); if($query->num_rows() > 0){ $array=array(); $row=$query->result_array(); foreach($row as $key=>$value){ $array[$row[$key]['name']]['setting']=unserialize($row[$key]['setting']); if($array[$row[$key]['name']]['setting']['status'] == '0'){ unset($array[$row[$key]['name']]); } } return $array; } return FALSE; } public function select_user_for_vid($via, $uid){ $this->db->select('user_id'); $this->db->where('via', $via); $this->db->where('uid', $uid); $this->db->from($this->db->dbprefix('user_sign_in_with')); $query=$this->db->get(); if($query->num_rows() > 0){ return $query->row_array()['user_id']; } return FALSE; } public function <API key>($data){ $this->db->insert($this->db->dbprefix('user'), $data['adduser']); $data['addsgin']['user_id']=$this->db->insert_id(); $_SESSION['user_id']=$data['addsgin']['user_id']; $this->db->insert($this->db->dbprefix('user_sign_in_with'), $data['addsgin']); $this->load->model('common/user_activity_model'); $this->user_activity_model->add_activity($data['addsgin']['user_id'], 'register', array('title'=>sprintf(lang_line('success_bind_login'), $data['adduser']['nickname']), 'msg'=>'')); } public function add_bind_accounts($data){ $data['addsgin']['user_id']=$_SESSION['user_id']; $this->db->insert($this->db->dbprefix('user_sign_in_with'), $data['addsgin']); $this->load->model('common/user_activity_model'); $this->user_activity_model->add_activity($data['addsgin']['user_id'], 'bind', array('title'=>sprintf(lang_line('success_bind'), $data['adduser']['nickname']), 'msg'=>'')); } public function unbundling($via, $nickname){ $this->db->where('via', $via); $this->db->where('user_id', $_SESSION['user_id']); $this->db->delete($this->db->dbprefix('user_sign_in_with')); } }
<?php namespace MCPETRADE\MultiTradeAPI\Commands; use pocketmine\Player; use pocketmine\command\CommandSender; use pocketmine\utils\TextFormat as TE; use MCPETRADE\MultiTradeAPI\MTAPI; use MCPETRADE\MultiTradeAPI\Commands\BaseCommand; Class FlyCommand extends BaseCommand { public function __construct(MTAPI $plugin) { parent::__construct($plugin, "fly", "Включить\выключить режим полёта"); $this->getPlugin()->getLogger()->notice(TE::LIGHT_PURPLE . "Fly загружен."); $this->setPermission("trade.commands.fly"); } public function execute(CommandSender $sender, $command, array $args) { if(!($sender instanceof Player)) return; if(!$this->testPermission($sender)) return; if($sender->getAllowFlight(true)){ $sender->setAllowFlight(false); $sender->sendMessage($this->getPlugin()->getPrefix() . "§f Вы§b успешно §cотключили §fрежим полёта!"); }else{ $sender->setAllowFlight(true);$sender->sendMessage($this->getPlugin()->getPrefix() . "§f Вы§b успешно §aвключили §fрежим полёта!"); } } } ?>
package bpmn; public class DataStore extends Artifact { public DataStore() { super(); } public DataStore(int xPos, int yPos, String text) { super(); setText(text); } public String toString() { return "BPMN data store"; } }
<?php class Affiliate { private $affiliate_id; private $firstname; private $lastname; private $email; private $telephone; private $fax; private $code; public function __construct($registry) { $this->config = $registry->get('config'); $this->db = $registry->get('db'); $this->request = $registry->get('request'); $this->session = $registry->get('session'); if (isset($this->session->data['affiliate_id'])) { $affiliate_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "affiliate WHERE affiliate_id = '" . (int)$this->session->data['affiliate_id'] . "' AND status = '1'"); if ($affiliate_query->num_rows) { $this->affiliate_id = $affiliate_query->row['affiliate_id']; $this->firstname = $affiliate_query->row['firstname']; $this->lastname = $affiliate_query->row['lastname']; $this->email = $affiliate_query->row['email']; $this->telephone = $affiliate_query->row['telephone']; $this->fax = $affiliate_query->row['fax']; $this->code = $affiliate_query->row['code']; $this->db->query("UPDATE " . DB_PREFIX . "affiliate SET ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE affiliate_id = '" . (int)$this->session->data['affiliate_id'] . "'"); } else { $this->logout(); } } } public function login($email, $password) { $affiliate_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "affiliate WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '" . $this->db->escape(md5($password)) . "') AND status = '1' AND approved = '1'"); if ($affiliate_query->num_rows) { $this->session->data['affiliate_id'] = $affiliate_query->row['affiliate_id']; $this->affiliate_id = $affiliate_query->row['affiliate_id']; $this->firstname = $affiliate_query->row['firstname']; $this->lastname = $affiliate_query->row['lastname']; $this->email = $affiliate_query->row['email']; $this->telephone = $affiliate_query->row['telephone']; $this->fax = $affiliate_query->row['fax']; $this->code = $affiliate_query->row['code']; return true; } else { return false; } } public function logout() { unset($this->session->data['affiliate_id']); $this->affiliate_id = ''; $this->firstname = ''; $this->lastname = ''; $this->email = ''; $this->telephone = ''; $this->fax = ''; } public function isLogged() { return $this->affiliate_id; } public function getId() { return $this->affiliate_id; } public function getFirstName() { return $this->firstname; } public function getLastName() { return $this->lastname; } public function getEmail() { return $this->email; } public function getTelephone() { return $this->telephone; } public function getFax() { return $this->fax; } public function getCode() { return $this->code; } }
#include "defs.h" #include "fdefs.h" #include <stdlib.h> void gasify(job) char *job; { char command[MAXCOMM] ; char g_type[MAXCOMM] ; double temp_y ; double temp_slope ; double rho_shock ; double temp_shock ; double gas_frac ; double rhobar ; double metal ; double rho ; int i,j ; int old_nsph ; struct dark_particle *dp ; /* Gas particles are created from dark matter particles. * Masses are gas_frac * masses of dm particles * dm particle masses are multiplied by (1-gas_frac). * Temperatures are set to t=temp_y*(rho/rhobar)^temp_slope, * or to t=temp_shock if rho/rhobar>rho_shock. */ if (!boxes_loaded[0]){ printf("<sorry, no boxes are loaded, %s>\n",title) ; } else { if (sscanf(job,"%s %lf %lf %lf %lf %lf %lf %lf %s",command,&gas_frac, &rhobar,&temp_y,&temp_slope,&rho_shock,&temp_shock, &metal,g_type) == 8) { calc_density(&box0_smx, 1, 0, 0); header.nbodies += boxlist[0].ndark ; old_nsph = header.nsph ; header.nsph += boxlist[0].ndark ; if(header.nsph != 0) { gas_particles = (struct gas_particle *) realloc(gas_particles, header.nsph*sizeof(*gas_particles)); if(gas_particles == NULL) { printf("<sorry, no memory for gas particles, %s>\n",title) ; return ; } mark_gas = (short *)realloc(mark_gas,header.nsph*sizeof(*mark_gas)); if(mark_gas == NULL) { printf("<sorry, no memory for gas particle markers, %s>\n", title) ; return ; } for (i = old_nsph; i < header.nsph; i++) mark_gas[i] = 0; } else gas_particles = NULL; for (i = 0 ;i < boxlist[0].ndark ;i++) { dp = boxlist[0].dp[i] ; gas_particles[i+old_nsph].mass = gas_frac*(dp->mass) ; dp->mass = (1. - gas_frac)*(dp->mass) ; for(j = 0; j < header.ndim; j++){ gas_particles[i+old_nsph].pos[j] = dp->pos[j] ; gas_particles[i+old_nsph].vel[j] = dp->vel[j] ; } gas_particles[i+old_nsph].rho = gas_frac*(box0_smx->kd->p[i].fDensity); gas_particles[i+old_nsph].temp = temp_y* pow((gas_particles[i+old_nsph].rho/rhobar),temp_slope) ; if (gas_particles[i+old_nsph].rho > rhobar*rho_shock) { gas_particles[i+old_nsph].temp = temp_shock ; } gas_particles[i+old_nsph].hsmooth = sqrt(box0_smx->kd->p[i].fBall2)/2.0; gas_particles[i+old_nsph].metals = metal ; gas_particles[i+old_nsph].phi = dp->phi ; } if(box0_smx) { kdFinish(box0_smx->kd); smFinish(box0_smx); box0_smx = NULL; } boxes_loaded[0] = NO ; unload_all() ; active_box = 0 ; binary_loaded = LOADED ; current_project = NO ; current_color = NO ; divv_loaded = NO ; hneutral_loaded = NO ; meanmwt_loaded = NO ; xray_loaded = NO ; dudt_loaded = NO ; starform_loaded = NO ; } else if (sscanf(job,"%s %lf %lf %lf %lf %lf %lf %lf %s",command, &gas_frac,&rhobar,&temp_y,&temp_slope,&rho_shock, &temp_shock,&metal,g_type) == 9) { if (strcmp(g_type,"destroy") != 0 && strcmp(g_type,"d") != 0){ printf("<sorry, %s is not a gasify type, %s",g_type,title) ; return; } calc_density(&box0_smx, 1, 0, 0); printf("<warning, destroying original dark and gas particles, %s>\n", title) ; header.nbodies -= header.nsph ; header.nsph = boxlist[0].ndark ; header.ndark = 0 ; if(header.nsph != 0) { dark_particles = (struct dark_particle *) realloc(dark_particles, header.nsph*sizeof(*gas_particles)); if(dark_particles == NULL) { printf("<sorry, no memory for gas particles, %s>\n",title) ; return ; } gas_particles = (struct gas_particle *)dark_particles ; free(mark_dark) ; if(header.nsph != 0) mark_gas = (short *)calloc(header.nsph, sizeof(*mark_gas)); if(mark_gas == NULL && header.nsph != 0) { printf("<sorry, no memory for gas particle markers, %s>\n", title) ; return ; } for (i = 0; i < header.nsph; i++) mark_gas[i] = 0; } else gas_particles = NULL; for (i = boxlist[0].ndark - 1 ;i >= 0 ;i dp = boxlist[0].dp[i] ; gas_particles[i].phi = dp->phi ; gas_particles[i].metals = metal ; gas_particles[i].hsmooth = sqrt(box0_smx->kd->p[i].fBall2)/2.0; rho = gas_frac*(box0_smx->kd->p[i].fDensity); gas_particles[i].temp = temp_y*pow((rho/rhobar),temp_slope) ; if (rho > rhobar*rho_shock) { gas_particles[i].temp = temp_shock ; } gas_particles[i].rho = rho ; for(j = header.ndim - 1; j >= 0; j gas_particles[i+old_nsph].vel[j] = dp->vel[j] ; } for(j = header.ndim - 1; j >= 0; j gas_particles[i+old_nsph].pos[j] = dp->pos[j] ; } gas_particles[i].mass = gas_frac*(dp->mass) ; } if(box0_smx) { kdFinish(box0_smx->kd); smFinish(box0_smx); box0_smx = NULL; } dark_particles = NULL; boxes_loaded[0] = NO ; unload_all() ; active_box = 0 ; binary_loaded = LOADED ; current_project = NO ; current_color = NO ; divv_loaded = NO ; hneutral_loaded = NO ; meanmwt_loaded = NO ; xray_loaded = NO ; starform_loaded = NO ; dudt_loaded = NO ; } else { input_error(command) ; } } }
# -*- coding: utf-8 -*- from exceptions import DropPage, AbortProcess
# -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import <API key>, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return <API key> # False signals to clear any existing value, as opposed to just None return False return upload class <API key>(ImagePreviewWidget): template_name = 'admin/attachment/widgets/<API key>.html' class <API key>(ImagePreviewWidget): template_name = 'admin/attachment/widgets/<API key>.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None)