code
stringlengths
4
1.01M
language
stringclasses
2 values
/* DreamChess ** ** DreamChess is the legal property of its developers, whose names are too ** numerous to list here. Please refer to the AUTHORS.txt file distributed ** with this source distribution. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GAMEGUI_SIGNAL_H #define GAMEGUI_SIGNAL_H #include <gamegui/queue.h> #include <gamegui/system.h> typedef int gg_signal_t; gg_signal_t gg_signal_lookup(gg_class_id class, char *name); int gg_signal_register(gg_class_id class, char *name); void gg_signal_init(void); void gg_signal_exit(void); #endif
Java
import { Component } from '@angular/core' @Component({ selector: 'gallery', templateUrl: 'app/home/gallery.component.html' }) export class GalleryComponent { }
Java
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. OpenFOAM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::globalPoints Description Calculates points shared by more than two processor patches or cyclic patches. Is used in globalMeshData. (this info is needed for point-edge communication where you do all but these shared points with patch to patch communication but need to do a reduce on these shared points) Works purely topological and using local communication only. Needs: - domain to be one single domain (i.e. all faces can be reached through face-cell walk). - patch face ordering to be ok - f[0] ordering on patch faces to be ok. Works by constructing equivalence lists for all the points on processor patches. These list are procPointList and give processor and meshPoint label on that processor. E.g. @verbatim ((7 93)(4 731)(3 114)) @endverbatim means point 93 on proc7 is connected to point 731 on proc4 and 114 on proc3. It then gets the lowest numbered processor (the 'master') to request a sharedPoint label from processor0 and it redistributes this label back to the other processors in the equivalence list. Algorithm: - get meshPoints of all my points on processor patches and initialize equivalence lists to this. loop - send to all neighbours in relative form: - patchFace - index in face - receive and convert into meshPoints. Add to to my equivalence lists. - mark meshPoints for which information changed. - send data for these meshPoints again endloop until nothing changes At this point one will have complete point-point connectivity for all points on processor patches. Now - remove point equivalences of size 2. These are just normal points shared between two neighbouring procPatches. - collect on each processor points for which it is the master - request number of sharedPointLabels from the Pstream::master. This information gets redistributed to all processors in a similar way as that in which the equivalence lists were collected: - initialize the indices of shared points I am the master for loop - send my known sharedPoints + meshPoints to all neighbours - receive from all neighbour. Find which meshPoint on my processor the sharedpoint is connected to - mark indices for which information has changed endloop until nothing changes. SourceFiles globalPoints.C \*---------------------------------------------------------------------------*/ #ifndef globalPoints_H #define globalPoints_H #include <OpenFOAM/DynamicList.H> #include <OpenFOAM/Map.H> #include <OpenFOAM/labelList.H> #include <OpenFOAM/FixedList.H> #include <OpenFOAM/primitivePatch.H> #include <OpenFOAM/className.H> #include <OpenFOAM/edgeList.H> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of classes class polyMesh; class polyBoundaryMesh; class cyclicPolyPatch; /*---------------------------------------------------------------------------*\ Class globalPoints Declaration \*---------------------------------------------------------------------------*/ class globalPoints { // Private classes //- Define procPointList as holding a list of meshPoint/processor labels typedef FixedList<label, 2> procPoint; typedef List<procPoint> procPointList; // Private data //- Mesh reference const polyMesh& mesh_; //- Sum of points on processor patches (unfiltered, point on 2 patches // counts as 2) const label nPatchPoints_; //- All points on boundaries and their corresponding connected points // on other processors. DynamicList<procPointList> procPoints_; //- Map from mesh point to index in procPoints Map<label> meshToProcPoint_; //- Shared points used by this processor (= global point number) labelList sharedPointAddr_; //- My meshpoints corresponding to the shared points labelList sharedPointLabels_; //- Total number of shared points. label nGlobalPoints_; // Private Member Functions //- Count all points on processorPatches. Is all points for which // information is collected. static label countPatchPoints(const polyBoundaryMesh&); //- Add information about patchPointI in relative indices to send // buffers (patchFaces, indexInFace etc.) static void addToSend ( const primitivePatch&, const label patchPointI, const procPointList&, DynamicList<label>& patchFaces, DynamicList<label>& indexInFace, DynamicList<procPointList>& allInfo ); //- Merge info from neighbour into my data static bool mergeInfo ( const procPointList& nbrInfo, procPointList& myInfo ); //- Store (and merge) info for meshPointI bool storeInfo(const procPointList& nbrInfo, const label meshPointI); //- Initialize procPoints_ to my patch points. allPoints = true: // seed with all patch points, = false: only boundaryPoints(). void initOwnPoints(const bool allPoints, labelHashSet& changedPoints); //- Send subset of procPoints to neighbours void sendPatchPoints(const labelHashSet& changedPoints) const; //- Receive neighbour points and merge into my procPoints. void receivePatchPoints(labelHashSet& changedPoints); //- Remove entries of size 2 where meshPoint is in provided Map. // Used to remove normal face-face connected points. void remove(const Map<label>&); //- Get indices of point for which I am master (lowest numbered proc) labelList getMasterPoints() const; //- Send subset of shared points to neighbours void sendSharedPoints(const labelList& changedIndices) const; //- Receive shared points and update subset. void receiveSharedPoints(labelList& changedIndices); //- Should move into cyclicPolyPatch but some ordering problem // keeps on giving problems. static edgeList coupledPoints(const cyclicPolyPatch&); //- Disallow default bitwise copy construct globalPoints(const globalPoints&); //- Disallow default bitwise assignment void operator=(const globalPoints&); public: //- Declare name of the class and its debug switch ClassName("globalPoints"); // Constructors //- Construct from mesh globalPoints(const polyMesh& mesh); // Member Functions // Access label nPatchPoints() const { return nPatchPoints_; } const Map<label>& meshToProcPoint() const { return meshToProcPoint_; } //- shared points used by this processor (= global point number) const labelList& sharedPointAddr() const { return sharedPointAddr_; } //- my meshpoints corresponding to the shared points const labelList& sharedPointLabels() const { return sharedPointLabels_; } label nGlobalPoints() const { return nGlobalPoints_; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************ vim: set sw=4 sts=4 et: ************************ //
Java
/* * Multi2Sim * Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.edu) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <assert.h> #include <lib/mhandle/mhandle.h> #include <lib/util/debug.h> #include <lib/util/linked-list.h> #include "opencl-repo.h" #include "opencl-command-queue.h" #include "opencl-context.h" #include "opencl-device.h" #include "opencl-event.h" #include "opencl-kernel.h" #include "opencl-mem.h" #include "opencl-platform.h" #include "opencl-program.h" #include "opencl-sampler.h" struct si_opencl_repo_t { struct linked_list_t *object_list; }; struct si_opencl_repo_t *si_opencl_repo_create(void) { struct si_opencl_repo_t *repo; /* Initialize */ repo = xcalloc(1, sizeof(struct si_opencl_repo_t)); repo->object_list = linked_list_create(); /* Return */ return repo; } void si_opencl_repo_free(struct si_opencl_repo_t *repo) { linked_list_free(repo->object_list); free(repo); } void si_opencl_repo_add_object(struct si_opencl_repo_t *repo, void *object) { struct linked_list_t *object_list = repo->object_list; /* Check that object does not exist */ linked_list_find(object_list, object); if (!object_list->error_code) fatal("%s: object already exists", __FUNCTION__); /* Insert */ linked_list_add(object_list, object); } void si_opencl_repo_remove_object(struct si_opencl_repo_t *repo, void *object) { struct linked_list_t *object_list = repo->object_list; /* Check that object exists */ linked_list_find(object_list, object); if (object_list->error_code) fatal("%s: object does not exist", __FUNCTION__); /* Remove */ linked_list_remove(object_list); } /* Look for an object in the repository. The first field of every OpenCL object * is its identifier. */ void *si_opencl_repo_get_object(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type, unsigned int object_id) { struct linked_list_t *object_list = repo->object_list; void *object; unsigned int current_object_id; /* Upper 16-bits represent the type of the object */ if (object_id >> 16 != type) fatal("%s: requested OpenCL object of incorrect type", __FUNCTION__); /* Search object */ LINKED_LIST_FOR_EACH(object_list) { object = linked_list_get(object_list); assert(object); current_object_id = * (unsigned int *) object; if (current_object_id == object_id) return object; } /* Not found */ fatal("%s: requested OpenCL does not exist (id=0x%x)", __FUNCTION__, object_id); return NULL; } /* Get the oldest created OpenCL object of the specified type */ void *si_opencl_repo_get_object_of_type(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type) { struct linked_list_t *object_list = repo->object_list; void *object; unsigned int object_id; /* Find object. Upper 16-bits of identifier contain its type. */ LINKED_LIST_FOR_EACH(object_list) { object = linked_list_get(object_list); assert(object); object_id = * (unsigned int *) object; if (object_id >> 16 == type) return object; } /* No object found */ return NULL; } /* Assignment of OpenCL object identifiers * An identifier is a 32-bit value, whose 16 most significant bits represent the * object type, while the 16 least significant bits represent a unique object ID. */ unsigned int si_opencl_repo_new_object_id(struct si_opencl_repo_t *repo, enum si_opencl_object_type_t type) { static unsigned int si_opencl_object_id_counter; unsigned int object_id; object_id = (type << 16) | si_opencl_object_id_counter; si_opencl_object_id_counter++; if (si_opencl_object_id_counter > 0xffff) fatal("%s: limit of OpenCL objects exceeded\n", __FUNCTION__); return object_id; } void si_opencl_repo_free_all_objects(struct si_opencl_repo_t *repo) { void *object; /* Platforms */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_platform))) si_opencl_platform_free((struct si_opencl_platform_t *) object); /* Devices */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_device))) si_opencl_device_free((struct si_opencl_device_t *) object); /* Contexts */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_context))) si_opencl_context_free((struct si_opencl_context_t *) object); /* Command queues */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_command_queue))) si_opencl_command_queue_free((struct si_opencl_command_queue_t *) object); /* Programs */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_program))) si_opencl_program_free((struct si_opencl_program_t *) object); /* Kernels */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_kernel))) si_opencl_kernel_free((struct si_opencl_kernel_t *) object); /* Mems */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_mem))) si_opencl_mem_free((struct si_opencl_mem_t *) object); /* Events */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_event))) si_opencl_event_free((struct si_opencl_event_t *) object); /* Samplers */ while ((object = si_opencl_repo_get_object_of_type(repo, si_opencl_object_sampler))) si_opencl_sampler_free((struct si_opencl_sampler_t *) object); /* Any object left */ if (linked_list_count(repo->object_list)) panic("%s: not all objects were freed", __FUNCTION__); }
Java
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; class ParityBackground extends Component { static propTypes = { style: PropTypes.object.isRequired, children: PropTypes.node, className: PropTypes.string, onClick: PropTypes.func }; render () { const { children, className, style, onClick } = this.props; return ( <div className={ className } style={ style } onTouchTap={ onClick }> { children } </div> ); } } function mapStateToProps (_, initProps) { const { gradient, seed, muiTheme } = initProps; let _seed = seed; let _props = { style: muiTheme.parity.getBackgroundStyle(gradient, seed) }; return (state, props) => { const { backgroundSeed } = state.settings; const { seed } = props; const newSeed = seed || backgroundSeed; if (newSeed === _seed) { return _props; } _seed = newSeed; _props = { style: muiTheme.parity.getBackgroundStyle(gradient, newSeed) }; return _props; }; } export default connect( mapStateToProps )(ParityBackground);
Java
/** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ (function ($, require) { var exports = require('piwik/UI'); /** * Creates a new notifications. * * Example: * var UI = require('piwik/UI'); * var notification = new UI.Notification(); * notification.show('My Notification Message', {title: 'Low space', context: 'warning'}); */ var Notification = function () { this.$node = null; }; /** * Makes the notification visible. * * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} [options] * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {bool} [options.animate=true] If enabled, the notification will be faded in. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} * @param {string} [options.placeat] By default, the notification will be displayed in the "stats bar". * You can specify any other CSS selector to place the notifications * wherever you want. */ Notification.prototype.show = function (message, options) { checkMessage(message); options = checkOptions(options); var template = generateNotificationHtmlMarkup(options, message); this.$node = placeNotification(template, options); }; /** * Removes a previously shown notification having the given notification id. * * * @param {string} notificationId The id of a notification that was previously registered. */ Notification.prototype.remove = function (notificationId) { $('[piwik-notification][notification-id=' + notificationId + ']').remove(); }; Notification.prototype.scrollToNotification = function () { if (this.$node) { piwikHelper.lazyScrollTo(this.$node, 250); } }; /** * Shows a notification at a certain point with a quick upwards animation. * * TODO: if the materializecss version matomo uses is updated, should use their toasts. * * @type {Notification} * @param {string} message The actual message that will be displayed. Must be set. * @param {Object} options * @param {string} options.placeat Where to place the notification. Required. * @param {string} [options.id] Only needed for persistent notifications. The id will be sent to the * frontend once the user closes the notifications. The notification has to * be registered/notified under this name * @param {string} [options.title] The title of the notification. For instance the plugin name. * @param {string} [options.context=warning] Context of the notification: 'info', 'warning', 'success' or * 'error' * @param {string} [options.type=transient] The type of the notification: Either 'toast' or 'transitent' * @param {bool} [options.noclear=false] If set, the close icon is not displayed. * @param {object} [options.style] Optional style/css dictionary. For instance {'display': 'inline-block'} */ Notification.prototype.toast = function (message, options) { checkMessage(message); options = checkOptions(options); var $placeat = $(options.placeat); if (!$placeat.length) { throw new Error("A valid selector is required for the placeat option when using Notification.toast()."); } var $template = $(generateNotificationHtmlMarkup(options, message)).hide(); $('body').append($template); compileNotification($template); $template.css({ position: 'absolute', left: $placeat.offset().left, top: $placeat.offset().top }); setTimeout(function () { $template.animate( { top: $placeat.offset().top - $template.height() }, { duration: 300, start: function () { $template.show(); } } ); }); }; exports.Notification = Notification; function generateNotificationHtmlMarkup(options, message) { var attributeMapping = { id: 'notification-id', title: 'notification-title', context: 'context', type: 'type', noclear: 'noclear', class: 'class', toastLength: 'toast-length' }, html = '<div piwik-notification'; for (var key in attributeMapping) { if (attributeMapping.hasOwnProperty(key) && options[key] ) { html += ' ' + attributeMapping[key] + '="' + options[key].toString().replace(/"/g, "&quot;") + '"'; } } html += '>' + message + '</div>'; return html; } function compileNotification($node) { angular.element(document).injector().invoke(function ($compile, $rootScope) { $compile($node)($rootScope.$new(true)); }); } function placeNotification(template, options) { var $notificationNode = $(template); // compile the template in angular compileNotification($notificationNode); if (options.style) { $notificationNode.css(options.style); } var notificationPosition = '#notificationContainer'; var method = 'append'; if (options.placeat) { notificationPosition = options.placeat; } else { // If a modal is open, we want to make sure the error message is visible and therefore show it within the opened modal var modalSelector = '.modal.open .modal-content'; var modalOpen = $(modalSelector); if (modalOpen.length) { notificationPosition = modalSelector; method = 'prepend'; } } $notificationNode = $notificationNode.hide(); $(notificationPosition)[method]($notificationNode); if (false === options.animate) { $notificationNode.show(); } else { $notificationNode.fadeIn(1000); } return $notificationNode; } function checkMessage(message) { if (!message) { throw new Error('No message given, cannot display notification'); } } function checkOptions(options) { if (options && !$.isPlainObject(options)) { throw new Error('Options has the wrong format, cannot display notification'); } else if (!options) { options = {}; } return options; } })(jQuery, require);
Java
PREP(initCBASettings); PREP(postInit);
Java
/* * Jinx is Copyright 2010-2020 by Jeremy Brooks and Contributors * * Jinx is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jinx is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jinx. If not, see <http://www.gnu.org/licenses/>. */ package net.jeremybrooks.jinx.api; import net.jeremybrooks.jinx.Jinx; import net.jeremybrooks.jinx.JinxException; import net.jeremybrooks.jinx.JinxUtils; import net.jeremybrooks.jinx.response.Response; import net.jeremybrooks.jinx.response.photos.notes.Note; import java.util.Map; import java.util.TreeMap; /** * Provides access to the flickr.photos.notes API methods. * * @author Jeremy Brooks * @see <a href="https://www.flickr.com/services/api/">Flickr API documentation</a> for more details. */ public class PhotosNotesApi { private Jinx jinx; public PhotosNotesApi(Jinx jinx) { this.jinx = jinx; } /** * Add a note to a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages. * <br> * This method requires authentication with 'write' permission. * * @param photoId (Required) The id of the photo to add a note to. * @param noteX (Required) The left coordinate of the note. * @param noteY (Required) The top coordinate of the note. * @param noteWidth (Required) The width of the note. * @param noteHeight (Required) The height of the note. * @param noteText (Required) The text of the note. * @return object with the ID for the newly created note. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.add.html">flickr.photos.notes.add</a> */ public Note add(String photoId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(photoId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.add"); params.put("photo_id", photoId); params.put("note_x", Integer.toString(noteX)); params.put("note_y", Integer.toString(noteY)); params.put("note_w", Integer.toString(noteWidth)); params.put("note_h", Integer.toString(noteHeight)); params.put("note_text", noteText); return jinx.flickrPost(params, Note.class); } /** * Edit a note on a photo. Coordinates and sizes are in pixels, based on the 500px image size shown on individual photo pages. * <br> * This method requires authentication with 'write' permission. * * @param noteId (Required) The id of the note to edit. * @param noteX (Required) The left coordinate of the note. * @param noteY (Required) The top coordinate of the note. * @param noteWidth (Required) The width of the note. * @param noteHeight (Required) The height of the note. * @param noteText (Required) The text of the note. * @return object with the status of the requested operation. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.edit.html">flickr.photos.notes.edit</a> */ public Response edit(String noteId, int noteX, int noteY, int noteWidth, int noteHeight, String noteText) throws JinxException { JinxUtils.validateParams(noteId, noteText); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.edit"); params.put("note_id", noteId); params.put("note_x", Integer.toString(noteX)); params.put("note_y", Integer.toString(noteY)); params.put("note_w", Integer.toString(noteWidth)); params.put("note_h", Integer.toString(noteHeight)); params.put("note_text", noteText); return jinx.flickrPost(params, Response.class); } /** * Delete a note from a photo. * <br> * This method requires authentication with 'write' permission. * * @param noteId (Required) The id of the note to delete. * @return object with the status of the requested operation. * @throws JinxException if required parameters are missing, or if there are any errors. * @see <a href="https://www.flickr.com/services/api/flickr.photos.notes.delete.html">flickr.photos.notes.delete</a> */ public Response delete(String noteId) throws JinxException { JinxUtils.validateParams(noteId); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.notes.delete"); params.put("note_id", noteId); return jinx.flickrPost(params, Response.class); } }
Java
<?php /** * PHPUnit * * Copyright (c) 2002-2009, Sebastian Bergmann <sb@sebastian-bergmann.de>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @category Testing * @package PHPUnit * @author Jan Borsodi <jb@ez.no> * @author Sebastian Bergmann <sb@sebastian-bergmann.de> * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version SVN: $Id: Parameters.php 4403 2008-12-31 09:26:51Z sb $ * @link http://www.phpunit.de/ * @since File available since Release 3.0.0 */ require_once 'PHPUnit/Framework.php'; require_once 'PHPUnit/Util/Filter.php'; require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; require_once 'PHPUnit/Framework/MockObject/Invocation.php'; PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); /** * Invocation matcher which looks for specific parameters in the invocations. * * Checks the parameters of all incoming invocations, the parameter list is * checked against the defined constraints in $parameters. If the constraint * is met it will return true in matches(). * * @category Testing * @package PHPUnit * @author Jan Borsodi <jb@ez.no> * @author Sebastian Bergmann <sb@sebastian-bergmann.de> * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> * @license http://www.opensource.org/licenses/bsd-license.php BSD License * @version Release: 3.4.0beta1 * @link http://www.phpunit.de/ * @since Class available since Release 3.0.0 */ class PHPUnit_Framework_MockObject_Matcher_Parameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation { protected $parameters = array(); protected $invocation; public function __construct($parameters) { foreach($parameters as $parameter) { if (!($parameter instanceof PHPUnit_Framework_Constraint)) { $parameter = new PHPUnit_Framework_Constraint_IsEqual($parameter); } $this->parameters[] = $parameter; } } public function toString() { $text = 'with parameter'; foreach($this->parameters as $index => $parameter) { if ($index > 0) { $text .= ' and'; } $text .= ' ' . $index . ' ' . $parameter->toString(); } return $text; } public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) { $this->invocation = $invocation; $this->verify(); return count($invocation->parameters) < count($this->parameters); } public function verify() { if ($this->invocation === NULL) { throw new PHPUnit_Framework_ExpectationFailedException( 'Mocked method does not exist.' ); } if (count($this->invocation->parameters) < count($this->parameters)) { throw new PHPUnit_Framework_ExpectationFailedException( sprintf( 'Parameter count for invocation %s is too low.', $this->invocation->toString() ) ); } foreach ($this->parameters as $i => $parameter) { if (!$parameter->evaluate($this->invocation->parameters[$i])) { $parameter->fail( $this->invocation->parameters[$i], sprintf( 'Parameter %s for invocation %s does not match expected value.', $i, $this->invocation->toString() ) ); } } } } ?>
Java
<?php /** * * @version 1.0.9 June 24, 2016 * @package Get Bible API * @author Llewellyn van der Merwe <llewellyn@vdm.io> * @copyright Copyright (C) 2013 Vast Development Method <http://www.vdm.io> * @license GNU General Public License <http://www.gnu.org/copyleft/gpl.html> * **/ defined( '_JEXEC' ) or die( 'Restricted access' ); //Import filesystem libraries. Perhaps not necessary, but does not hurt jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.application.component.helper'); class GetbibleModelImport extends JModelLegacy { protected $user; protected $dateSql; protected $book_counter; protected $app_params; protected $local = false; protected $curlError = false; public $availableVersions; public $availableVersionsList; public $installedVersions; public function __construct() { parent::__construct(); // get params $this->app_params = JComponentHelper::getParams('com_getbible'); // get user data $this->user = JFactory::getUser(); // get todays date $this->dateSql = JFactory::getDate()->toSql(); // we need a loger execution time if (ini_set('max_execution_time', 300) === false) { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_INCREASE_EXECUTION_TIME'), 'error'); return false; } // load available verstions $this->getVersionAvailable(); // get installed versions $this->getInstalledVersions(); } protected function populateState() { parent::populateState(); // Get the input data $jinput = JFactory::getApplication()->input; $source = $jinput->post->get('translation', NULL, 'STRING'); $translation = (string) preg_replace('/[^A-Z0-9_\)\(-]/i', '', $source); // Set to state $this->setState('translation', $translation); } public function getVersions() { // reload version list for app $available = $this->availableVersionsList; $alreadyin = $this->installedVersions; if($available){ if ($alreadyin){ $result = array_diff($available, $alreadyin); } else { $result = $available; } if($result){ $setVersions = array(); $setVersions[] = JHtml::_('select.option', '', JText::_('COM_GETBIBLE_PLEASE_SELECT')); foreach ($this->availableVersions as $key => $values){ if(in_array($key, $result)){ $name = $values["versionName"]. ' ('.$values["versionLang"].')'; $setVersions[] = JHtml::_('select.option', $values["fileName"], $name); } } return $setVersions; } JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_ALL_BIBLES_ALREADY_INSTALLED'), 'success'); return false; } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } public function rutime($ru, $rus, $index) { return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000)) - ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000)); } public function getImport() { if ($this->getState('translation')){ // set version $versionFileName = $this->getState('translation'); $versionfix = str_replace("___", "'", $versionFileName); list($versionLang,$versionName,$versionCode,$bidi) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $version = $versionCode; //check input if ($this->checkTranslation($version) && $this->checkFileName($versionFileName)){ // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); if($installOptions){ // get the file $filename = 'https://getbible.net/scriptureinstall/'.$versionFileName.'.txt'; } else { // get localInstallFolder set in params $filename = JPATH_ROOT.'/'.rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/').'/'.$versionFileName.'.txt'; } // load the file $file = new SplFileObject($filename); // start up database $db = JFactory::getDbo(); // load all books $books = $this->setBooks($version); $i = 1; // build query to save if (is_object($file)) { while (! $file->eof()) { $verse = explode("||",$file->fgets()); $found = false; // rename books foreach ($books as $book){ $verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0])); if ($book['nr'] <= 39) { if (strpos($verse[0],'O') !== false) { $search_value = sprintf("%02s", $book['nr']).'O'; } else { $search_value = sprintf("%02s", $book['nr']); } } else { if (strpos($verse[0],'N') !== false) { $search_value = $book['nr'].'N'; } else { $search_value = $book['nr']; } } if ($verse[0] == $search_value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $book_name = $book['name']; $found = true; break; } } if(!$found){ foreach ($books as $book){ $verse[0] = strtoupper(preg_replace('/\s+/', '', $verse[0])); foreach($book['book_names'] as $key => $value){ if ($value){ $value = strtoupper(preg_replace('/\s+/', '', $value)); if ($verse[0] == $value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $book_name = $book['name']; $found = true; break; } } } } } if(!$found){ // load all books again as KJV $books = $this->setBooks($version, true); foreach ($books as $book){ foreach($book['book_names'] as $key => $value){ if ($value){ $value = strtoupper(preg_replace('/\s+/', '', $value)); if ($verse[0] == $value){ $verse[0] = $book['nr']; $book_nr = $book['nr']; $found = true; break; } } } } } // set data if(isset($verse[3]) && $verse[3]){ $Bible[$verse[0]][$verse[1]][$verse[2]] = $verse[3]; // Create a new query object for this verse. $versObject = new stdClass(); $versObject->version = $version; $versObject->book_nr = $book_nr; $versObject->chapter_nr = $verse[1]; $versObject->verse_nr = $verse[2]; $versObject->verse = $verse[3]; $versObject->access = 1; $versObject->published = 1; $versObject->created_by = $this->user->id; $versObject->created_on = $this->dateSql; // Insert the object into the verses table. $result = JFactory::getDbo()->insertObject('#__getbible_verses', $versObject); } } } // clear from memory unset($file); // save complete books & chapters foreach ($books as $book) { if (isset($book["nr"]) && isset($Bible[$book["nr"]])) { $this->saveChapter($version, $book["nr"], $Bible[$book["nr"]]); $this->saveBooks($version, $book["nr"], $Bible[$book["nr"]]); } } // clear from memory unset($books); // Set version details if(is_array($this->book_counter)){ if(in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){ $testament = 'OT&NT'; } elseif(in_array(1,$this->book_counter) && !in_array(66,$this->book_counter)){ $testament = 'OT'; } elseif(!in_array(1,$this->book_counter) && in_array(66,$this->book_counter)){ $testament = 'NT'; } else { $testament = 'NOT'; } $book_counter = json_encode($this->book_counter); } else { $book_counter = 'error'; $testament = 'error'; } // Create a new query object for this Version. $versionObject = new stdClass(); $versionObject->name = $versionName; $versionObject->bidi = $bidi; $versionObject->language = $versionLang; $versionObject->books_nr = $book_counter; $versionObject->testament = $testament; $versionObject->version = $version; $versionObject->link = $filename; $versionObject->installed = 1; $versionObject->access = 1; $versionObject->published = 1; $versionObject->created_by = $this->user->id; $versionObject->created_on = $this->dateSql; // Insert the object into the versions table. $result = JFactory::getDbo()->insertObject('#__getbible_versions', $versionObject); JFactory::getApplication()->enqueueMessage(JText::sprintf('COM_GETBIBLE_MESSAGE_BIBLE_INSTALLED_SUCCESSFULLY', $versionName)); // reset the local version list. $this->_cpanel(); // if first Bible is installed change the application to load localy with that Bible as the default $this->setLocal(); // clean cache to insure the dropdown removes this installed version. $this->cleanCache('_system'); return true; } else { return false; } } else { return false; } } protected function checkTranslation($version) { // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); $available = $this->availableVersionsList; $alreadyin = $this->installedVersions; if ($available){ if(in_array($version, $available)){ if ($alreadyin){ if(in_array($version, $alreadyin)){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_ALREADY_INSTALLED'), 'error'); return false; }return true; }return true; } JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_NOT_FOUND_ON_GETBIBLE'), 'error'); return false; } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } protected function checkFileName($versionFileName) { $available = $this->availableVersions; $found = false; if ($available){ foreach($available as $file){ if (in_array($versionFileName, $file)){ $found = true; break; } else { $found = false; } } if(!$found){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_VERSION_NOT_FOUND_ON_GETBIBLE'), 'error'); return false; } else { return $found; } } if($this->curlError){ JFactory::getApplication()->enqueueMessage(JText::_($this->curlError), 'error'); return false; } else { if($this->local){ JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_LOCAL_OFFLINE'), 'error'); return false; } else { JFactory::getApplication()->enqueueMessage(JText::_('COM_GETBIBLE_MESSAGE_GETBIBLE_OFFLINE'), 'error'); return false; } } } protected function saveChapter($version, $book_nr, $chapters) { if ( $chapters ){ // start up database $db = JFactory::getDbo(); // Create a new query object for this verstion $query = $db->getQuery(true); // set chapter number $chapter_nr = 1; $values = ''; // set the data foreach ($chapters as $chapter) { $setup = NULL; $text = NULL; $ver = 1; foreach($chapter as $verse) { $text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse); $ver++; } $setup = array('chapter'=>$text); $scripture = json_encode($setup); // Insert values. $values[] = $db->quote($version).', '.(int)$book_nr.', '.(int)$chapter_nr.', '.$db->quote($scripture).', 1, 1, '.$this->user->id.', '.$db->quote($this->dateSql); $chapter_nr++; } // clear from memory unset($chapters); // Insert columns. $columns = array( 'version', 'book_nr', 'chapter_nr', 'chapter', 'access', 'published', 'created_by', 'created_on' ); // Prepare the insert query. $query->insert($db->quoteName('#__getbible_chapters')); $query->columns($db->quoteName($columns)); $query->values($values); // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->query(); } return true; } protected function saveBooks($version, $book_nr, $book) { if (is_array($book) && count($book)){ //set book number $this->book_counter[] = $book_nr; // start up database $db = JFactory::getDbo(); // Create a new query object for this verstion $query = $db->getQuery(true); // set chapter number $chapter_nr = 1; $values = ''; // set the data foreach ($book as $chapter) { $setup = NULL; $text = NULL; $ver = 1; foreach($chapter as $verse) { $text[$ver] = array( 'verse_nr' => $ver,'verse' => $verse); $ver++; } $setupChapter[$chapter_nr] = array('chapter_nr'=>$chapter_nr,'chapter'=>$text); $chapter_nr++; } // clear from memory unset($book); $setup = array('book'=>$setupChapter); $saveBook = json_encode($setup); // Create a new query object for this verstion $query = $db->getQuery(true); // Insert columns. $columns = array('version', 'book_nr', 'book', 'access', 'published', 'created_by', 'created_on'); // Insert values. $values = array($db->quote($version), (int) $book_nr, $db->quote($saveBook), 1, 1, $this->user->id, $db->quote($this->dateSql)); // Prepare the insert query. $query ->insert($db->quoteName('#__getbible_books')) ->columns($db->quoteName($columns)) ->values(implode(',', $values)); //echo nl2br(str_replace('#__','api_',$query)); die; // Set the query using our newly populated query object and execute it. $db->setQuery($query); $db->query(); } return true; } protected function getInstalledVersions() { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName('version')); $query->from($db->quoteName('#__getbible_versions')); $query->order('version ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadColumn(); if ($results){ $this->installedVersions = $results; return true; } return false; } protected function setLocalXML() { jimport( 'joomla.filesystem.folder' ); // get localInstallFolder set in params $path = rtrim(ltrim($this->app_params->get('localInstallFolder'),'/'),'/'); // creat folder JFolder::create(JPATH_ROOT.'/'.$path.'/xml'); // set the file name $filepath = JPATH_ROOT.'/'.$path.'/xml/version.xml.php'; // set folder path $folderpath = JPATH_ROOT.'/'.$path; $fh = fopen($filepath, "w"); if (!is_resource($fh)) { return false; } $data = $this->setPHPforXML($folderpath); if(!fwrite($fh, $data)){ // close file. fclose($fh); return false; } // close file. fclose($fh); // return local file path return JURI::root().$path.'/xml/version.xml.php/versions.xml'; } protected function setPHPforXML($path) { return "<?php foreach (glob(\"".$path."/*.txt\") as \$filename) { \$available[] = str_replace('.txt', '', basename(\$filename)); // do something with \$filename } \$xml = new SimpleXMLElement('<versions/>'); foreach (\$available as \$version) { \$xml->addChild('name', \$version); } header('Content-type: text/xml'); header('Pragma: public'); header('Cache-control: private'); header('Expires: -1'); print(\$xml->asXML()); ?>"; } protected function getVersionAvailable() { // get instilation opstion set in params $installOptions = $this->app_params->get('installOptions'); if(!$installOptions){ $xml = $this->setLocalXML(); $this->local = true; } else { // check the available versions on getBible $xml = 'https://getbible.net/scriptureinstall/xml/version.xml.php/versions.xml'; } if(@fopen($xml, 'r')){ if (($response_xml_data = file_get_contents($xml))===false){ $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { libxml_use_internal_errors(true); $data = simplexml_load_string($response_xml_data); if (!$data) { $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { foreach ($data->name as $version){ $versionfix = str_replace("___", "'", $version); list($versionLang,$versionName,$versionCode) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $versions[$versionCode]['fileName'] = $version; $versions[$versionCode]['versionName'] = $versionName; $versions[$versionCode]['versionLang'] = $versionLang; $versions[$versionCode]['versionCode'] = $versionCode; $version_list[] = $versionCode; } $this->availableVersions = $versions; $this->availableVersionsList = $version_list; return true; } } } elseif(function_exists('curl_init')){ $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL,$xml); $response_xml_data = curl_exec($ch); if(curl_error($ch)){ $this->curlError = curl_error($ch); } curl_close($ch); $data = simplexml_load_string($response_xml_data); // echo'<pre>';var_dump($data);exit; if (!$data) { $this->availableVersions = false; $this->availableVersionsList = false; return false; } else { foreach ($data->name as $version){ $versionfix = str_replace("___", "'", $version); list($versionLang,$versionName,$versionCode) = explode('__', $versionfix); $versionName = str_replace("_", " ", $versionName); $versions[$versionCode]['fileName'] = $version; $versions[$versionCode]['versionName'] = $versionName; $versions[$versionCode]['versionLang'] = $versionLang; $versions[$versionCode]['versionCode'] = $versionCode; $version_list[] = $versionCode; } $this->availableVersions = $versions; $this->availableVersionsList = $version_list; return true; } } else { $this->availableVersions = false; $this->availableVersionsList = false; return false; } } protected function setBooks($version = NULL, $retry = false, $default = 'kjv') { // Get a db connection. $db = JFactory::getDbo(); if ($version){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($version)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); if($results){ foreach ($results as $book){ $books[$book['book_nr']]['nr'] = $book['book_nr']; $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); // if retry do't change name $books[$book['book_nr']]['name'] = $book['book_name']; } } } if(!isset($books)){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($default)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); foreach ($results as $book){ $books[$book['book_nr']]['nr'] = $book['book_nr']; $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); $books[$book['book_nr']]['name'] = $book['book_name']; } } if($retry){ // Create a new query object. $query = $db->getQuery(true); // Order it by the ordering field. $query->select($db->quoteName(array('book_names', 'book_nr', 'book_name'))); $query->from($db->quoteName('#__getbible_setbooks')); $query->where($db->quoteName('version') . ' = '. $db->quote($default)); $query->where($db->quoteName('access') . ' = 1'); $query->where($db->quoteName('published') . ' = 1'); $query->order('book_nr ASC'); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadAssocList(); foreach ($results as $book){ if(!$books[$book['book_nr']]['nr']){ $books[$book['book_nr']]['nr'] = $book['book_nr']; } $books[$book['book_nr']]['book_names'] = (array)json_decode($book['book_names']); if(!$books[$book['book_nr']]['name']){ $books[$book['book_nr']]['name'] = $book['book_name']; } } } return $books; } protected function _cpanel() { // Base this model on the backend version. require_once JPATH_ADMINISTRATOR.'/components/com_getbible/models/cpanel.php'; $cpanel_model = new GetbibleModelCpanel; return $cpanel_model->setCpanel(); } protected function setLocal() { $this->getInstalledVersions(); $versions = $this->installedVersions; $number = count($versions); // only change to local API on install of first Bible if ($number == 1){ // get default Book Name $defaultStartBook = $this->app_params->get('defaultStartBook'); // make sure it is set to the correct name avaliable in this new default version // first get book number $book_nr = $this->getLocalBookNR($defaultStartBook, $versions[0]); // second check if this version has this book and return the book number it has $book_nr = $this->checkVersionBookNR($book_nr, $versions[0]); // third set the book name $defaultStartBook = $this->getLocalDefaultBook($defaultStartBook, $versions[0], $book_nr); // Update Global Settings $params = JComponentHelper::getParams('com_getbible'); $params->set('defaultStartVersion', $versions[0]); $params->set('defaultStartBook', $defaultStartBook); $params->set('jsonQueryOptions', 1); // Get a new database query instance $db = JFactory::getDBO(); $query = $db->getQuery(true); // Build the query $query->update('#__extensions AS a'); $query->set('a.params = ' . $db->quote((string)$params)); $query->where('a.element = "com_getbible"'); // Execute the query // echo nl2br(str_replace('#__','api_',$query)); die; $db->setQuery($query); $db->query(); return true; } return false; } protected function getLocalBookNR($defaultStartBook,$version,$retry = false) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_setbooks AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($version)); $query->where($db->quoteName('a.book_name') . ' = ' . $db->quote($defaultStartBook)); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $db->loadResult(); } else { // fall back on default if($retry){ return 43; } return $this->getLocalBookNR($defaultStartBook,'kjv',true); } } protected function checkVersionBookNR($book_nr, $defaultVersion) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_books AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $book_nr; } else { // Run the default // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_nr'); $query->from('#__getbible_books AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); // Reset the query using our newly populated query object. $db->setQuery($query); // Load the results $results = $db->loadColumn(); // set book array $results = array_unique($results); // set book for Old Testament (Psalms) or New Testament (John) if (in_array(43,$results)){ return 43; } elseif(in_array(19,$results)) { return 19; } return false; } } protected function getLocalDefaultBook($defaultStartBook,$defaultVersion,$book_nr,$tryAgain = false) { // Get a db connection. $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); $query->select('a.book_name'); $query->from('#__getbible_setbooks AS a'); $query->where($db->quoteName('a.access') . ' = 1'); $query->where($db->quoteName('a.published') . ' = 1'); if($tryAgain){ $query->where($db->quoteName('a.version') . ' = ' . $db->quote($tryAgain)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); } else { $query->where($db->quoteName('a.version') . ' = ' . $db->quote($defaultVersion)); $query->where($db->quoteName('a.book_nr') . ' = ' . $book_nr); } // Reset the query using our newly populated query object. $db->setQuery($query); $db->execute(); $num_rows = $db->getNumRows(); if($num_rows){ // Load the results return $db->loadResult(); } else { // fall back on default return $this->getLocalDefaultBook($defaultStartBook,$defaultVersion,$book_nr,'kjv'); } } }
Java
# recette_la42 la bière qui répond à la question sur la vie, l'univers et le reste Recette Bière de Blé Libre 4.2° - Blanche ## Ingrédients pour 100 litres * 15kg Malt Pils ardèche (Malteur Echos) * 10kg Malt Blé ardèche (Malteur Echos) * 2,5kg Flocon de blé (Celnat Haute Loire) ## Méthode * MONOPALIER * Empâtage 65.5° : 1h30 * Houblonnage : * Opal 20g Infusion 75mn * Opal 100g 1mn + pendant le transfert * Brewers gold 100g 1mn + pendant le transfert * Houblonnage à cru 7 jours entre 10 et 15° * OPAL 100g * Brewers gold 100g
Java
/* Multiple Lua Programming Language : Intermediate Code Generator * Copyright(C) 2014 Cheryl Natsu * This file is part of multiple - Multiple Paradigm Language Interpreter * multiple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * multiple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "selfcheck.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "multiple_ir.h" #include "multiply.h" #include "multiply_assembler.h" #include "multiply_str_aux.h" #include "multiple_misc.h" #include "multiple_err.h" #include "vm_predef.h" #include "vm_opcode.h" #include "vm_types.h" #include "mlua_lexer.h" #include "mlua_ast.h" #include "mlua_icg.h" #include "mlua_icg_aux.h" #include "mlua_icg_fcb.h" #include "mlua_icg_context.h" #include "mlua_icg_expr.h" #include "mlua_icg_stmt.h" #include "mlua_icg_built_in_proc.h" #include "mlua_icg_built_in_table.h" /* Declaration */ int mlua_icodegen_statement_list(struct multiple_error *err, \ struct mlua_icg_context *context, \ struct mlua_icg_fcb_block *icg_fcb_block, \ struct mlua_map_offset_label_list *map_offset_label_list, \ struct mlua_ast_statement_list *list, \ struct multiply_offset_item_pack *offset_pack_break); static int mlua_icodegen_merge_blocks(struct multiple_error *err, \ struct mlua_icg_context *context) { int ret = 0; struct mlua_icg_fcb_block *icg_fcb_block_cur; struct mlua_icg_fcb_line *icg_fcb_line_cur; uint32_t instrument_number; struct multiple_ir_export_section_item *export_section_item_cur; struct multiple_ir_text_section_item *text_section_item_cur; uint32_t offset_start; uint32_t fcb_size = 0; uint32_t count; /* Do not disturb the instrument produced by other way */ offset_start = (uint32_t)(context->icode->text_section->size); export_section_item_cur = context->icode->export_section->begin; icg_fcb_block_cur = context->icg_fcb_block_list->begin; while (icg_fcb_block_cur != NULL) { icg_fcb_line_cur = icg_fcb_block_cur->begin; /* Record the absolute instrument number */ instrument_number = (uint32_t)context->icode->text_section->size; if (export_section_item_cur == NULL) { MULTIPLE_ERROR_INTERNAL(); ret = -MULTIPLE_ERR_INTERNAL; goto fail; } export_section_item_cur->instrument_number = instrument_number; while (icg_fcb_line_cur != NULL) { switch (icg_fcb_line_cur->type) { case MLUA_ICG_FCB_LINE_TYPE_NORMAL: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_PC: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, instrument_number + icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK: /* Operand of this instrument here is the index number of lambda */ if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; case MLUA_ICG_FCB_LINE_TYPE_BLTIN_PROC_MK: if ((ret = multiply_icodegen_text_section_append(err, \ context->icode, \ icg_fcb_line_cur->opcode, icg_fcb_line_cur->operand)) != 0) { goto fail; } break; } fcb_size += 1; icg_fcb_line_cur = icg_fcb_line_cur->next; } icg_fcb_block_cur = icg_fcb_block_cur->next; export_section_item_cur = export_section_item_cur->next; } /* 2nd pass, dealing with lambdas */ icg_fcb_block_cur = context->icg_fcb_block_list->begin; /* Skip text body of built-in procedures at the beginning part */ text_section_item_cur = context->icode->text_section->begin; while (offset_start-- > 0) { text_section_item_cur = text_section_item_cur->next; } /* Process lambda mks */ while (icg_fcb_block_cur != NULL) { icg_fcb_line_cur = icg_fcb_block_cur->begin; while (icg_fcb_line_cur != NULL) { if (icg_fcb_line_cur->type == MLUA_ICG_FCB_LINE_TYPE_LAMBDA_MK) { /* Locate to the export section item */ count = icg_fcb_line_cur->operand; export_section_item_cur = context->icode->export_section->begin; while ((export_section_item_cur != NULL) && (count != 0)) { count--; export_section_item_cur = export_section_item_cur->next; } if (export_section_item_cur == NULL) { MULTIPLE_ERROR_INTERNAL(); ret = -MULTIPLE_ERR_INTERNAL; goto fail; } text_section_item_cur->operand = export_section_item_cur->instrument_number; } text_section_item_cur = text_section_item_cur->next; icg_fcb_line_cur = icg_fcb_line_cur->next; } icg_fcb_block_cur = icg_fcb_block_cur->next; } goto done; fail: done: return ret; } static int mlua_icodegen_special(struct multiple_error *err, \ struct multiple_ir *icode, \ struct multiply_resource_id_pool *res_id, \ struct mlua_icg_fcb_block_list *icg_fcb_block_list, \ struct mlua_icg_fcb_block *icg_fcb_block, \ const char *name, const size_t name_len) { int ret = 0; uint32_t id; struct multiple_ir_export_section_item *new_export_section_item = NULL; new_export_section_item = multiple_ir_export_section_item_new(); if (new_export_section_item == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_export_section_item->args_count = 0; new_export_section_item->args = NULL; new_export_section_item->args_types = NULL; /* Return */ if ((ret = mlua_icg_fcb_block_append_with_configure(icg_fcb_block, OP_RETNONE, 0)) != 0) { goto fail; } /* Append block */ if ((ret = mlua_icg_fcb_block_list_append(icg_fcb_block_list, icg_fcb_block)) != 0) { MULTIPLE_ERROR_INTERNAL(); goto fail; } /* Append export section item */ if ((ret = multiply_resource_get_id( \ err, \ icode, \ res_id, \ &id, \ name, name_len)) != 0) { goto fail; } new_export_section_item->name = id; new_export_section_item->instrument_number = (uint32_t)icode->export_section->size; multiple_ir_export_section_append(icode->export_section, new_export_section_item); goto done; fail: if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item); done: return ret; } static int mlua_icodegen_program(struct multiple_error *err, \ struct mlua_icg_context *context, \ struct mlua_ast_program *program) { int ret = 0; struct mlua_icg_fcb_block *new_icg_fcb_block_autorun = NULL; struct mlua_map_offset_label_list *new_map_offset_label_list = NULL; uint32_t id; struct multiple_ir_export_section_item *new_export_section_item = NULL; uint32_t instrument_number_insert_point_built_in_proc; uint32_t instrument_count_built_in_proc; new_icg_fcb_block_autorun = mlua_icg_fcb_block_new(); if (new_icg_fcb_block_autorun == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_map_offset_label_list = mlua_map_offset_label_list_new(); if (new_map_offset_label_list == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } new_export_section_item = multiple_ir_export_section_item_new(); if (new_export_section_item == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } /* def in .text section */ if ((ret = multiply_resource_get_id( \ err, \ context->icode, \ context->res_id, \ &id, \ VM_PREDEF_MODULE_AUTORUN, \ VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } if ((ret = mlua_icg_fcb_block_append_with_configure(new_icg_fcb_block_autorun, OP_DEF, id)) != 0) { goto fail; } new_export_section_item->name = id; new_export_section_item->args_count = 0; new_export_section_item->args = NULL; new_export_section_item->args_types = NULL; instrument_number_insert_point_built_in_proc = mlua_icg_fcb_block_get_instrument_number(new_icg_fcb_block_autorun); /* Statements of top level */ if ((ret = mlua_icodegen_statement_list(err, context, \ new_icg_fcb_block_autorun, \ new_map_offset_label_list, \ program->stmts, NULL)) != 0) { goto fail; } /* Apply goto to label */ if ((ret = mlua_icodegen_statement_list_apply_goto(err, \ context, \ new_icg_fcb_block_autorun, \ new_map_offset_label_list)) != 0) { goto fail; } /* Pop a label offset pack */ multiply_offset_item_pack_stack_pop(context->offset_item_pack_stack); /* Put built-in procedures directly into icode, * and put initialize code into '__autorun__' */ if ((ret = mlua_icg_add_built_in_procs(err, \ context->icode, \ context->res_id, \ new_icg_fcb_block_autorun, \ context->customizable_built_in_procedure_list, \ instrument_number_insert_point_built_in_proc, &instrument_count_built_in_proc)) != 0) { goto fail; } /* Put built-in 'tables' directly into icode, * and put initialize code into '__autorun__' */ if ((ret = mlua_icg_add_built_in_tables(err, \ context->icode, \ context->res_id, \ new_icg_fcb_block_autorun, \ context->stdlibs, \ instrument_number_insert_point_built_in_proc, &instrument_count_built_in_proc)) != 0) { goto fail; } /* '__autorun__' subroutine */ if ((ret = mlua_icodegen_special( \ err, \ context->icode, \ context->res_id, \ context->icg_fcb_block_list, new_icg_fcb_block_autorun, \ VM_PREDEF_MODULE_AUTORUN, VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } new_icg_fcb_block_autorun = NULL; /* Append export section item */ if ((ret = multiply_resource_get_id( \ err, \ context->icode, \ context->res_id, \ &id, \ VM_PREDEF_MODULE_AUTORUN, \ VM_PREDEF_MODULE_AUTORUN_LEN)) != 0) { goto fail; } new_export_section_item->name = id; goto done; fail: if (new_icg_fcb_block_autorun != NULL) mlua_icg_fcb_block_destroy(new_icg_fcb_block_autorun); done: if (new_export_section_item != NULL) multiple_ir_export_section_item_destroy(new_export_section_item); if (new_map_offset_label_list != NULL) mlua_map_offset_label_list_destroy(new_map_offset_label_list); return ret; } int mlua_irgen(struct multiple_error *err, \ struct multiple_ir **icode_out, \ struct mlua_ast_program *program, \ int verbose) { int ret = 0; struct mlua_icg_context context; struct mlua_icg_fcb_block_list *new_icg_fcb_block_list = NULL; struct multiple_ir *new_icode = NULL; struct multiply_resource_id_pool *new_res_id = NULL; struct mlua_icg_customizable_built_in_procedure_list *new_customizable_built_in_procedure_list = NULL; struct multiply_offset_item_pack_stack *new_offset_item_pack_stack = NULL; struct mlua_icg_stdlib_table_list *new_table_list = NULL; (void)verbose; if ((new_customizable_built_in_procedure_list = mlua_icg_customizable_built_in_procedure_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_icg_fcb_block_list = mlua_icg_fcb_block_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_offset_item_pack_stack = multiply_offset_item_pack_stack_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_table_list = mlua_icg_stdlib_table_list_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_icode = multiple_ir_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } if ((new_res_id = multiply_resource_id_pool_new()) == NULL) { MULTIPLE_ERROR_MALLOC(); ret = -MULTIPLE_ERR_MALLOC; goto fail; } mlua_icg_context_init(&context); context.icg_fcb_block_list = new_icg_fcb_block_list; context.icode = new_icode; context.res_id = new_res_id; context.customizable_built_in_procedure_list = new_customizable_built_in_procedure_list; context.offset_item_pack_stack = new_offset_item_pack_stack; context.stdlibs = new_table_list; /* Generating icode for '__init__' */ if ((ret = mlua_icodegen_program(err, \ &context, \ program)) != 0) { goto fail; } /* Merge blocks */ if ((ret = mlua_icodegen_merge_blocks(err, \ &context)) != 0) { goto fail; } *icode_out = new_icode; ret = 0; goto done; fail: if (new_icode != NULL) multiple_ir_destroy(new_icode); done: if (new_res_id != NULL) multiply_resource_id_pool_destroy(new_res_id); if (new_icg_fcb_block_list != NULL) mlua_icg_fcb_block_list_destroy(new_icg_fcb_block_list); if (new_customizable_built_in_procedure_list != NULL) \ { mlua_icg_customizable_built_in_procedure_list_destroy(new_customizable_built_in_procedure_list); } if (new_offset_item_pack_stack != NULL) { multiply_offset_item_pack_stack_destroy(new_offset_item_pack_stack); } if (new_table_list != NULL) { mlua_icg_stdlib_table_list_destroy(new_table_list); } return ret; }
Java
package de.jotschi.geo.osm.tags; import org.w3c.dom.Node; public class OsmMember { String type, ref, role; public OsmMember(Node node) { ref = node.getAttributes().getNamedItem("ref").getNodeValue(); role = node.getAttributes().getNamedItem("role").getNodeValue(); type = node.getAttributes().getNamedItem("type").getNodeValue(); } public String getType() { return type; } public String getRef() { return ref; } public String getRole() { return role; } }
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Library\CommandLine\AbstractCommandLineController | Library</title> <link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="../../css/sami.css"> <script src="../../js/jquery-1.11.1.min.js"></script> <script src="../../js/bootstrap.min.js"></script> <script src="../../js/typeahead.min.js"></script> <script src="../../sami.js"></script> <meta name="MobileOptimized" content="width"> <meta name="HandheldFriendly" content="true"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"> </head> <body id="class" data-name="class:Library_CommandLine_AbstractCommandLineController" data-root-path="../../"> <div id="content"> <div id="left-column"> <div id="control-panel"> <form id="search-form" action="../../search.html" method="GET"> <span class="glyphicon glyphicon-search"></span> <input name="search" class="typeahead form-control" type="search" placeholder="Search"> </form> </div> <div id="api-tree"></div> </div> <div id="right-column"> <nav id="site-nav" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../index.html">Library</a> </div> <div class="collapse navbar-collapse" id="navbar-elements"> <ul class="nav navbar-nav"> <li><a href="../../classes.html">Classes</a></li> <li><a href="../../namespaces.html">Namespaces</a></li> <li><a href="../../interfaces.html">Interfaces</a></li> <li><a href="../../traits.html">Traits</a></li> <li><a href="../../doc-index.html">Index</a></li> <li><a href="../../search.html">Search</a></li> </ul> </div> </div> </nav> <div class="namespace-breadcrumbs"> <ol class="breadcrumb"> <li><span class="label label-default">class</span></li> <li><a href="../../Library.html">Library</a></li> <li><a href="../../Library/CommandLine.html">CommandLine</a></li> <li>AbstractCommandLineController</li> </ol> </div> <div id="page-content"> <div class="page-header"> <h1>AbstractCommandLineController</h1> </div> <p> class <strong>AbstractCommandLineController</strong> implements <a href="../../Library/CommandLine/CommandLineControllerInterface.html"><abbr title="Library\CommandLine\CommandLineControllerInterface">CommandLineControllerInterface</abbr></a> </p> <div class="description"> <p>Basic command line controller</p> <p>Any command line controller must extend this abstract class.</p> <p>It defines some basic command line options that you must not overwrite in your child class:</p> <ul> <li>"h | help" : get a usage information,</li> <li>"v | verbose" : increase verbosity of the execution (written strings must be handled in your scripts),</li> <li>"x | debug" : execute the script in "debug" mode (must write actions before executing them),</li> <li>"q | quiet" : turn verbosity totally off during the execution (only errors and informations will be written),</li> <li>"f | force" : force some actions (avoid interactions),</li> <li>"i | interactive" : increase interactivity of the execution,</li> <li>"version" : get some version information about running environment.</li> </ul> </p> </div> <h2>Properties</h2> <table class="table table-condensed"> <tr> <td class="type" id="property__name"> static string </td> <td>$_name</td> <td class="last">This must be over-written in any child class</td> <td></td> </tr> <tr> <td class="type" id="property__version"> static string </td> <td>$_version</td> <td class="last">This must be over-written in any child class</td> <td></td> </tr> </table> <h2>Methods</h2> <div class="container-fluid underlined"> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method___construct">__construct</a>( array $options = array()) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method___toString">__toString</a>() <p>Magic distribution when printing object</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_distribute">distribute</a>() <p>Distribution of the work</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <a href="../../Library/CommandLine/AbstractCommandLineController.html"><abbr title="Library\CommandLine\AbstractCommandLineController">AbstractCommandLineController</abbr></a> </div> <div class="col-md-8 type"> <a href="#method_setDebug">setDebug</a>( bool $dbg = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setVerbose">setVerbose</a>( bool $vbr = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setForce">setForce</a>( bool $frc = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setInteractive">setInteractive</a>( bool $frc = true) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_setQuiet">setQuiet</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_addDoneMethod">addDoneMethod</a>( string $_cls_meth) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> array </div> <div class="col-md-8 type"> <a href="#method_getDoneMethods">getDoneMethods</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_setScript">setScript</a>( string $script_name) <p>Set the current command line script called</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string|null </div> <div class="col-md-8 type"> <a href="#method_getScript">getScript</a>() <p>Get the current command line script called</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_setParameters">setParameters</a>( array $params) <p>Set the command line parameters</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> array </div> <div class="col-md-8 type"> <a href="#method_getParameters">getParameters</a>() <p>Get the parameters collection</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runHelpCommand">runHelpCommand</a>($opt = null) <p>List of all options and features of the command line tool ; for some commands, a specific help can be available, running <var>--command --help</var> Some command examples are purposed running <var>--console --help</var></p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runVerboseCommand">runVerboseCommand</a>() <p>Run the command line in <bold>verbose</bold> mode, writing some information on screen (default is <option>OFF</option>)</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runQuietCommand">runQuietCommand</a>() <p>Run the command line in <bold>quiet</bold> mode, trying to not write anything on screen (default is <option>OFF</option>)</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runDebugCommand">runDebugCommand</a>() <p>Run the command line in <bold>debug</bold> mode, writing some scripts information during runtime (default is <option>OFF</option>)</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runForceCommand">runForceCommand</a>() <p>Run the command line in <bold>forced</bold> mode ; any choice will be set on default value if so</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runInteractiveCommand">runInteractiveCommand</a>() <p>Run the command line in <bold>interactive</bold> mode ; any choice will be prompted if possible</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runVersionCommand">runVersionCommand</a>() <p>Get versions of system environment</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_write">write</a>( null $str = null, bool $new_line = true) <p>Format and write a string to STDOUT</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_error">error</a>( null $str = null, int $status = 1, bool $new_line = true) <p>Format and write an error message to STDOUT (or STDERR) and exits with status <code>$status</code></p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_parseAndWrite">parseAndWrite</a>( string $str, null $type = null, bool $spaced = false) <p>Parse, format and write a message to STDOUT</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeError">writeError</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeThinError">writeThinError</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeInfo">writeInfo</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeComment">writeComment</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeHighlight">writeHighlight</a>( string $str) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeBreak">writeBreak</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_writeStop">writeStop</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_verboseWrite">verboseWrite</a>( null $str = null, bool $new_line = true) <p>Write a string only in verbose mode</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> <abbr title="Library\CommandLine\$this">$this</abbr> </div> <div class="col-md-8 type"> <a href="#method_debugWrite">debugWrite</a>( null $str = null, bool $new_line = true) <p>Write a string only in debug mode</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method_prompt">prompt</a>( string|null $str = null, mixed|null $default = null) <p>Prompt user input</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> string </div> <div class="col-md-8 type"> <a href="#method_getPrompt">getPrompt</a>() <p>Get last user input</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_writeIntro">writeIntro</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getVersionString">getVersionString</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_writeNothingToDo">writeNothingToDo</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_runArgumentHelp">runArgumentHelp</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_usage">usage</a>($opt = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getopt">getopt</a>() <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getOptionMethod">getOptionMethod</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getOptionDescription">getOptionDescription</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> <div class="row"> <div class="col-md-2 type"> </div> <div class="col-md-8 type"> <a href="#method_getOptionHelp">getOptionHelp</a>($arg = null) <p class="no-description">No description</p> </div> <div class="col-md-2"></div> </div> </div> <h2>Details</h2> <div id="method-details"> <div class="method-item"> <h3 id="method___construct"> <div class="location">at line 175</div> <code> <strong>__construct</strong>( array $options = array())</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> array</td> <td>$options</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method___toString"> <div class="location">at line 219</div> <code> string <strong>__toString</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Magic distribution when printing object</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_distribute"> <div class="location">at line 228</div> <code> <strong>distribute</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Distribution of the work</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_setDebug"> <div class="location">at line 248</div> <code> <a href="../../Library/CommandLine/AbstractCommandLineController.html"><abbr title="Library\CommandLine\AbstractCommandLineController">AbstractCommandLineController</abbr></a> <strong>setDebug</strong>( bool $dbg = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$dbg</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <a href="../../Library/CommandLine/AbstractCommandLineController.html"><abbr title="Library\CommandLine\AbstractCommandLineController">AbstractCommandLineController</abbr></a></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setVerbose"> <div class="location">at line 259</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setVerbose</strong>( bool $vbr = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$vbr</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setForce"> <div class="location">at line 269</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setForce</strong>( bool $frc = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$frc</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setInteractive"> <div class="location">at line 279</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setInteractive</strong>( bool $frc = true)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> bool</td> <td>$frc</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setQuiet"> <div class="location">at line 290</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>setQuiet</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> <h4>See also</h4> <table class="table table-condensed"> <tr> <td>self::setVerbose()</td> <td></td> </tr> <tr> <td>self::setDebug()</td> <td></td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_addDoneMethod"> <div class="location">at line 301</div> <code> <strong>addDoneMethod</strong>( string $_cls_meth)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$_cls_meth</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getDoneMethods"> <div class="location">at line 310</div> <code> array <strong>getDoneMethods</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> array</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setScript"> <div class="location">at line 321</div> <code> <strong>setScript</strong>( string $script_name)</code> </h3> <div class="details"> <div class="method-description"> <p>Set the current command line script called</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$script_name</td> <td>The script name</td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getScript"> <div class="location">at line 332</div> <code> string|null <strong>getScript</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get the current command line script called</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string|null</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_setParameters"> <div class="location">at line 343</div> <code> <strong>setParameters</strong>( array $params)</code> </h3> <div class="details"> <div class="method-description"> <p>Set the command line parameters</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> array</td> <td>$params</td> <td>The collection of parameters</td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getParameters"> <div class="location">at line 354</div> <code> array <strong>getParameters</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get the parameters collection</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> array</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_runHelpCommand"> <div class="location">at line 368</div> <code> <strong>runHelpCommand</strong>($opt = null)</code> </h3> <div class="details"> <div class="method-description"> <p>List of all options and features of the command line tool ; for some commands, a specific help can be available, running <var>--command --help</var> Some command examples are purposed running <var>--console --help</var></p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$opt</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_runVerboseCommand"> <div class="location">at line 391</div> <code> <strong>runVerboseCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>verbose</bold> mode, writing some information on screen (default is <option>OFF</option>)</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runQuietCommand"> <div class="location">at line 399</div> <code> <strong>runQuietCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>quiet</bold> mode, trying to not write anything on screen (default is <option>OFF</option>)</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runDebugCommand"> <div class="location">at line 407</div> <code> <strong>runDebugCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>debug</bold> mode, writing some scripts information during runtime (default is <option>OFF</option>)</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runForceCommand"> <div class="location">at line 415</div> <code> <strong>runForceCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>forced</bold> mode ; any choice will be set on default value if so</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runInteractiveCommand"> <div class="location">at line 423</div> <code> <strong>runInteractiveCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Run the command line in <bold>interactive</bold> mode ; any choice will be prompted if possible</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runVersionCommand"> <div class="location">at line 431</div> <code> <strong>runVersionCommand</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get versions of system environment</p> </div> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_write"> <div class="location">at line 460</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>write</strong>( null $str = null, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Format and write a string to STDOUT</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_error"> <div class="location">at line 474</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>error</strong>( null $str = null, int $status = 1, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Format and write an error message to STDOUT (or STDERR) and exits with status <code>$status</code></p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> int</td> <td>$status</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_parseAndWrite"> <div class="location">at line 488</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>parseAndWrite</strong>( string $str, null $type = null, bool $spaced = false)</code> </h3> <div class="details"> <div class="method-description"> <p>Parse, format and write a message to STDOUT</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> <tr> <td> null</td> <td>$type</td> <td> </td> </tr> <tr> <td> bool</td> <td>$spaced</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeError"> <div class="location">at line 503</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeError</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeThinError"> <div class="location">at line 514</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeThinError</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeInfo"> <div class="location">at line 526</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeInfo</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeComment"> <div class="location">at line 536</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeComment</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeHighlight"> <div class="location">at line 547</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeHighlight</strong>( string $str)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string</td> <td>$str</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeBreak"> <div class="location">at line 556</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeBreak</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeStop"> <div class="location">at line 565</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>writeStop</strong>()</code> </h3> <div class="details"> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_verboseWrite"> <div class="location">at line 585</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>verboseWrite</strong>( null $str = null, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Write a string only in verbose mode</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_debugWrite"> <div class="location">at line 598</div> <code> <abbr title="Library\CommandLine\$this">$this</abbr> <strong>debugWrite</strong>( null $str = null, bool $new_line = true)</code> </h3> <div class="details"> <div class="method-description"> <p>Write a string only in debug mode</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> null</td> <td>$str</td> <td> </td> </tr> <tr> <td> bool</td> <td>$new_line</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> <abbr title="Library\CommandLine\$this">$this</abbr></td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_prompt"> <div class="location">at line 611</div> <code> string <strong>prompt</strong>( string|null $str = null, mixed|null $default = null)</code> </h3> <div class="details"> <div class="method-description"> <p>Prompt user input</p> </div> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td> string|null</td> <td>$str</td> <td> </td> </tr> <tr> <td> mixed|null</td> <td>$default</td> <td> </td> </tr> </table> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getPrompt"> <div class="location">at line 624</div> <code> string <strong>getPrompt</strong>()</code> </h3> <div class="details"> <div class="method-description"> <p>Get last user input</p> </div> <div class="tags"> <h4>Return Value</h4> <table class="table table-condensed"> <tr> <td> string</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_writeIntro"> <div class="location">at line 641</div> <code> <strong>writeIntro</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_getVersionString"> <div class="location">at line 651</div> <code> <strong>getVersionString</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_writeNothingToDo"> <div class="location">at line 664</div> <code> <strong>writeNothingToDo</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_runArgumentHelp"> <div class="location">at line 671</div> <code> <strong>runArgumentHelp</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_usage"> <div class="location">at line 684</div> <code> <strong>usage</strong>($opt = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$opt</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getopt"> <div class="location">at line 788</div> <code> <strong>getopt</strong>()</code> </h3> <div class="details"> <div class="tags"> </div> </div> </div> <div class="method-item"> <h3 id="method_getOptionMethod"> <div class="location">at line 795</div> <code> <strong>getOptionMethod</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getOptionDescription"> <div class="location">at line 802</div> <code> <strong>getOptionDescription</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> <div class="method-item"> <h3 id="method_getOptionHelp"> <div class="location">at line 807</div> <code> <strong>getOptionHelp</strong>($arg = null)</code> </h3> <div class="details"> <div class="tags"> <h4>Parameters</h4> <table class="table table-condensed"> <tr> <td></td> <td>$arg</td> <td> </td> </tr> </table> </div> </div> </div> </div> </div> <div id="footer"> Generated by <a href="http://sami.sensiolabs.org/">Sami, the API Documentation Generator</a>. </div> </div> </div> </body> </html>
Java
/********************* * bio_tune_menu.cpp * *********************/ /**************************************************************************** * Written By Mark Pelletier 2017 - Aleph Objects, Inc. * * Written By Marcio Teixeira 2018 - Aleph Objects, Inc. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * To view a copy of the GNU General Public License, go to the following * * location: <http://www.gnu.org/licenses/>. * ****************************************************************************/ #include "../config.h" #if ENABLED(TOUCH_UI_FTDI_EVE) && defined(TOUCH_UI_LULZBOT_BIO) #include "screens.h" using namespace FTDI; using namespace Theme; using namespace ExtUI; void TuneMenu::onRedraw(draw_mode_t what) { #define GRID_ROWS 8 #define GRID_COLS 2 if (what & BACKGROUND) { CommandProcessor cmd; cmd.cmd(CLEAR_COLOR_RGB(bg_color)) .cmd(CLEAR(true,true,true)) .cmd(COLOR_RGB(bg_text_enabled)) .tag(0) .font(font_large) .text( BTN_POS(1,1), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_MENU)); } if (what & FOREGROUND) { CommandProcessor cmd; cmd.colors(normal_btn) .font(font_medium) .enabled( isPrinting()).tag(2).button( BTN_POS(1,2), BTN_SIZE(2,1), GET_TEXT_F(MSG_PRINT_SPEED)) .tag(3).button( BTN_POS(1,3), BTN_SIZE(2,1), GET_TEXT_F(MSG_BED_TEMPERATURE)) .enabled(TERN_(BABYSTEPPING, true)) .tag(4).button( BTN_POS(1,4), BTN_SIZE(2,1), GET_TEXT_F(MSG_NUDGE_NOZZLE)) .enabled(!isPrinting()).tag(5).button( BTN_POS(1,5), BTN_SIZE(2,1), GET_TEXT_F(MSG_MOVE_TO_HOME)) .enabled(!isPrinting()).tag(6).button( BTN_POS(1,6), BTN_SIZE(2,1), GET_TEXT_F(MSG_RAISE_PLUNGER)) .enabled(!isPrinting()).tag(7).button( BTN_POS(1,7), BTN_SIZE(2,1), GET_TEXT_F(MSG_RELEASE_XY_AXIS)) .colors(action_btn) .tag(1).button( BTN_POS(1,8), BTN_SIZE(2,1), GET_TEXT_F(MSG_BACK)); } #undef GRID_COLS #undef GRID_ROWS } bool TuneMenu::onTouchEnd(uint8_t tag) { switch (tag) { case 1: GOTO_PREVIOUS(); break; case 2: GOTO_SCREEN(FeedratePercentScreen); break; case 3: GOTO_SCREEN(TemperatureScreen); break; case 4: GOTO_SCREEN(NudgeNozzleScreen); break; case 5: GOTO_SCREEN(BioConfirmHomeXYZ); break; case 6: SpinnerDialogBox::enqueueAndWait_P(F("G0 E0 F120")); break; case 7: StatusScreen::unlockMotors(); break; default: return false; } return true; } #endif // TOUCH_UI_FTDI_EVE
Java
/* * Copyright (C) 2006-2010 - Frictional Games * * This file is part of HPL1 Engine. * * HPL1 Engine is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HPL1 Engine is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HPL1 Engine. If not, see <http://www.gnu.org/licenses/>. */ #include "scene/Entity3D.h" #include "scene/Node3D.h" #include "math/Math.h" #include "graphics/RenderList.h" #include "system/LowLevelSystem.h" #include "scene/PortalContainer.h" namespace hpl { ////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- iEntity3D::iEntity3D(tString asName) : iEntity(asName) { m_mtxLocalTransform = cMatrixf::Identity; m_mtxWorldTransform = cMatrixf::Identity; mbTransformUpdated = true; mlCount = 0; mlGlobalRenderCount = cRenderList::GetGlobalRenderCount(); msSourceFile = ""; mbApplyTransformToBV = true; mbUpdateBoundingVolume = true; mpParent = NULL; mlIteratorCount =-1; mpCurrentSector = NULL; } iEntity3D::~iEntity3D() { if(mpParent) mpParent->RemoveChild(this); for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it) { iEntity3D *pChild = *it; pChild->mpParent = NULL; } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PUBLIC METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- cVector3f iEntity3D::GetLocalPosition() { return m_mtxLocalTransform.GetTranslation(); } //----------------------------------------------------------------------- cMatrixf& iEntity3D::GetLocalMatrix() { return m_mtxLocalTransform; } //----------------------------------------------------------------------- cVector3f iEntity3D::GetWorldPosition() { UpdateWorldTransform(); return m_mtxWorldTransform.GetTranslation(); } //----------------------------------------------------------------------- cMatrixf& iEntity3D::GetWorldMatrix() { UpdateWorldTransform(); return m_mtxWorldTransform; } //----------------------------------------------------------------------- void iEntity3D::SetPosition(const cVector3f& avPos) { m_mtxLocalTransform.m[0][3] = avPos.x; m_mtxLocalTransform.m[1][3] = avPos.y; m_mtxLocalTransform.m[2][3] = avPos.z; SetTransformUpdated(); } //----------------------------------------------------------------------- void iEntity3D::SetMatrix(const cMatrixf& a_mtxTransform) { m_mtxLocalTransform = a_mtxTransform; SetTransformUpdated(); } //----------------------------------------------------------------------- void iEntity3D::SetWorldPosition(const cVector3f& avWorldPos) { if(mpParent) { SetPosition(avWorldPos - mpParent->GetWorldPosition()); } else { SetPosition(avWorldPos); } } //----------------------------------------------------------------------- void iEntity3D::SetWorldMatrix(const cMatrixf& a_mtxWorldTransform) { if(mpParent) { SetMatrix(cMath::MatrixMul(cMath::MatrixInverse(mpParent->GetWorldMatrix()), a_mtxWorldTransform)); } else { SetMatrix(a_mtxWorldTransform); } } //----------------------------------------------------------------------- void iEntity3D::SetTransformUpdated(bool abUpdateCallbacks) { mbTransformUpdated = true; mlCount++; //Perhaps not update this yet? This is baaaad! if(mbApplyTransformToBV) mBoundingVolume.SetTransform(GetWorldMatrix()); mbUpdateBoundingVolume = true; //Update children for(tEntity3DListIt EntIt = mlstChildren.begin(); EntIt != mlstChildren.end();++EntIt) { iEntity3D *pChild = *EntIt; pChild->SetTransformUpdated(true); } //Update callbacks if(mlstCallbacks.empty() || abUpdateCallbacks==false) return; tEntityCallbackListIt it = mlstCallbacks.begin(); for(; it!= mlstCallbacks.end(); ++it) { iEntityCallback* pCallback = *it; pCallback->OnTransformUpdate(this); } } //----------------------------------------------------------------------- bool iEntity3D::GetTransformUpdated() { return mbTransformUpdated; } //----------------------------------------------------------------------- int iEntity3D::GetTransformUpdateCount() { return mlCount; } //----------------------------------------------------------------------- void iEntity3D::AddCallback(iEntityCallback *apCallback) { mlstCallbacks.push_back(apCallback); } //----------------------------------------------------------------------- void iEntity3D::RemoveCallback(iEntityCallback *apCallback) { STLFindAndDelete(mlstCallbacks, apCallback); } //----------------------------------------------------------------------- void iEntity3D::AddChild(iEntity3D *apEntity) { if(apEntity==NULL)return; if(apEntity->mpParent != NULL) return; mlstChildren.push_back(apEntity); apEntity->mpParent = this; apEntity->SetTransformUpdated(true); } void iEntity3D::RemoveChild(iEntity3D *apEntity) { for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();) { iEntity3D *pChild = *it; if(pChild == apEntity) { pChild->mpParent = NULL; it = mlstChildren.erase(it); } else { ++it; } } } bool iEntity3D::IsChild(iEntity3D *apEntity) { for(tEntity3DListIt it = mlstChildren.begin(); it != mlstChildren.end();++it) { iEntity3D *pChild = *it; if(pChild == apEntity) return true; } return false; } iEntity3D * iEntity3D::GetEntityParent() { return mpParent; } //----------------------------------------------------------------------- bool iEntity3D::IsInSector(cSector *apSector) { //Log("-- %s --\n",msName.c_str()); //bool bShouldReturnTrue = false; if(apSector == GetCurrentSector()) { //Log("Should return true\n"); //bShouldReturnTrue = true; return true; } tRenderContainerDataList *pDataList = GetRenderContainerDataList(); tRenderContainerDataListIt it = pDataList->begin(); for(; it != pDataList->end(); ++it) { iRenderContainerData *pRenderContainerData = *it; cSector *pSector = static_cast<cSector*>(pRenderContainerData); //Log("%s (%d) vs %s (%d)\n",pSector->GetId().c_str(),pSector, apSector->GetId().c_str(),apSector); if(pSector == apSector) { //Log("return true!\n"); return true; } } //if(bShouldReturnTrue)Log(" %s should have returned true. Sectors: %d\n",msName.c_str(), mlstRenderContainerData.size()); //Log("return false!\n"); return false; } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // PRIVATE METHODS ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- void iEntity3D::UpdateWorldTransform() { if(mbTransformUpdated) { mbTransformUpdated = false; //first check if there is a node parent if(mpParentNode) { cNode3D* pNode3D = static_cast<cNode3D*>(mpParentNode); m_mtxWorldTransform = cMath::MatrixMul(pNode3D->GetWorldMatrix(), m_mtxLocalTransform); } //If there is no node parent check for entity parent else if(mpParent) { m_mtxWorldTransform = cMath::MatrixMul(mpParent->GetWorldMatrix(), m_mtxLocalTransform); } else { m_mtxWorldTransform = m_mtxLocalTransform; } } } //----------------------------------------------------------------------- ////////////////////////////////////////////////////////////////////////// // SAVE OBJECT STUFF ////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------- kBeginSerializeVirtual(cSaveData_iEntity3D,cSaveData_iEntity) kSerializeVar(m_mtxLocalTransform,eSerializeType_Matrixf) kSerializeVar(mBoundingVolume,eSerializeType_Class) kSerializeVar(msSourceFile,eSerializeType_String) kSerializeVar(mlParentId,eSerializeType_Int32) kSerializeVarContainer(mlstChildren,eSerializeType_Int32) kEndSerialize() //----------------------------------------------------------------------- iSaveData* iEntity3D::CreateSaveData() { return NULL; } //----------------------------------------------------------------------- void iEntity3D::SaveToSaveData(iSaveData *apSaveData) { kSaveData_SaveToBegin(iEntity3D); //Log("-------- Saving %s --------------\n",msName.c_str()); kSaveData_SaveTo(m_mtxLocalTransform); kSaveData_SaveTo(mBoundingVolume); kSaveData_SaveTo(msSourceFile); kSaveData_SaveObject(mpParent,mlParentId); kSaveData_SaveIdList(mlstChildren,tEntity3DListIt,mlstChildren); /*if(mlstChildren.empty()==false) { Log("Children in '%s'/'%s': ",msName.c_str(),GetEntityType().c_str()); for(tEntity3DListIt it=mlstChildren.begin(); it != mlstChildren.end(); ++it) { iEntity3D *pEntity = *it; Log("('%d/%s'/'%s'), ",pEntity->GetSaveObjectId(),pEntity->GetName().c_str(),pEntity->GetEntityType().c_str()); } Log("\n"); }*/ } //----------------------------------------------------------------------- void iEntity3D::LoadFromSaveData(iSaveData *apSaveData) { kSaveData_LoadFromBegin(iEntity3D); //Log("-------- Loading %s --------------\n",msName.c_str()); SetMatrix(pData->m_mtxLocalTransform); //Not sure of this is needed: kSaveData_LoadFrom(mBoundingVolume); kSaveData_LoadFrom(msSourceFile); } //----------------------------------------------------------------------- void iEntity3D::SaveDataSetup(cSaveObjectHandler *apSaveObjectHandler, cGame *apGame) { kSaveData_SetupBegin(iEntity3D); //Log("-------- Setup %s --------------\n",msName.c_str()); //kSaveData_LoadObject(mpParent,mlParentId,iEntity3D*); //kSaveData_LoadIdList(mlstChildren,mlstChildren,iEntity3D*); if(pData->mlParentId!=-1 && mpParent == NULL) { iEntity3D *pParentEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(pData->mlParentId)); if(pParentEntity) pParentEntity->AddChild(this); else Error("Couldn't find parent entity id %d for '%s'\n",pData->mlParentId,GetName().c_str()); } cContainerListIterator<int> it = pData->mlstChildren.GetIterator(); while(it.HasNext()) { int mlId = it.Next(); if(mlId != -1) { iEntity3D *pChildEntity = static_cast<iEntity3D*>(apSaveObjectHandler->Get(mlId)); if(pChildEntity) AddChild(pChildEntity); else Error("Couldn't find child entity id %d for '%s'\n",mlId,GetName().c_str()); } } SetTransformUpdated(true); } //----------------------------------------------------------------------- }
Java
from feeluown.utils.dispatch import Signal from feeluown.gui.widgets.my_music import MyMusicModel class MyMusicItem(object): def __init__(self, text): self.text = text self.clicked = Signal() class MyMusicUiManager: """ .. note:: 目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。 我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic 的上下文。 而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。 """ def __init__(self, app): self._app = app self._items = [] self.model = MyMusicModel(app) @classmethod def create_item(cls, text): return MyMusicItem(text) def add_item(self, item): self.model.add(item) self._items.append(item) def clear(self): self._items.clear() self.model.clear()
Java
(function() { var app = angular.module('article-directive', ['ui.bootstrap.contextMenu']); app.config(function($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }); app.directive('article', function () { var controller = function () { var vm = this; }; var getSelectionText = function() { if(window.getSelection) { return window.getSelection().toString(); } if(document.selection && document.selection.type != "Control") { return document.selection.createRange().text; } return ""; }; var link = function link(scope, element, attrs) { scope.toggleComments = function () { scope.$broadcast("event:toggle"); } scope.menuOptions = [['Copy', function ($itemScope) { }], null, // Dividier ['Comment', function ($itemScope) { scope.toggleComments(); }]]; }; return { restrict: 'EA', //Default for 1.3+ scope: { text: '@text', url: '@url' }, controller: controller, link: link, controllerAs: 'vm', bindToController: true, //required in 1.3+ with controllerAs templateUrl: '/article/article.html' }; }); }());
Java
/******************************************************************************* * This file is part of RedReader. * * RedReader is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RedReader is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with RedReader. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.quantumbadger.redreader.io; import org.quantumbadger.redreader.common.collections.WeakReferenceListManager; public class UpdatedVersionListenerNotifier<K, V extends WritableObject<K>> implements WeakReferenceListManager.ArgOperator<UpdatedVersionListener<K, V>, V> { @Override public void operate(final UpdatedVersionListener<K, V> listener, final V data) { listener.onUpdatedVersion(data); } }
Java
<?php /** * Copyright 2013 Android Holo Colors by Jérôme Van Der Linden * Copyright 2010 Android Asset Studio by Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ require_once('common-fastscroll.php'); $color = $_GET['color']; $size = $_GET['size']; $holo = $_GET['holo']; $component = $_GET['component']; if (isset($color) && isset($size) && isset($holo) && isset($component)) { switch ($component) { case "fastscroll": $et = new Fastscroll(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; case "fastscroll-pressed": $et = new FastscrollPressed(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; default: $et = new Fastscroll(HOLO_COLORS_COMPONENTS_PATH.'/fastscroll/'); break; } $et->generate_image($color, $size, $holo); } ?>
Java
# Only run if this is an interactive text bash session if [ -n "$PS1" ] && [ -n "$BASH_VERSION" ] && [ -z "$DISPLAY" ]; then echo "Press enter to activate this console" read answer # The user should have chosen their preferred keyboard layout # in tails-greeter by now. . /etc/default/locale . /etc/default/keyboard sudo setupcon fi
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_131) on Sat Oct 28 21:24:43 CEST 2017 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class nxt.util.MiningPlot (burstcoin 1.3.6cg API)</title> <meta name="date" content="2017-10-28"> <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="Uses of Class nxt.util.MiningPlot (burstcoin 1.3.6cg API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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><a href="../package-summary.html">Package</a></li> <li><a href="../../../nxt/util/MiningPlot.html" title="class in nxt.util">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-all.html">Index</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?nxt/util/class-use/MiningPlot.html" target="_top">Frames</a></li> <li><a href="MiningPlot.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class nxt.util.MiningPlot" class="title">Uses of Class<br>nxt.util.MiningPlot</h2> </div> <div class="classUseContainer">No usage of nxt.util.MiningPlot</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <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><a href="../package-summary.html">Package</a></li> <li><a href="../../../nxt/util/MiningPlot.html" title="class in nxt.util">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-all.html">Index</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?nxt/util/class-use/MiningPlot.html" target="_top">Frames</a></li> <li><a href="MiningPlot.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2017. All rights reserved.</small></p> </body> </html>
Java
/* * This file is protected by Copyright. Please refer to the COPYRIGHT file * distributed with this source distribution. * * This file is part of GNUHAWK. * * GNUHAWK is free software: you can redistribute it and/or modify is under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see http://www.gnu.org/licenses/. */ #include "streams_to_stream_ff_1i_base.h" /******************************************************************************************* AUTO-GENERATED CODE. DO NOT MODIFY The following class functions are for the base class for the component class. To customize any of these functions, do not modify them here. Instead, overload them on the child class ******************************************************************************************/ streams_to_stream_ff_1i_base::streams_to_stream_ff_1i_base(const char *uuid, const char *label) : GnuHawkBlock(uuid, label), serviceThread(0), noutput_items(0), _maintainTimeStamp(false), _throttle(false) { construct(); } void streams_to_stream_ff_1i_base::construct() { Resource_impl::_started = false; loadProperties(); serviceThread = 0; sentEOS = false; inputPortOrder.resize(0);; outputPortOrder.resize(0); PortableServer::ObjectId_var oid; float_in = new bulkio::InFloatPort("float_in"); float_in->setNewStreamListener(this, &streams_to_stream_ff_1i_base::float_in_newStreamCallback); oid = ossie::corba::RootPOA()->activate_object(float_in); float_out = new bulkio::OutFloatPort("float_out"); oid = ossie::corba::RootPOA()->activate_object(float_out); registerInPort(float_in); inputPortOrder.push_back("float_in"); registerOutPort(float_out, float_out->_this()); outputPortOrder.push_back("float_out"); } /******************************************************************************************* Framework-level functions These functions are generally called by the framework to perform housekeeping. *******************************************************************************************/ void streams_to_stream_ff_1i_base::initialize() throw (CF::LifeCycle::InitializeError, CORBA::SystemException) { } void streams_to_stream_ff_1i_base::start() throw (CORBA::SystemException, CF::Resource::StartError) { boost::mutex::scoped_lock lock(serviceThreadLock); if (serviceThread == 0) { float_in->unblock(); serviceThread = new ProcessThread<streams_to_stream_ff_1i_base>(this, 0.1); serviceThread->start(); } if (!Resource_impl::started()) { Resource_impl::start(); } } void streams_to_stream_ff_1i_base::stop() throw (CORBA::SystemException, CF::Resource::StopError) { if ( float_in ) float_in->block(); { boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.clear(); } // release the child thread (if it exists) if (serviceThread != 0) { { boost::mutex::scoped_lock lock(serviceThreadLock); LOG_TRACE( streams_to_stream_ff_1i_base, "Stopping Service Function" ); serviceThread->stop(); } if ( !serviceThread->release()) { throw CF::Resource::StopError(CF::CF_NOTSET, "Processing thread did not die"); } boost::mutex::scoped_lock lock(serviceThreadLock); if ( serviceThread ) { delete serviceThread; } } serviceThread = 0; if (Resource_impl::started()) { Resource_impl::stop(); } LOG_TRACE( streams_to_stream_ff_1i_base, "COMPLETED STOP REQUEST" ); } CORBA::Object_ptr streams_to_stream_ff_1i_base::getPort(const char* _id) throw (CORBA::SystemException, CF::PortSupplier::UnknownPort) { std::map<std::string, Port_Provides_base_impl *>::iterator p_in = inPorts.find(std::string(_id)); if (p_in != inPorts.end()) { if (!strcmp(_id,"float_in")) { bulkio::InFloatPort *ptr = dynamic_cast<bulkio::InFloatPort *>(p_in->second); if (ptr) { return ptr->_this(); } } } std::map<std::string, CF::Port_var>::iterator p_out = outPorts_var.find(std::string(_id)); if (p_out != outPorts_var.end()) { return CF::Port::_duplicate(p_out->second); } throw (CF::PortSupplier::UnknownPort()); } void streams_to_stream_ff_1i_base::releaseObject() throw (CORBA::SystemException, CF::LifeCycle::ReleaseError) { // This function clears the component running condition so main shuts down everything try { stop(); } catch (CF::Resource::StopError& ex) { // TODO - this should probably be logged instead of ignored } // deactivate ports releaseInPorts(); releaseOutPorts(); delete(float_in); delete(float_out); Resource_impl::releaseObject(); } void streams_to_stream_ff_1i_base::loadProperties() { addProperty(item_size, 4, "item_size", "item_size", "readonly", "", "external", "configure"); addProperty(nstreams, 1, "nstreams", "nstreams", "readonly", "", "external", "configure"); } // // Allow for logging // PREPARE_LOGGING(streams_to_stream_ff_1i_base); inline static unsigned int round_up (unsigned int n, unsigned int multiple) { return ((n + multiple - 1) / multiple) * multiple; } inline static unsigned int round_down (unsigned int n, unsigned int multiple) { return (n / multiple) * multiple; } uint32_t streams_to_stream_ff_1i_base::getNOutputStreams() { return 0; } void streams_to_stream_ff_1i_base::setupIOMappings( ) { int ninput_streams = 0; int noutput_streams = 0; std::vector<std::string>::iterator pname; std::string sid(""); int inMode=RealMode; if ( !validGRBlock() ) return; ninput_streams = gr_sptr->get_max_input_streams(); gr_io_signature_sptr g_isig = gr_sptr->input_signature(); noutput_streams = gr_sptr->get_max_output_streams(); gr_io_signature_sptr g_osig = gr_sptr->output_signature(); LOG_DEBUG( streams_to_stream_ff_1i_base, "GNUHAWK IO MAPPINGS IN/OUT " << ninput_streams << "/" << noutput_streams ); // // Someone reset the GR Block so we need to clean up old mappings if they exists // we need to reset the io signatures and check the vlens // if ( _istreams.size() > 0 || _ostreams.size() > 0 ) { LOG_DEBUG( streams_to_stream_ff_1i_base, "RESET INPUT SIGNATURE SIZE:" << _istreams.size() ); IStreamList::iterator istream; for ( int idx=0 ; istream != _istreams.end(); idx++, istream++ ) { // re-add existing stream definitons LOG_DEBUG( streams_to_stream_ff_1i_base, "ADD READ INDEX TO GNU RADIO BLOCK"); if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // setup io signature istream->associate( gr_sptr ); } LOG_DEBUG( streams_to_stream_ff_1i_base, "RESET OUTPUT SIGNATURE SIZE:" << _ostreams.size() ); OStreamList::iterator ostream; for ( int idx=0 ; ostream != _ostreams.end(); idx++, ostream++ ) { // need to evaluate new settings...??? ostream->associate( gr_sptr ); } return; } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio input stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // Stream Identifiers will be pass along as they are received // LOG_TRACE( streams_to_stream_ff_1i_base, "setupIOMappings INPUT PORTS: " << inPorts.size() ); pname = inputPortOrder.begin(); for( int i=0; pname != inputPortOrder.end(); pname++ ) { // grab ports based on their order in the scd.xml file RH_ProvidesPortMap::iterator p_in = inPorts.find(*pname); if ( p_in != inPorts.end() ) { bulkio::InFloatPort *port = dynamic_cast< bulkio::InFloatPort * >(p_in->second); int mode = inMode; sid = ""; // need to add read index to GNU Radio Block for processing streams when max_input == -1 if ( ninput_streams == -1 ) gr_sptr->add_read_index(); // check if we received SRI during setup BULKIO::StreamSRISequence_var sris = port->activeSRIs(); if ( sris->length() > 0 ) { BULKIO::StreamSRI sri = sris[sris->length()-1]; mode = sri.mode; } std::vector<int> in; io_mapping.push_back( in ); _istreams.push_back( gr_istream< bulkio::InFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( streams_to_stream_ff_1i_base, "ADDING INPUT MAP IDX:" << i << " SID:" << sid ); // increment port counter i++; } } // // Setup mapping of RH port to GNU RADIO Block input streams // For version 1, we are ignoring the GNU Radio output stream -1 case that allows multiple data // streams over a single connection. We are mapping a single RH Port to a single GNU Radio stream. // LOG_TRACE( streams_to_stream_ff_1i_base, "setupIOMappings OutputPorts: " << outPorts.size() ); pname = outputPortOrder.begin(); for( int i=0; pname != outputPortOrder.end(); pname++ ) { // grab ports based on their order in the scd.xml file RH_UsesPortMap::iterator p_out = outPorts.find(*pname); if ( p_out != outPorts.end() ) { bulkio::OutFloatPort *port = dynamic_cast< bulkio::OutFloatPort * >(p_out->second); int idx = -1; BULKIO::StreamSRI sri = createOutputSRI( i, idx ); if (idx == -1) idx = i; if(idx < (int)io_mapping.size()) io_mapping[idx].push_back(i); int mode = sri.mode; sid = sri.streamID; _ostreams.push_back( gr_ostream< bulkio::OutFloatPort > ( port, gr_sptr, i, mode, sid )); LOG_DEBUG( streams_to_stream_ff_1i_base, "ADDING OUTPUT MAP IDX:" << i << " SID:" << sid ); _ostreams[i].setSRI(sri, i ); // increment port counter i++; } } } void streams_to_stream_ff_1i_base::float_in_newStreamCallback( BULKIO::StreamSRI &sri ) { LOG_TRACE( streams_to_stream_ff_1i_base, "START NotifySRI port:stream " << float_in->getName() << "/" << sri.streamID); boost::mutex::scoped_lock lock(_sriMutex); _sriQueue.push_back( std::make_pair( float_in, sri ) ); LOG_TRACE( streams_to_stream_ff_1i_base, "END NotifySRI QUEUE " << _sriQueue.size() << " port:stream " << float_in->getName() << "/" << sri.streamID); } void streams_to_stream_ff_1i_base::processStreamIdChanges() { boost::mutex::scoped_lock lock(_sriMutex); LOG_TRACE( streams_to_stream_ff_1i_base, "processStreamIDChanges QUEUE: " << _sriQueue.size() ); if ( _sriQueue.size() == 0 ) return; std::string sid(""); if ( validGRBlock() ) { IStreamList::iterator istream; int idx=0; std::string sid(""); int mode=0; SRIQueue::iterator item = _sriQueue.begin(); for ( ; item != _sriQueue.end(); item++ ) { idx = 0; sid = ""; mode= item->second.mode; sid = item->second.streamID; istream = _istreams.begin(); for ( ; istream != _istreams.end(); idx++, istream++ ) { if ( istream->port == item->first ) { LOG_DEBUG( streams_to_stream_ff_1i_base, " SETTING IN_STREAM ID/STREAM_ID :" << idx << "/" << sid ); istream->sri(true); istream->spe(mode); LOG_DEBUG( streams_to_stream_ff_1i_base, " SETTING OUT_STREAM ID/STREAM_ID :" << idx << "/" << sid ); setOutputStreamSRI( idx, item->second ); } } } _sriQueue.clear(); } else { LOG_WARN( streams_to_stream_ff_1i_base, " NEW STREAM ID, NO GNU RADIO BLOCK DEFINED, SRI QUEUE SIZE:" << _sriQueue.size() ); } } BULKIO::StreamSRI streams_to_stream_ff_1i_base::createOutputSRI( int32_t oidx ) { // for each output stream set the SRI context BULKIO::StreamSRI sri = BULKIO::StreamSRI(); sri.hversion = 1; sri.xstart = 0.0; sri.xdelta = 1; sri.xunits = BULKIO::UNITS_TIME; sri.subsize = 0; sri.ystart = 0.0; sri.ydelta = 0.0; sri.yunits = BULKIO::UNITS_NONE; sri.mode = 0; std::ostringstream t; t << naming_service_name.c_str() << "_" << oidx; std::string sid = t.str(); sri.streamID = CORBA::string_dup(sid.c_str()); return sri; } BULKIO::StreamSRI streams_to_stream_ff_1i_base::createOutputSRI( int32_t oidx, int32_t &in_idx) { return createOutputSRI( oidx ); } void streams_to_stream_ff_1i_base::adjustOutputRate(BULKIO::StreamSRI &sri ) { if ( validGRBlock() ) { double ret=sri.xdelta*gr_sptr->relative_rate(); /** ret = ret / gr_sptr->interpolation(); **/ LOG_TRACE( streams_to_stream_ff_1i_base, "ADJUSTING SRI.XDELTA FROM/TO: " << sri.xdelta << "/" << ret ); sri.xdelta = ret; } } streams_to_stream_ff_1i_base::TimeDuration streams_to_stream_ff_1i_base::getTargetDuration() { TimeDuration t_drate;; uint64_t samps=0; double xdelta=1.0; double trate=1.0; if ( _ostreams.size() > 0 ) { samps= _ostreams[0].nelems(); xdelta= _ostreams[0].sri.xdelta; } trate = samps*xdelta; uint64_t sec = (uint64_t)trunc(trate); uint64_t usec = (uint64_t)((trate-sec)*1e6); t_drate = boost::posix_time::seconds(sec) + boost::posix_time::microseconds(usec); LOG_TRACE( streams_to_stream_ff_1i_base, " SEC/USEC " << sec << "/" << usec << "\n" << " target_duration " << t_drate ); return t_drate; } streams_to_stream_ff_1i_base::TimeDuration streams_to_stream_ff_1i_base::calcThrottle( TimeMark &start_time, TimeMark &end_time ) { TimeDuration delta; TimeDuration target_duration = getTargetDuration(); if ( start_time.is_not_a_date_time() == false ) { TimeDuration s_dtime= end_time - start_time; delta = target_duration - s_dtime; delta /= 4; LOG_TRACE( streams_to_stream_ff_1i_base, " s_time/t_dime " << s_dtime << "/" << target_duration << "\n" << " delta " << delta ); } return delta; } template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int streams_to_stream_ff_1i_base::_transformerServiceFunction( typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams , typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams ) { typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList; typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList; boost::mutex::scoped_lock lock(serviceThreadLock); if ( validGRBlock() == false ) { // create our processing block, and setup property notifiers createBlock(); LOG_DEBUG( streams_to_stream_ff_1i_base, " FINISHED BUILDING GNU RADIO BLOCK"); } //process any Stream ID changes this could affect number of io streams processStreamIdChanges(); if ( !validGRBlock() || istreams.size() == 0 || ostreams.size() == 0 ) { LOG_WARN( streams_to_stream_ff_1i_base, "NO STREAMS ATTACHED TO BLOCK..." ); return NOOP; } _input_ready.resize( istreams.size() ); _ninput_items_required.resize( istreams.size() ); _ninput_items.resize( istreams.size() ); _input_items.resize( istreams.size() ); _output_items.resize( ostreams.size() ); // // RESOLVE: need to look at forecast strategy, // 1) see how many read items are necessary for N number of outputs // 2) read input data and see how much output we can produce // // // Grab available data from input streams // typename _OStreamList::iterator ostream; typename _IStreamList::iterator istream = istreams.begin(); int nitems=0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { // note this a blocking read that can cause deadlocks nitems = istream->read(); if ( istream->overrun() ) { LOG_WARN( streams_to_stream_ff_1i_base, " NOT KEEPING UP WITH STREAM ID:" << istream->streamID ); } if ( istream->sriChanged() ) { // RESOLVE - need to look at how SRI changes can affect Gnu Radio BLOCK state LOG_DEBUG( streams_to_stream_ff_1i_base, "SRI CHANGED, STREAMD IDX/ID: " << idx << "/" << istream->pkt->streamID ); setOutputStreamSRI( idx, istream->pkt->SRI ); } } LOG_TRACE( streams_to_stream_ff_1i_base, "READ NITEMS: " << nitems ); if ( nitems <= 0 && !_istreams[0].eos() ) { return NOOP; } bool eos = false; int nout = 0; bool workDone = false; while ( nout > -1 && serviceThread->threadRunning() ) { eos = false; nout = _forecastAndProcess( eos, istreams, ostreams ); if ( nout > -1 ) { workDone = true; // we chunked on data so move read pointer.. istream = istreams.begin(); for ( ; istream != istreams.end(); istream++ ) { int idx=std::distance( istreams.begin(), istream ); // if we processed data for this stream if ( _input_ready[idx] ) { size_t nitems = 0; try { nitems = gr_sptr->nitems_read( idx ); } catch(...){} if ( nitems > istream->nitems() ) { LOG_WARN( streams_to_stream_ff_1i_base, "WORK CONSUMED MORE DATA THAN AVAILABLE, READ/AVAILABLE " << nitems << "/" << istream->nitems() ); nitems = istream->nitems(); } istream->consume( nitems ); LOG_TRACE( streams_to_stream_ff_1i_base, " CONSUME READ DATA ITEMS/REMAIN " << nitems << "/" << istream->nitems()); } } gr_sptr->reset_read_index(); } // check for not enough data return if ( nout == -1 ) { // check for end of stream istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++) { if ( istream->eos() ) { eos=true; } } if ( eos ) { LOG_TRACE( streams_to_stream_ff_1i_base, "EOS SEEN, SENDING DOWNSTREAM " ); _forecastAndProcess( eos, istreams, ostreams); } } } if ( eos ) { istream = istreams.begin(); for ( ; istream != istreams.end() ; istream++ ) { int idx=std::distance( istreams.begin(), istream ); LOG_DEBUG( streams_to_stream_ff_1i_base, " CLOSING INPUT STREAM IDX:" << idx ); istream->close(); } // close remaining output streams ostream = ostreams.begin(); for ( ; eos && ostream != ostreams.end(); ostream++ ) { int idx=std::distance( ostreams.begin(), ostream ); LOG_DEBUG( streams_to_stream_ff_1i_base, " CLOSING OUTPUT STREAM IDX:" << idx ); ostream->close(); } } // // set the read pointers of the GNU Radio Block to start at the beginning of the // supplied buffers // gr_sptr->reset_read_index(); LOG_TRACE( streams_to_stream_ff_1i_base, " END OF TRANSFORM SERVICE FUNCTION....." << noutput_items ); if ( nout == -1 && eos == false && !workDone ) { return NOOP; } else { return NORMAL; } } template < typename IN_PORT_TYPE, typename OUT_PORT_TYPE > int streams_to_stream_ff_1i_base::_forecastAndProcess( bool &eos, typename std::vector< gr_istream< IN_PORT_TYPE > > &istreams , typename std::vector< gr_ostream< OUT_PORT_TYPE > > &ostreams ) { typedef typename std::vector< gr_istream< IN_PORT_TYPE > > _IStreamList; typedef typename std::vector< gr_ostream< OUT_PORT_TYPE > > _OStreamList; typename _OStreamList::iterator ostream; typename _IStreamList::iterator istream = istreams.begin(); int nout = 0; bool dataReady = false; if ( !eos ) { uint64_t max_items_avail = 0; for ( int idx=0 ; istream != istreams.end() && serviceThread->threadRunning() ; idx++, istream++ ) { LOG_TRACE( streams_to_stream_ff_1i_base, "GET MAX ITEMS: STREAM:"<< idx << " NITEMS/SCALARS:" << istream->nitems() << "/" << istream->_data.size() ); max_items_avail = std::max( istream->nitems(), max_items_avail ); } if ( max_items_avail == 0 ) { LOG_TRACE( streams_to_stream_ff_1i_base, "DATA CHECK - MAX ITEMS NOUTPUT/MAX_ITEMS:" << noutput_items << "/" << max_items_avail); return -1; } // // calc number of output elements based on input items available // noutput_items = 0; if ( !gr_sptr->fixed_rate() ) { noutput_items = round_down((int32_t) (max_items_avail * gr_sptr->relative_rate()), gr_sptr->output_multiple()); LOG_TRACE( streams_to_stream_ff_1i_base, " VARIABLE FORECAST NOUTPUT == " << noutput_items ); } else { istream = istreams.begin(); for ( int i=0; istream != istreams.end(); i++, istream++ ) { int t_noutput_items = gr_sptr->fixed_rate_ninput_to_noutput( istream->nitems() ); if ( gr_sptr->output_multiple_set() ) { t_noutput_items = round_up(t_noutput_items, gr_sptr->output_multiple()); } if ( t_noutput_items > 0 ) { if ( noutput_items == 0 ) { noutput_items = t_noutput_items; } if ( t_noutput_items <= noutput_items ) { noutput_items = t_noutput_items; } } } LOG_TRACE( streams_to_stream_ff_1i_base, " FIXED FORECAST NOUTPUT/output_multiple == " << noutput_items << "/" << gr_sptr->output_multiple()); } // // ask the block how much input they need to produce noutput_items... // if enough data is available to process then set the dataReady flag // int32_t outMultiple = gr_sptr->output_multiple(); while ( !dataReady && noutput_items >= outMultiple ) { // // ask the block how much input they need to produce noutput_items... // gr_sptr->forecast(noutput_items, _ninput_items_required); LOG_TRACE( streams_to_stream_ff_1i_base, "--> FORECAST IN/OUT " << _ninput_items_required[0] << "/" << noutput_items ); istream = istreams.begin(); uint32_t dr_cnt=0; for ( int idx=0 ; noutput_items > 0 && istream != istreams.end(); idx++, istream++ ) { // check if buffer has enough elements _input_ready[idx] = false; if ( istream->nitems() >= (uint64_t)_ninput_items_required[idx] ) { _input_ready[idx] = true; dr_cnt++; } LOG_TRACE( streams_to_stream_ff_1i_base, "ISTREAM DATACHECK NELMS/NITEMS/REQ/READY:" << istream->nelems() << "/" << istream->nitems() << "/" << _ninput_items_required[idx] << "/" << _input_ready[idx]); } if ( dr_cnt < istreams.size() ) { if ( outMultiple > 1 ) { noutput_items -= outMultiple; } else { noutput_items /= 2; } } else { dataReady = true; } LOG_TRACE( streams_to_stream_ff_1i_base, " TRIM FORECAST NOUTPUT/READY " << noutput_items << "/" << dataReady ); } // check if data is ready... if ( !dataReady ) { LOG_TRACE( streams_to_stream_ff_1i_base, "DATA CHECK - NOT ENOUGH DATA AVAIL/REQ:" << _istreams[0].nitems() << "/" << _ninput_items_required[0] ); return -1; } // reset looping variables int ritems = 0; int nitems = 0; // reset caching vectors _output_items.clear(); _input_items.clear(); _ninput_items.clear(); istream = istreams.begin(); for ( int idx=0 ; istream != istreams.end(); idx++, istream++ ) { // check if the stream is ready if ( !_input_ready[idx] ) { continue; } // get number of items remaining try { ritems = gr_sptr->nitems_read( idx ); } catch(...){ // something bad has happened, we are missing an input stream LOG_ERROR( streams_to_stream_ff_1i_base, "MISSING INPUT STREAM FOR GR BLOCK, STREAM ID:" << istream->streamID ); return -2; } nitems = istream->nitems() - ritems; LOG_TRACE( streams_to_stream_ff_1i_base, " ISTREAM: IDX:" << idx << " ITEMS AVAIL/READ/REQ " << nitems << "/" << ritems << "/" << _ninput_items_required[idx] ); if ( nitems >= _ninput_items_required[idx] && nitems > 0 ) { //remove eos checks ...if ( nitems < _ninput_items_required[idx] ) nitems=0; _ninput_items.push_back( nitems ); _input_items.push_back( (const void *) (istream->read_pointer(ritems)) ); } } // // setup output buffer vector based on noutput.. // ostream = ostreams.begin(); for( ; ostream != ostreams.end(); ostream++ ) { ostream->resize(noutput_items); _output_items.push_back((void*)(ostream->write_pointer()) ); } nout=0; if ( _input_items.size() != 0 && serviceThread->threadRunning() ) { LOG_TRACE( streams_to_stream_ff_1i_base, " CALLING WORK.....N_OUT:" << noutput_items << " N_IN:" << nitems << " ISTREAMS:" << _input_items.size() << " OSTREAMS:" << _output_items.size()); nout = gr_sptr->general_work( noutput_items, _ninput_items, _input_items, _output_items); LOG_TRACE( streams_to_stream_ff_1i_base, "RETURN WORK ..... N_OUT:" << nout); } // check for stop condition from work method if ( nout < gr_block::WORK_DONE ) { LOG_WARN( streams_to_stream_ff_1i_base, "WORK RETURNED STOP CONDITION..." << nout ); nout=0; eos = true; } } if (nout != 0 or eos ) { noutput_items = nout; LOG_TRACE( streams_to_stream_ff_1i_base, " WORK RETURNED: NOUT : " << nout << " EOS:" << eos); ostream = ostreams.begin(); typename IN_PORT_TYPE::dataTransfer *pkt=NULL; for ( int idx=0 ; ostream != ostreams.end(); idx++, ostream++ ) { pkt=NULL; int inputIdx = idx; if ( (size_t)(inputIdx) >= istreams.size() ) { for ( inputIdx= istreams.size()-1; inputIdx > -1; inputIdx--) { if ( istreams[inputIdx].pkt != NULL ) { pkt = istreams[inputIdx].pkt; break; } } } else { pkt = istreams[inputIdx].pkt; } LOG_TRACE( streams_to_stream_ff_1i_base, "PUSHING DATA ITEMS/STREAM_ID " << ostream->nitems() << "/" << ostream->streamID ); if ( _maintainTimeStamp ) { // set time stamp for output samples based on input time stamp if ( ostream->nelems() == 0 ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "SEED - TS SRI: xdelta:" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM WRITE: maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "SEED - TS frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif ostream->setTimeStamp( pkt->T, _maintainTimeStamp ); } // write out samples, and set next time stamp based on xdelta and noutput_items ostream->write ( noutput_items, eos ); } else { // use incoming packet's time stamp to forward if ( pkt ) { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "PKT - TS maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << pkt->T.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << pkt->T.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << pkt->T.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << pkt->T.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "PKT - TS frac:" << std::setprecision(12) << pkt->T.tfsec ); #endif ostream->write( noutput_items, eos, pkt->T ); } else { #ifdef TEST_TIME_STAMP LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM SRI: items/xdelta:" << noutput_items << "/" << std::setprecision(12) << ostream->sri.xdelta ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM TOD maint:" << _maintainTimeStamp ); LOG_DEBUG( streams_to_stream_ff_1i_base, " mode:" << ostream->tstamp.tcmode ); LOG_DEBUG( streams_to_stream_ff_1i_base, " status:" << ostream->tstamp.tcstatus ); LOG_DEBUG( streams_to_stream_ff_1i_base, " offset:" << ostream->tstamp.toff ); LOG_DEBUG( streams_to_stream_ff_1i_base, " whole:" << std::setprecision(10) << ostream->tstamp.twsec ); LOG_DEBUG( streams_to_stream_ff_1i_base, "OSTREAM TOD frac:" << std::setprecision(12) << ostream->tstamp.tfsec ); #endif // use time of day as time stamp ostream->write( noutput_items, eos, _maintainTimeStamp ); } } } // for ostreams } return nout; }
Java
/* Copyright (C) 2014 PencilBlue, LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Interface for managing topics */ function ManageTopics() {} //inheritance util.inherits(ManageTopics, pb.BaseController); var SUB_NAV_KEY = 'manage_topics'; ManageTopics.prototype.render = function(cb) { var self = this; var dao = new pb.DAO(); dao.query('topic', pb.DAO.ANYWHERE, pb.DAO.PROJECT_ALL).then(function(topics) { if (util.isError(topics)) { //TODO handle this } //none to manage if(topics.length === 0) { self.redirect('/admin/content/topics/new', cb); return; } //currently, mongo cannot do case-insensitive sorts. We do it manually //until a solution for https://jira.mongodb.org/browse/SERVER-90 is merged. topics.sort(function(a, b) { var x = a.name.toLowerCase(); var y = b.name.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); var angularObjects = pb.js.getAngularObjects( { navigation: pb.AdminNavigation.get(self.session, ['content', 'topics'], self.ls), pills: pb.AdminSubnavService.get(SUB_NAV_KEY, self.ls, SUB_NAV_KEY), topics: topics }); self.setPageName(self.ls.get('MANAGE_TOPICS')); self.ts.registerLocal('angular_objects', new pb.TemplateValue(angularObjects, false)); self.ts.load('admin/content/topics/manage_topics', function(err, data) { var result = '' + data; cb({content: result}); }); }); }; ManageTopics.getSubNavItems = function(key, ls, data) { return [{ name: SUB_NAV_KEY, title: ls.get('MANAGE_TOPICS'), icon: 'refresh', href: '/admin/content/topics' }, { name: 'import_topics', title: '', icon: 'upload', href: '/admin/content/topics/import' }, { name: 'new_topic', title: '', icon: 'plus', href: '/admin/content/topics/new' }]; }; //register admin sub-nav pb.AdminSubnavService.registerFor(SUB_NAV_KEY, ManageTopics.getSubNavItems); //exports module.exports = ManageTopics;
Java
-- -------------------------------------------------------- -- Host: spahost.es -- Versión del servidor: 5.1.70-cll - MySQL Community Server (GPL) -- SO del servidor: unknown-linux-gnu -- HeidiSQL Versión: 8.0.0.4396 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Volcando estructura de base de datos para spahost_lsb CREATE DATABASE IF NOT EXISTS `spahost_lsb` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `spahost_lsb`; -- Volcando estructura para tabla spahost_lsb.lb_cat CREATE TABLE IF NOT EXISTS `lb_cat` ( `id` int(11) NOT NULL AUTO_INCREMENT, `sub_id` int(11) DEFAULT NULL, `title` varchar(250) CHARACTER SET latin1 NOT NULL DEFAULT '', `description` text CHARACTER SET latin1 NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Categorias del blog'; -- Volcando estructura para tabla spahost_lsb.lb_config CREATE TABLE IF NOT EXISTS `lb_config` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `title` varchar(60) NOT NULL DEFAULT '', `subtitle` varchar(60) NOT NULL DEFAULT '', `description` varchar(255) NOT NULL DEFAULT '', `author` varchar(50) NOT NULL DEFAULT '', `email` varchar(100) NOT NULL DEFAULT '', `site_url` varchar(100) NOT NULL DEFAULT '', `lang` varchar(5) NOT NULL, `template` varchar(255) NOT NULL DEFAULT '', `mantenimiento` int(2) NOT NULL DEFAULT '0', `limit_home` int(2) NOT NULL DEFAULT '0', `limit_rss` int(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `user_login_key` (`title`), KEY `user_nicename` (`author`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='Configuracion del blog'; -- Volcando datos para la tabla spahost_lsb.lb_config: 1 rows DELETE FROM `lb_config`; /*!40000 ALTER TABLE `lb_config` DISABLE KEYS */; INSERT INTO `lb_config` (`id`, `title`, `subtitle`, `description`, `author`, `email`, `site_url`, `lang`, `template`, `mantenimiento`, `limit_home`, `limit_rss`) VALUES (1, 'Nombre de Blog', 'Subtitulo de tu blog', 'descripcion de blog', 'tu nombre', 'tu email', 'http://www.tu-web.com', 'es', 'default', 0, 10, 25); /*!40000 ALTER TABLE `lb_config` ENABLE KEYS */; -- Volcando estructura para tabla spahost_lsb.lb_news CREATE TABLE IF NOT EXISTS `lb_news` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(250) CHARACTER SET latin1 NOT NULL DEFAULT '', `news` text CHARACTER SET latin1 NOT NULL, `news_extend` text CHARACTER SET latin1 NOT NULL, `author` varchar(99) CHARACTER SET latin1 NOT NULL DEFAULT '', `source` varchar(99) CHARACTER SET latin1 NOT NULL DEFAULT '', `views` int(11) NOT NULL DEFAULT '0', `category` int(11) NOT NULL DEFAULT '0', `image` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '', `link` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '', `oday` varchar(2) DEFAULT NULL, `omonth` varchar(2) DEFAULT NULL, `oyear` varchar(4) DEFAULT NULL, `ttime` int(10) NOT NULL, `lsttime` int(10) NOT NULL, PRIMARY KEY (`id`), FULLTEXT KEY `FULLTEXT` (`title`) ) ENGINE=MyISAM AUTO_INCREMENT=172 DEFAULT CHARSET=utf8; -- Volcando estructura para tabla spahost_lsb.lb_users CREATE TABLE IF NOT EXISTS `lb_users` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_login` varchar(60) NOT NULL DEFAULT '', `user_pass` varchar(64) NOT NULL DEFAULT '', `user_email` varchar(100) NOT NULL DEFAULT '', `user_url` varchar(100) NOT NULL DEFAULT '', `user_registered` int(10) NOT NULL, `user_activation_key` varchar(60) NOT NULL DEFAULT '', `user_status` int(11) NOT NULL DEFAULT '0', `display_name` varchar(250) NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `user_login_key` (`user_login`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- Volcando datos para la tabla spahost_lsb.lb_users: 1 rows DELETE FROM `lb_users`; /*!40000 ALTER TABLE `lb_users` DISABLE KEYS */; INSERT INTO `lb_users` (`id`, `user_login`, `user_pass`, `user_email`, `user_url`, `user_registered`, `user_activation_key`, `user_status`, `display_name`) VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'admin@tuweb.com', 'http://www.tu-web.com', 1, '', 0, 'Nick a mostrar'); /*!40000 ALTER TABLE `lb_users` ENABLE KEYS */; -- Volcando estructura para tabla spahost_lsb.lb_users_online CREATE TABLE IF NOT EXISTS `lb_users_online` ( `timestap` int(15) NOT NULL DEFAULT '0', `status` int(1) NOT NULL, `ttime` varchar(55) NOT NULL DEFAULT '', `username` varchar(55) NOT NULL DEFAULT '', `ip` varchar(40) NOT NULL DEFAULT '', `country` varchar(10) NOT NULL DEFAULT '', `file` varchar(100) NOT NULL DEFAULT '', `page_title` varchar(100) NOT NULL, `os` varchar(100) NOT NULL, `browser` varchar(100) NOT NULL, `browser_ver` varchar(100) NOT NULL, PRIMARY KEY (`timestap`), KEY `ip` (`ip`), KEY `file` (`file`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- Volcando datos para la tabla spahost_lsb.lb_users_online: 0 rows DELETE FROM `lb_users_online`; /*!40000 ALTER TABLE `lb_users_online` DISABLE KEYS */; /*!40000 ALTER TABLE `lb_users_online` ENABLE KEYS */; -- Volcando estructura para tabla spahost_lsb.vt_users_online CREATE TABLE IF NOT EXISTS `vt_users_online` ( `timestap` int(15) NOT NULL DEFAULT '0', `status` int(1) NOT NULL, `ttime` varchar(55) NOT NULL DEFAULT '', `username` varchar(55) NOT NULL DEFAULT '', `ip` varchar(40) NOT NULL DEFAULT '', `country` varchar(10) NOT NULL DEFAULT '', `file` varchar(100) NOT NULL DEFAULT '', `page_title` varchar(100) NOT NULL, `os` varchar(100) NOT NULL, `browser` varchar(100) NOT NULL, `browser_ver` varchar(100) NOT NULL, PRIMARY KEY (`timestap`), KEY `ip` (`ip`), KEY `file` (`file`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- Volcando datos para la tabla spahost_lsb.vt_users_online: 0 rows DELETE FROM `vt_users_online`; /*!40000 ALTER TABLE `vt_users_online` DISABLE KEYS */; /*!40000 ALTER TABLE `vt_users_online` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
Java
#include <shlobj.h> HRESULT CreateDataObject(FORMATETC *,STGMEDIUM *,IDataObject **,int);
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Thu Oct 24 15:10:37 CEST 2013 --> <title>RmcpConstants</title> <meta name="date" content="2013-10-24"> <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="RmcpConstants"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <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 class="navBarCell1Rev">Class</li> <li><a href="class-use/RmcpConstants.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="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpClassOfMessage.html" title="enum in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpDecoder.html" title="class in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html" target="_top">Frames</a></li> <li><a href="RmcpConstants.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.veraxsystems.vxipmi.coding.rmcp</div> <h2 title="Class RmcpConstants" class="title">Class RmcpConstants</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="strong">RmcpConstants</span> extends java.lang.Object</pre> <div class="block">Set of constants. Byte constants are encoded as pseudo unsigned bytes. RMCPConstants doesn't use <a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html" title="class in com.veraxsystems.vxipmi.common"><code>TypeConverter</code></a> because fields need to be runtime constants.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html#byteToInt(byte)"><code>TypeConverter.byteToInt(byte)</code></a>, <a href="../../../../../com/veraxsystems/vxipmi/common/TypeConverter.html#intToByte(int)"><code>TypeConverter.intToByte(int)</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</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> <tr class="altColor"> <td class="colFirst"><code>static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#ASFIANA">ASFIANA</a></strong></code> <div class="block">IANA Enterprise Number = ASF IANA</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static byte</code></td> <td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#PRESENCE_PING">PRESENCE_PING</a></strong></code> <div class="block">ASF Message type = Presence Ping</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static byte</code></td> <td class="colLast"><code><strong><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html#RMCP_V1_0">RMCP_V1_0</a></strong></code> <div class="block">RMCP version 1.0</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="RMCP_V1_0"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>RMCP_V1_0</h4> <pre>public static final&nbsp;byte RMCP_V1_0</pre> <div class="block">RMCP version 1.0</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.RMCP_V1_0">Constant Field Values</a></dd></dl> </li> </ul> <a name="ASFIANA"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ASFIANA</h4> <pre>public static final&nbsp;int ASFIANA</pre> <div class="block">IANA Enterprise Number = ASF IANA</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.ASFIANA">Constant Field Values</a></dd></dl> </li> </ul> <a name="PRESENCE_PING"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>PRESENCE_PING</h4> <pre>public static final&nbsp;byte PRESENCE_PING</pre> <div class="block">ASF Message type = Presence Ping</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.veraxsystems.vxipmi.coding.rmcp.RmcpConstants.PRESENCE_PING">Constant Field Values</a></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_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 class="navBarCell1Rev">Class</li> <li><a href="class-use/RmcpConstants.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="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpClassOfMessage.html" title="enum in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/veraxsystems/vxipmi/coding/rmcp/RmcpDecoder.html" title="class in com.veraxsystems.vxipmi.coding.rmcp"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/veraxsystems/vxipmi/coding/rmcp/RmcpConstants.html" target="_top">Frames</a></li> <li><a href="RmcpConstants.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
/* * LibrePCB - Professional EDA for everyone! * Copyright (C) 2013 LibrePCB Developers, see AUTHORS.md for contributors. * https://librepcb.org/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /******************************************************************************* * Includes ******************************************************************************/ #include <gtest/gtest.h> #include <librepcb/common/uuid.h> #include <QtCore> /******************************************************************************* * Namespace ******************************************************************************/ namespace librepcb { namespace tests { /******************************************************************************* * Test Data Type ******************************************************************************/ typedef struct { bool valid; QString uuid; } UuidTestData; /******************************************************************************* * Test Class ******************************************************************************/ class UuidTest : public ::testing::TestWithParam<UuidTestData> {}; /******************************************************************************* * Test Methods ******************************************************************************/ TEST_P(UuidTest, testCopyConstructor) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid source = Uuid::fromString(data.uuid); Uuid copy(source); EXPECT_TRUE(copy == source); EXPECT_EQ(source.toStr(), copy.toStr()); } } TEST_P(UuidTest, testToStr) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid = Uuid::fromString(data.uuid); EXPECT_EQ(data.uuid, uuid.toStr()); EXPECT_EQ(36, uuid.toStr().length()); } } TEST_P(UuidTest, testOperatorAssign) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid source = Uuid::fromString(data.uuid); Uuid destination = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID EXPECT_NE(source.toStr(), destination.toStr()); destination = source; EXPECT_EQ(source.toStr(), destination.toStr()); } } TEST_P(UuidTest, testOperatorEquals) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid1 = Uuid::fromString(data.uuid); Uuid uuid2 = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID EXPECT_FALSE(uuid2 == uuid1); EXPECT_FALSE(uuid1 == uuid2); uuid2 = uuid1; EXPECT_TRUE(uuid2 == uuid1); EXPECT_TRUE(uuid1 == uuid2); } } TEST_P(UuidTest, testOperatorNotEquals) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid1 = Uuid::fromString(data.uuid); Uuid uuid2 = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID EXPECT_TRUE(uuid2 != uuid1); EXPECT_TRUE(uuid1 != uuid2); uuid2 = uuid1; EXPECT_FALSE(uuid2 != uuid1); EXPECT_FALSE(uuid1 != uuid2); } } TEST_P(UuidTest, testOperatorComparisons) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid1 = Uuid::fromString(data.uuid); Uuid uuid2 = Uuid::fromString("d2c30518-5cd1-4ce9-a569-44f783a3f66a"); // valid UUID if (uuid1.toStr() == uuid2.toStr()) { EXPECT_FALSE((uuid2 < uuid1) || (uuid2 > uuid1)); EXPECT_FALSE((uuid1 < uuid2) || (uuid1 > uuid2)); EXPECT_TRUE((uuid2 <= uuid1) && (uuid2 >= uuid1)); EXPECT_TRUE((uuid1 <= uuid2) && (uuid1 >= uuid2)); } else { EXPECT_TRUE((uuid2 < uuid1) != (uuid2 > uuid1)); EXPECT_TRUE((uuid1 < uuid2) != (uuid1 > uuid2)); EXPECT_TRUE((uuid2 <= uuid1) != (uuid2 >= uuid1)); EXPECT_TRUE((uuid1 <= uuid2) != (uuid1 >= uuid2)); } EXPECT_EQ(uuid2.toStr() < uuid1.toStr(), uuid2 < uuid1); EXPECT_EQ(uuid1.toStr() < uuid2.toStr(), uuid1 < uuid2); EXPECT_EQ(uuid2.toStr() > uuid1.toStr(), uuid2 > uuid1); EXPECT_EQ(uuid1.toStr() > uuid2.toStr(), uuid1 > uuid2); EXPECT_EQ(uuid2.toStr() <= uuid1.toStr(), uuid2 <= uuid1); EXPECT_EQ(uuid1.toStr() <= uuid2.toStr(), uuid1 <= uuid2); EXPECT_EQ(uuid2.toStr() >= uuid1.toStr(), uuid2 >= uuid1); EXPECT_EQ(uuid1.toStr() >= uuid2.toStr(), uuid1 >= uuid2); } } TEST(UuidTest, testCreateRandom) { for (int i = 0; i < 1000; i++) { Uuid uuid = Uuid::createRandom(); EXPECT_FALSE(uuid.toStr().isEmpty()); EXPECT_EQ(QUuid::DCE, QUuid(uuid.toStr()).variant()); EXPECT_EQ(QUuid::Random, QUuid(uuid.toStr()).version()); } } TEST_P(UuidTest, testIsValid) { const UuidTestData& data = GetParam(); EXPECT_EQ(data.valid, Uuid::isValid(data.uuid)); } TEST_P(UuidTest, testFromString) { const UuidTestData& data = GetParam(); if (data.valid) { EXPECT_EQ(data.uuid, Uuid::fromString(data.uuid).toStr()); } else { EXPECT_THROW(Uuid::fromString(data.uuid), Exception); } } TEST_P(UuidTest, testTryFromString) { const UuidTestData& data = GetParam(); tl::optional<Uuid> uuid = Uuid::tryFromString(data.uuid); if (data.valid) { EXPECT_TRUE(uuid); EXPECT_EQ(data.uuid, uuid->toStr()); } else { EXPECT_FALSE(uuid); EXPECT_EQ(tl::nullopt, uuid); } } TEST_P(UuidTest, testSerializeToSExpression) { const UuidTestData& data = GetParam(); if (data.valid) { Uuid uuid = Uuid::fromString(data.uuid); EXPECT_EQ(data.uuid, serializeToSExpression(uuid).getStringOrToken()); EXPECT_EQ( data.uuid, serializeToSExpression(tl::make_optional(uuid)).getStringOrToken()); } } TEST_P(UuidTest, testDeserializeFromSExpression) { const UuidTestData& data = GetParam(); SExpression sexpr = SExpression::createToken(data.uuid); if (data.valid) { EXPECT_EQ(data.uuid, deserializeFromSExpression<Uuid>(sexpr, false).toStr()); EXPECT_EQ( data.uuid, deserializeFromSExpression<tl::optional<Uuid>>(sexpr, false)->toStr()); } else { EXPECT_THROW(deserializeFromSExpression<Uuid>(sexpr, false), Exception); EXPECT_THROW(deserializeFromSExpression<tl::optional<Uuid>>(sexpr, false), Exception); } } TEST(UuidTest, testSerializeOptionalToSExpression) { tl::optional<Uuid> uuid = tl::nullopt; EXPECT_EQ("none", serializeToSExpression(uuid).getStringOrToken()); } TEST(UuidTest, testDeserializeOptionalFromSExpression) { SExpression sexpr = SExpression::createToken("none"); EXPECT_EQ(tl::nullopt, deserializeFromSExpression<tl::optional<Uuid>>(sexpr, false)); } /******************************************************************************* * Test Data ******************************************************************************/ // Test UUIDs are generated with: // - https://www.uuidgenerator.net // - https://uuidgenerator.org/ // - https://www.famkruithof.net/uuid/uuidgen // - http://www.freecodeformat.com/uuid-guid.php // - https://de.wikipedia.org/wiki/Universally_Unique_Identifier // // clang-format off INSTANTIATE_TEST_SUITE_P(UuidTest, UuidTest, ::testing::Values( // DCE Version 4 (random, the only accepted UUID type for us) UuidTestData({true , "bdf7bea5-b88e-41b2-be85-c1604e8ddfca" }), UuidTestData({true , "587539af-1c39-40ed-9bdd-2ca2e6aeb18d" }), UuidTestData({true , "27556d27-fe33-4334-a8ee-b05b402a21d6" }), UuidTestData({true , "91172d44-bdcc-41b2-8e07-4f8cf44eb108" }), UuidTestData({true , "ecb3a5fe-1cbc-4a1b-bf8f-5d6e26deaee1" }), UuidTestData({true , "908f9c33-40be-46aa-97b4-be2cd7477881" }), UuidTestData({true , "74ca6127-e785-4355-8580-1ced4f0a0e9e" }), UuidTestData({true , "568eb40d-cd69-47a5-8932-4f5cc4b2d3fa" }), UuidTestData({true , "29401dcb-6cb6-47a1-8f7d-72dd7f9f4939" }), UuidTestData({true , "e367d539-3163-4530-ab47-3b4cb2df2a40" }), UuidTestData({true , "00000000-0000-4001-8000-000000000000" }), // DCE Version 1 (time based) UuidTestData({false, "15edb784-76df-11e6-8b77-86f30ca893d3" }), UuidTestData({false, "232872b8-76df-11e6-8b77-86f30ca893d3" }), UuidTestData({false, "1d5a3bd6-76e0-11e6-b25e-0401beb96201" }), UuidTestData({false, "F0CDE9F0-76DF-11E6-BDF4-0800200C9A66" }), UuidTestData({false, "EA9A1590-76DF-11E6-BDF4-0800200C9A66" }), // DCE Version 3 (name based, md5) UuidTestData({false, "1a32cba8-79ba-3f01-bd8a-46c5ae17ccd8" }), UuidTestData({false, "BBCB4DF8-95FB-38E8-A398-187EA35A1655" }), // DCE Version 5 (name based, sha1) UuidTestData({false, "74738ff5-5367-5958-9aee-98fffdcd1876" }), // Microsoft GUID UuidTestData({false, "00000000-0000-0000-C000-000000000046" }), // NULL UUID UuidTestData({false, "00000000-0000-0000-0000-000000000000" }), // Invalid UUIDs UuidTestData({false, "" }), // empty UuidTestData({false, " " }), // empty UuidTestData({false, QString()}), // null UuidTestData({false, "74CA6127-E785-4355-8580-1CED4F0A0E9E" }), // uppercase UuidTestData({false, "568EB40D-CD69-47A5-8932-4F5CC4B2D3FA" }), // uppercase UuidTestData({false, "29401DCB-6CB6-47A1-8F7D-72DD7F9F4939" }), // uppercase UuidTestData({false, "E367D539-3163-4530-AB47-3B4CB2DF2A40" }), // uppercase UuidTestData({false, "C56A4180-65AA-42EC-A945-5FD21DEC" }), // too short UuidTestData({false, "bdf7bea5-b88e-41b2-be85-c1604e8ddfca " }), // too long UuidTestData({false, " bdf7bea5-b88e-41b2-be85-c1604e8ddfca" }), // too long UuidTestData({false, "bdf7bea5b88e41b2be85c1604e8ddfca" }), // missing '-' UuidTestData({false, "{bdf7bea5-b88e-41b2-be85-c1604e8ddfca}"}), // '{', '}' UuidTestData({false, "bdf7bea5-b88g-41b2-be85-c1604e8ddfca" }), // 'g' UuidTestData({false, "bdf7bea5_b88e_41b2_be85_c1604e8ddfca" }), // '_' UuidTestData({false, "bdf7bea5 b88e 41b2 be85 c1604e8ddfca" }) // spaces )); // clang-format on /******************************************************************************* * End of File ******************************************************************************/ } // namespace tests } // namespace librepcb
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_01) on Sun Jul 03 07:12:39 ICT 2005 --> <TITLE> Uses of Package com.golden.gamedev.object.sprite (GTGE API v0.2.3) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Package com.golden.gamedev.object.sprite (GTGE API v0.2.3)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>GTGE API</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/golden/gamedev/object/sprite/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>com.golden.gamedev.object.sprite</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#com.golden.gamedev.object.sprite"><B>com.golden.gamedev.object.sprite</B></A></TD> <TD>Sprite implementation.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="com.golden.gamedev.object.sprite"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A> used by <A HREF="../../../../../com/golden/gamedev/object/sprite/package-summary.html">com.golden.gamedev.object.sprite</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../com/golden/gamedev/object/sprite/class-use/AdvanceSprite.html#com.golden.gamedev.object.sprite"><B>AdvanceSprite</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>AdvanceSprite</code> class is animated sprite that has status and direction attributes, that way the animation is fully controlled by its status and direction.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>GTGE API</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?com/golden/gamedev/object/sprite/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2003-2005 Golden T Studios. All rights reserved. Use is subject to <a href=http://creativecommons.org/licenses/by/2.0/>license terms<a/>.<br><a target=_blank href=http://www.goldenstudios.or.id/>GoldenStudios.or.id</a></i> </BODY> </HTML>
Java
/* Copyright David Strachan Buchan 2013 * This file is part of BounceBallGame. BounceBallGame is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BounceBallGame is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with BounceBallGame. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.ashndave; import javax.swing.JFrame; import uk.co.ashndave.game.GameLoop; import uk.co.ashndave.game.Renderable; import uk.co.ashndave.game.Updateable; public class KeepyUppy { private static final String BriefLicence1 = "Copyright (C) 2013 David Strachan Buchan."; private static final String BriefLicence2 = "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>."; private static final String BriefLicence3 = "This is free software: you are free to change and redistribute it."; private static final String BriefLicence4 = "There is NO WARRANTY, to the extent permitted by law."; private static final String BriefLicence5 = "Written by David Strachan Buchan."; private static final String[] BriefLicence = new String[]{BriefLicence1, BriefLicence2,BriefLicence3,BriefLicence4,BriefLicence5}; private Thread animator; private GameLoop looper; private GamePanel gamePanel; private static KeepyUppy game; /** * @param args */ public static void main(String[] args) { printLicence(); game = new KeepyUppy(); javax.swing.SwingUtilities.invokeLater(new Runnable(){ public void run(){ game.createAndShowGUI(); } }); } private static void printLicence() { for(String licence : BriefLicence) { System.out.println(licence); } } protected void createAndShowGUI() { gamePanel = new GamePanel(); looper = new GameLoop(gamePanel, gamePanel); JFrame frame = new JFrame("Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gamePanel); frame.pack(); frame.setVisible(true); animator = new Thread(looper); animator.start(); } }
Java
/** ****************************************************************************** * @file Examples_LL/USART/USART_Communication_TxRx_DMA/Src/main.c * @author MCD Application Team * @brief This example describes how to send/receive bytes over USART IP using * the STM32F0xx USART LL API in DMA mode. * Peripheral initialization done using LL unitary services functions. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F0xx_LL_Examples * @{ */ /** @addtogroup USART_Communication_TxRx_DMA * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint8_t ubButtonPress = 0; __IO uint8_t ubSend = 0; /* Buffer used for transmission */ const uint8_t aTxBuffer[] = "STM32F0xx USART LL API Example : TX/RX in DMA mode\r\nConfiguration UART 115200 bps, 8 data bit/1 stop bit/No parity/No HW flow control\r\nPlease enter 'END' string ...\r\n"; uint8_t ubNbDataToTransmit = sizeof(aTxBuffer); __IO uint8_t ubTransmissionComplete = 0; /* Buffer used for reception */ const uint8_t aStringToReceive[] = "END"; uint8_t ubNbDataToReceive = sizeof(aStringToReceive) - 1; uint8_t aRxBuffer[sizeof(aStringToReceive) - 1]; __IO uint8_t ubReceptionComplete = 0; /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); void Configure_DMA(void); void Configure_USART(void); void StartTransfers(void); void LED_Init(void); void LED_On(void); void LED_Blinking(uint32_t Period); void LED_Off(void); void UserButton_Init(void); void WaitForUserButtonPress(void); void WaitAndCheckEndOfTransfer(void); uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* Configure the system clock to 48 MHz */ SystemClock_Config(); /* Initialize LED2 */ LED_Init(); /* Initialize button in EXTI mode */ UserButton_Init(); /* Configure USARTx (USART IP configuration and related GPIO initialization) */ Configure_USART(); /* Configure DMA channels for USART instance */ Configure_DMA(); /* Wait for User push-button press to start transfer */ WaitForUserButtonPress(); /* Initiate DMA transfers */ StartTransfers(); /* Wait for the end of the transfer and check received data */ WaitAndCheckEndOfTransfer(); /* Infinite loop */ while (1) { } } /** * @brief This function configures the DMA Channels for TX and RX transfers * @note This function is used to : * -1- Enable DMA1 clock * -2- Configure NVIC for DMA transfer complete/error interrupts * -3- Configure DMA TX channel functional parameters * -4- Configure DMA RX channel functional parameters * -5- Enable transfer complete/error interrupts * @param None * @retval None */ void Configure_DMA(void) { /* DMA1 used for USART2 Transmission and Reception */ /* (1) Enable the clock of DMA1 */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1); /* (2) Configure NVIC for DMA transfer complete/error interrupts */ NVIC_SetPriority(DMA1_Channel4_5_6_7_IRQn, 0); NVIC_EnableIRQ(DMA1_Channel4_5_6_7_IRQn); /* (3) Configure the DMA functional parameters for transmission */ LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_4, LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE); LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_4, (uint32_t)aTxBuffer, LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_TRANSMIT), LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_4)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_4, ubNbDataToTransmit); /* (4) Configure the DMA functional parameters for reception */ LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_5, LL_DMA_DIRECTION_PERIPH_TO_MEMORY | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE); LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_5, LL_USART_DMA_GetRegAddr(USART2, LL_USART_DMA_REG_DATA_RECEIVE), (uint32_t)aRxBuffer, LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_5)); LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_5, ubNbDataToReceive); /* (5) Enable DMA transfer complete/error interrupts */ LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_4); LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_4); LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_5); LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_5); } /** * @brief This function configures USARTx Instance. * @note This function is used to : * -1- Enable GPIO clock and configures the USART2 pins. * -2- Enable the USART2 peripheral clock and clock source. * -3- Configure USART2 functional parameters. * -4- Enable USART2. * @note Peripheral configuration is minimal configuration from reset values. * Thus, some useless LL unitary functions calls below are provided as * commented examples - setting is default configuration from reset. * @param None * @retval None */ void Configure_USART(void) { /* (1) Enable GPIO clock and configures the USART pins **********************/ /* Enable the peripheral clock of GPIO Port */ LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA); /* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_2, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_2, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_2, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_2, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_2, LL_GPIO_PULL_UP); /* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */ LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_3, LL_GPIO_MODE_ALTERNATE); LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_3, LL_GPIO_AF_1); LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_3, LL_GPIO_SPEED_FREQ_HIGH); LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_3, LL_GPIO_OUTPUT_PUSHPULL); LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_3, LL_GPIO_PULL_UP); /* (2) Enable USART2 peripheral clock and clock source ****************/ LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART2); /* Set clock source */ LL_RCC_SetUSARTClockSource(LL_RCC_USART2_CLKSOURCE_PCLK1); /* (3) Configure USART2 functional parameters ********************************/ /* Disable USART prior modifying configuration registers */ /* Note: Commented as corresponding to Reset value */ // LL_USART_Disable(USART2); /* TX/RX direction */ LL_USART_SetTransferDirection(USART2, LL_USART_DIRECTION_TX_RX); /* 8 data bit, 1 start bit, 1 stop bit, no parity */ LL_USART_ConfigCharacter(USART2, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1); /* No Hardware Flow control */ /* Reset value is LL_USART_HWCONTROL_NONE */ // LL_USART_SetHWFlowCtrl(USART2, LL_USART_HWCONTROL_NONE); /* Oversampling by 16 */ /* Reset value is LL_USART_OVERSAMPLING_16 */ // LL_USART_SetOverSampling(USART2, LL_USART_OVERSAMPLING_16); /* Set Baudrate to 115200 using APB frequency set to 48000000 Hz */ /* Frequency available for USART peripheral can also be calculated through LL RCC macro */ /* Ex : Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance In this example, Peripheral Clock is expected to be equal to 48000000 Hz => equal to SystemCoreClock */ LL_USART_SetBaudRate(USART2, SystemCoreClock, LL_USART_OVERSAMPLING_16, 115200); /* (4) Enable USART2 **********************************************************/ LL_USART_Enable(USART2); /* Polling USART initialisation */ while((!(LL_USART_IsActiveFlag_TEACK(USART2))) || (!(LL_USART_IsActiveFlag_REACK(USART2)))) { } } /** * @brief This function initiates TX and RX DMA transfers by enabling DMA channels * @param None * @retval None */ void StartTransfers(void) { /* Enable DMA RX Interrupt */ LL_USART_EnableDMAReq_RX(USART2); /* Enable DMA TX Interrupt */ LL_USART_EnableDMAReq_TX(USART2); /* Enable DMA Channel Rx */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_5); /* Enable DMA Channel Tx */ LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_4); } /** * @brief Initialize LED2. * @param None * @retval None */ void LED_Init(void) { /* Enable the LED2 Clock */ LED2_GPIO_CLK_ENABLE(); /* Configure IO in output push-pull mode to drive external LED2 */ LL_GPIO_SetPinMode(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_MODE_OUTPUT); /* Reset value is LL_GPIO_OUTPUT_PUSHPULL */ //LL_GPIO_SetPinOutputType(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_OUTPUT_PUSHPULL); /* Reset value is LL_GPIO_SPEED_FREQ_LOW */ //LL_GPIO_SetPinSpeed(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_SPEED_FREQ_LOW); /* Reset value is LL_GPIO_PULL_NO */ //LL_GPIO_SetPinPull(LED2_GPIO_PORT, LED2_PIN, LL_GPIO_PULL_NO); } /** * @brief Turn-on LED2. * @param None * @retval None */ void LED_On(void) { /* Turn LED2 on */ LL_GPIO_SetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Turn-off LED2. * @param None * @retval None */ void LED_Off(void) { /* Turn LED2 off */ LL_GPIO_ResetOutputPin(LED2_GPIO_PORT, LED2_PIN); } /** * @brief Set LED2 to Blinking mode for an infinite loop (toggle period based on value provided as input parameter). * @param Period : Period of time (in ms) between each toggling of LED * This parameter can be user defined values. Pre-defined values used in that example are : * @arg LED_BLINK_FAST : Fast Blinking * @arg LED_BLINK_SLOW : Slow Blinking * @arg LED_BLINK_ERROR : Error specific Blinking * @retval None */ void LED_Blinking(uint32_t Period) { /* Toggle LED2 in an infinite loop */ while (1) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(Period); } } /** * @brief Configures User push-button in GPIO or EXTI Line Mode. * @param None * @retval None */ void UserButton_Init(void) { /* Enable the BUTTON Clock */ USER_BUTTON_GPIO_CLK_ENABLE(); /* Configure GPIO for BUTTON */ LL_GPIO_SetPinMode(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_MODE_INPUT); LL_GPIO_SetPinPull(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, LL_GPIO_PULL_NO); /* Connect External Line to the GPIO*/ USER_BUTTON_SYSCFG_SET_EXTI(); /* Enable a rising trigger EXTI_Line4_15 Interrupt */ USER_BUTTON_EXTI_LINE_ENABLE(); USER_BUTTON_EXTI_FALLING_TRIG_ENABLE(); /* Configure NVIC for USER_BUTTON_EXTI_IRQn */ NVIC_SetPriority(USER_BUTTON_EXTI_IRQn, 3); NVIC_EnableIRQ(USER_BUTTON_EXTI_IRQn); } /** * @brief Wait for User push-button press to start transfer. * @param None * @retval None */ /* */ void WaitForUserButtonPress(void) { while (ubButtonPress == 0) { LL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN); LL_mDelay(LED_BLINK_FAST); } /* Ensure that LED2 is turned Off */ LED_Off(); } /** * @brief Wait end of transfer and check if received Data are well. * @param None * @retval None */ void WaitAndCheckEndOfTransfer(void) { /* 1 - Wait end of transmission */ while (ubTransmissionComplete != 1) { } /* Disable DMA1 Tx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4); /* 2 - Wait end of reception */ while (ubReceptionComplete != 1) { } /* Disable DMA1 Rx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5); /* 3 - Compare received string to expected one */ if(Buffercmp8((uint8_t*)aStringToReceive, (uint8_t*)aRxBuffer, ubNbDataToReceive)) { /* Processing Error */ LED_Blinking(LED_BLINK_ERROR); } else { /* Turn On Led if data are well received */ LED_On(); } } /** * @brief Compares two 8-bit buffers and returns the comparison result. * @param pBuffer1: pointer to the source buffer to be compared to. * @param pBuffer2: pointer to the second source buffer to be compared to the first. * @param BufferLength: buffer's length. * @retval 0: Comparison is OK (the two Buffers are identical) * Value different from 0: Comparison is NOK (Buffers are different) */ uint8_t Buffercmp8(uint8_t* pBuffer1, uint8_t* pBuffer2, uint8_t BufferLength) { while (BufferLength--) { if (*pBuffer1 != *pBuffer2) { return 1; } pBuffer1++; pBuffer2++; } return 0; } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSI48) * SYSCLK(Hz) = 48000000 * HCLK(Hz) = 48000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * HSI Frequency(Hz) = 48000000 * PREDIV = 2 * PLLMUL = 2 * Flash Latency(WS) = 1 * @param None * @retval None */ void SystemClock_Config(void) { /* Set FLASH latency */ LL_FLASH_SetLatency(LL_FLASH_LATENCY_1); /* Enable HSI48 and wait for activation*/ LL_RCC_HSI48_Enable(); while(LL_RCC_HSI48_IsReady() != 1) { }; /* Main PLL configuration and activation */ LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSI48, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2); LL_RCC_PLL_Enable(); while(LL_RCC_PLL_IsReady() != 1) { }; /* Sysclk activation on the main PLL */ LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1); LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL); while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) { }; /* Set APB1 prescaler */ LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1); /* Set systick to 1ms in using frequency set to 48MHz */ /* This frequency can be calculated through LL RCC macro */ /* ex: __LL_RCC_CALC_PLLCLK_FREQ (HSI48_VALUE, LL_RCC_PLL_MUL_2, LL_RCC_PREDIV_DIV_2) */ LL_Init1msTick(48000000); /* Update CMSIS variable (which can be updated also through SystemCoreClockUpdate function) */ LL_SetSystemCoreClock(48000000); } /******************************************************************************/ /* USER IRQ HANDLER TREATMENT Functions */ /******************************************************************************/ /** * @brief Function to manage User push-button * @param None * @retval None */ void UserButton_Callback(void) { /* Update User push-button variable : to be checked in waiting loop in main program */ ubButtonPress = 1; } /** * @brief Function called from DMA1 IRQ Handler when Tx transfer is completed * @param None * @retval None */ void DMA1_TransmitComplete_Callback(void) { /* DMA Tx transfer completed */ ubTransmissionComplete = 1; } /** * @brief Function called from DMA1 IRQ Handler when Rx transfer is completed * @param None * @retval None */ void DMA1_ReceiveComplete_Callback(void) { /* DMA Rx transfer completed */ ubReceptionComplete = 1; } /** * @brief Function called in case of error detected in USART IT Handler * @param None * @retval None */ void USART_TransferError_Callback(void) { /* Disable DMA1 Tx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_4); /* Disable DMA1 Rx Channel */ LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_5); /* Set LED2 to Blinking mode to indicate error occurs */ LED_Blinking(LED_BLINK_ERROR); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Java
/* * FuchsTracker.c Copyright (C) 1999 Sylvain "Asle" Chipaux * * Depacks Fuchs Tracker modules * * Modified in 2006,2007,2014 by Claudio Matsuoka */ #include <string.h> #include <stdlib.h> #include "prowiz.h" static int depack_fuchs(HIO_HANDLE *in, FILE *out) { uint8 *tmp; uint8 max_pat; /*int ssize;*/ uint8 data[1080]; unsigned smp_len[16]; unsigned loop_start[16]; unsigned pat_size; unsigned i; memset(smp_len, 0, 16 * 4); memset(loop_start, 0, 16 * 4); memset(data, 0, 1080); hio_read(data, 1, 10, in); /* read/write title */ /*ssize =*/ hio_read32b(in); /* read all sample data size */ /* read/write sample sizes */ for (i = 0; i < 16; i++) { smp_len[i] = hio_read16b(in); data[42 + i * 30] = smp_len[i] >> 9; data[43 + i * 30] = smp_len[i] >> 1; } /* read/write volumes */ for (i = 0; i < 16; i++) { data[45 + i * 30] = hio_read16b(in); } /* read/write loop start */ for (i = 0; i < 16; i++) { loop_start[i] = hio_read16b(in); data[46 + i * 30] = loop_start[i] >> 1; } /* write replen */ for (i = 0; i < 16; i++) { int loop_size; loop_size = smp_len[i] - loop_start[i]; if (loop_size == 0 || loop_start[i] == 0) { data[49 + i * 30] = 1; } else { data[48 + i * 30] = loop_size >> 9; data[49 + i * 30] = loop_size >> 1; } } /* fill replens up to 31st sample wiz $0001 */ for (i = 16; i < 31; i++) { data[49 + i * 30] = 1; } /* that's it for the samples ! */ /* now, the pattern list */ /* read number of pattern to play */ data[950] = hio_read16b(in); data[951] = 0x7f; /* read/write pattern list */ for (max_pat = i = 0; i < 40; i++) { uint8 pat = hio_read16b(in); data[952 + i] = pat; if (pat > max_pat) { max_pat = pat; } } /* write ptk's ID */ if (fwrite(data, 1, 1080, out) != 1080) { return -1; } write32b(out, PW_MOD_MAGIC); /* now, the pattern data */ /* bypass the "SONG" ID */ hio_read32b(in); /* read pattern data size */ pat_size = hio_read32b(in); /* Sanity check */ if (pat_size <= 0 || pat_size > 0x20000) return -1; /* read pattern data */ tmp = (uint8 *)malloc(pat_size); if (hio_read(tmp, 1, pat_size, in) != pat_size) { free(tmp); return -1; } /* convert shits */ for (i = 0; i < pat_size; i += 4) { /* convert fx C arg back to hex value */ if ((tmp[i + 2] & 0x0f) == 0x0c) { int x = tmp[i + 3]; tmp[i + 3] = 10 * (x >> 4) + (x & 0xf); } } /* write pattern data */ fwrite(tmp, pat_size, 1, out); free(tmp); /* read/write sample data */ hio_read32b(in); /* bypass "INST" Id */ for (i = 0; i < 16; i++) { if (smp_len[i] != 0) pw_move_data(out, in, smp_len[i]); } return 0; } static int test_fuchs (uint8 *data, char *t, int s) { int i; int ssize, hdr_ssize; #if 0 /* test #1 */ if (i < 192) { Test = BAD; return; } start = i - 192; #endif if (readmem32b(data + 192) != 0x534f4e47) /* SONG */ return -1; /* all sample size */ hdr_ssize = readmem32b(data + 10); if (hdr_ssize <= 2 || hdr_ssize >= 65535 * 16) return -1; /* samples descriptions */ ssize = 0; for (i = 0; i < 16; i++) { uint8 *d = data + i * 2; int len = readmem16b(d + 14); int start = readmem16b(d + 78); /* volumes */ if (d[46] > 0x40) return -1; if (len < start) return -1; ssize += len; } if (ssize <= 2 || ssize > hdr_ssize) return -1; /* get highest pattern number in pattern list */ /*max_pat = 0;*/ for (i = 0; i < 40; i++) { int pat = data[i * 2 + 113]; if (pat > 40) return -1; /*if (pat > max_pat) max_pat = pat;*/ } #if 0 /* input file not long enough ? */ max_pat++; max_pat *= 1024; PW_REQUEST_DATA (s, k + 200); #endif pw_read_title(NULL, t, 0); return 0; } const struct pw_format pw_fchs = { "Fuchs Tracker", test_fuchs, depack_fuchs };
Java
#ifndef SDK_CONFIG_H #define SDK_CONFIG_H // <<< Use Configuration Wizard in Context Menu >>>\n #ifdef USE_APP_CONFIG #include "app_config.h" #endif // <h> Application //========================================================== // <o> ADV_INTERVAL - Advertising interval (in units of 0.625 ms) #ifndef ADV_INTERVAL #define ADV_INTERVAL 300 #endif // <s> DEVICE_NAME - Name of device. Will be included in the advertising data. #ifndef DEVICE_NAME #define DEVICE_NAME "Nordic_ATT_MTU" #endif // <o> NRF_BLE_CENTRAL_LINK_COUNT - Number of central links #ifndef NRF_BLE_CENTRAL_LINK_COUNT #define NRF_BLE_CENTRAL_LINK_COUNT 1 #endif // <o> NRF_BLE_PERIPHERAL_LINK_COUNT - Number of peripheral links #ifndef NRF_BLE_PERIPHERAL_LINK_COUNT #define NRF_BLE_PERIPHERAL_LINK_COUNT 1 #endif // <o> SCAN_INTERVAL - Scanning interval, determines scan interval in units of 0.625 millisecond. #ifndef SCAN_INTERVAL #define SCAN_INTERVAL 160 #endif // <o> SCAN_WINDOW - Scanning window, determines scan window in units of 0.625 millisecond. #ifndef SCAN_WINDOW #define SCAN_WINDOW 80 #endif // </h> //========================================================== // <h> nRF_BLE //========================================================== // <q> BLE_ADVERTISING_ENABLED - ble_advertising - Advertising module #ifndef BLE_ADVERTISING_ENABLED #define BLE_ADVERTISING_ENABLED 0 #endif // <q> BLE_DB_DISCOVERY_ENABLED - ble_db_discovery - Database discovery module #ifndef BLE_DB_DISCOVERY_ENABLED #define BLE_DB_DISCOVERY_ENABLED 1 #endif // <q> BLE_DTM_ENABLED - ble_dtm - Module for testing RF/PHY using DTM commands #ifndef BLE_DTM_ENABLED #define BLE_DTM_ENABLED 0 #endif // <q> BLE_RACP_ENABLED - ble_racp - Record Access Control Point library #ifndef BLE_RACP_ENABLED #define BLE_RACP_ENABLED 0 #endif // <e> NRF_BLE_GATT_ENABLED - nrf_ble_gatt - GATT module //========================================================== #ifndef NRF_BLE_GATT_ENABLED #define NRF_BLE_GATT_ENABLED 1 #endif #if NRF_BLE_GATT_ENABLED // <o> NRF_BLE_GATT_MAX_MTU_SIZE - Static maximum MTU size that is passed to the @ref sd_ble_enable function. #ifndef NRF_BLE_GATT_MAX_MTU_SIZE #define NRF_BLE_GATT_MAX_MTU_SIZE 247 #endif #endif //NRF_BLE_GATT_ENABLED // </e> // <q> NRF_BLE_QWR_ENABLED - nrf_ble_qwr - Queued writes support module (prepare/execute write) #ifndef NRF_BLE_QWR_ENABLED #define NRF_BLE_QWR_ENABLED 0 #endif // <q> PEER_MANAGER_ENABLED - peer_manager - Peer Manager #ifndef PEER_MANAGER_ENABLED #define PEER_MANAGER_ENABLED 0 #endif // </h> //========================================================== // <h> nRF_BLE_Services //========================================================== // <q> BLE_ANCS_C_ENABLED - ble_ancs_c - Apple Notification Service Client #ifndef BLE_ANCS_C_ENABLED #define BLE_ANCS_C_ENABLED 0 #endif // <q> BLE_ANS_C_ENABLED - ble_ans_c - Alert Notification Service Client #ifndef BLE_ANS_C_ENABLED #define BLE_ANS_C_ENABLED 0 #endif // <q> BLE_BAS_C_ENABLED - ble_bas_c - Battery Service Client #ifndef BLE_BAS_C_ENABLED #define BLE_BAS_C_ENABLED 0 #endif // <q> BLE_BAS_ENABLED - ble_bas - Battery Service #ifndef BLE_BAS_ENABLED #define BLE_BAS_ENABLED 0 #endif // <q> BLE_CSCS_ENABLED - ble_cscs - Cycling Speed and Cadence Service #ifndef BLE_CSCS_ENABLED #define BLE_CSCS_ENABLED 0 #endif // <q> BLE_CTS_C_ENABLED - ble_cts_c - Current Time Service Client #ifndef BLE_CTS_C_ENABLED #define BLE_CTS_C_ENABLED 0 #endif // <q> BLE_DIS_ENABLED - ble_dis - Device Information Service #ifndef BLE_DIS_ENABLED #define BLE_DIS_ENABLED 0 #endif // <q> BLE_GLS_ENABLED - ble_gls - Glucose Service #ifndef BLE_GLS_ENABLED #define BLE_GLS_ENABLED 0 #endif // <q> BLE_HIDS_ENABLED - ble_hids - Human Interface Device Service #ifndef BLE_HIDS_ENABLED #define BLE_HIDS_ENABLED 0 #endif // <e> BLE_HRS_C_ENABLED - ble_hrs_c - Heart Rate Service Client //========================================================== #ifndef BLE_HRS_C_ENABLED #define BLE_HRS_C_ENABLED 0 #endif #if BLE_HRS_C_ENABLED // <o> BLE_HRS_C_RR_INTERVALS_MAX_CNT - Maximum number of RR_INTERVALS per notification to be decoded #ifndef BLE_HRS_C_RR_INTERVALS_MAX_CNT #define BLE_HRS_C_RR_INTERVALS_MAX_CNT 30 #endif #endif //BLE_HRS_C_ENABLED // </e> // <q> BLE_HRS_ENABLED - ble_hrs - Heart Rate Service #ifndef BLE_HRS_ENABLED #define BLE_HRS_ENABLED 0 #endif // <q> BLE_HTS_ENABLED - ble_hts - Health Thermometer Service #ifndef BLE_HTS_ENABLED #define BLE_HTS_ENABLED 0 #endif // <q> BLE_IAS_C_ENABLED - ble_ias_c - Immediate Alert Service Client #ifndef BLE_IAS_C_ENABLED #define BLE_IAS_C_ENABLED 0 #endif // <q> BLE_IAS_ENABLED - ble_ias - Immediate Alert Service #ifndef BLE_IAS_ENABLED #define BLE_IAS_ENABLED 0 #endif // <q> BLE_LBS_C_ENABLED - ble_lbs_c - Nordic LED Button Service Client #ifndef BLE_LBS_C_ENABLED #define BLE_LBS_C_ENABLED 0 #endif // <q> BLE_LBS_ENABLED - ble_lbs - LED Button Service #ifndef BLE_LBS_ENABLED #define BLE_LBS_ENABLED 0 #endif // <q> BLE_LLS_ENABLED - ble_lls - Link Loss Service #ifndef BLE_LLS_ENABLED #define BLE_LLS_ENABLED 0 #endif // <q> BLE_NUS_C_ENABLED - ble_nus_c - Nordic UART Central Service #ifndef BLE_NUS_C_ENABLED #define BLE_NUS_C_ENABLED 0 #endif // <q> BLE_NUS_ENABLED - ble_nus - Nordic UART Service #ifndef BLE_NUS_ENABLED #define BLE_NUS_ENABLED 0 #endif // <q> BLE_RSCS_C_ENABLED - ble_rscs_c - Running Speed and Cadence Client #ifndef BLE_RSCS_C_ENABLED #define BLE_RSCS_C_ENABLED 0 #endif // <q> BLE_RSCS_ENABLED - ble_rscs - Running Speed and Cadence Service #ifndef BLE_RSCS_ENABLED #define BLE_RSCS_ENABLED 0 #endif // <q> BLE_TPS_ENABLED - ble_tps - TX Power Service #ifndef BLE_TPS_ENABLED #define BLE_TPS_ENABLED 0 #endif // </h> //========================================================== // <h> nRF_Drivers //========================================================== // <e> APP_USBD_ENABLED - app_usbd - USB Device library //========================================================== #ifndef APP_USBD_ENABLED #define APP_USBD_ENABLED 0 #endif #if APP_USBD_ENABLED // <o> APP_USBD_VID - Vendor ID <0x0000-0xFFFF> // <i> Vendor ID ordered from USB IF: http://www.usb.org/developers/vendor/ #ifndef APP_USBD_VID #define APP_USBD_VID 0 #endif // <o> APP_USBD_PID - Product ID <0x0000-0xFFFF> // <i> Selected Product ID #ifndef APP_USBD_PID #define APP_USBD_PID 0 #endif // <o> APP_USBD_DEVICE_VER_MAJOR - Device version, major part <0-99> // <i> Device version, will be converted automatically to BCD notation. Use just decimal values. #ifndef APP_USBD_DEVICE_VER_MAJOR #define APP_USBD_DEVICE_VER_MAJOR 1 #endif // <o> APP_USBD_DEVICE_VER_MINOR - Device version, minor part <0-99> // <i> Device version, will be converted automatically to BCD notation. Use just decimal values. #ifndef APP_USBD_DEVICE_VER_MINOR #define APP_USBD_DEVICE_VER_MINOR 0 #endif #endif //APP_USBD_ENABLED // </e> // <e> CLOCK_ENABLED - nrf_drv_clock - CLOCK peripheral driver //========================================================== #ifndef CLOCK_ENABLED #define CLOCK_ENABLED 1 #endif #if CLOCK_ENABLED // <o> CLOCK_CONFIG_XTAL_FREQ - HF XTAL Frequency // <0=> Default (64 MHz) #ifndef CLOCK_CONFIG_XTAL_FREQ #define CLOCK_CONFIG_XTAL_FREQ 0 #endif // <o> CLOCK_CONFIG_LF_SRC - LF Clock Source // <0=> RC // <1=> XTAL // <2=> Synth #ifndef CLOCK_CONFIG_LF_SRC #define CLOCK_CONFIG_LF_SRC 1 #endif // <o> CLOCK_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef CLOCK_CONFIG_IRQ_PRIORITY #define CLOCK_CONFIG_IRQ_PRIORITY 7 #endif // <e> CLOCK_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef CLOCK_CONFIG_LOG_ENABLED #define CLOCK_CONFIG_LOG_ENABLED 0 #endif #if CLOCK_CONFIG_LOG_ENABLED // <o> CLOCK_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef CLOCK_CONFIG_LOG_LEVEL #define CLOCK_CONFIG_LOG_LEVEL 3 #endif // <o> CLOCK_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef CLOCK_CONFIG_INFO_COLOR #define CLOCK_CONFIG_INFO_COLOR 0 #endif // <o> CLOCK_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef CLOCK_CONFIG_DEBUG_COLOR #define CLOCK_CONFIG_DEBUG_COLOR 0 #endif #endif //CLOCK_CONFIG_LOG_ENABLED // </e> #endif //CLOCK_ENABLED // </e> // <e> COMP_ENABLED - nrf_drv_comp - COMP peripheral driver //========================================================== #ifndef COMP_ENABLED #define COMP_ENABLED 0 #endif #if COMP_ENABLED // <o> COMP_CONFIG_REF - Reference voltage // <0=> Internal 1.2V // <1=> Internal 1.8V // <2=> Internal 2.4V // <4=> VDD // <7=> ARef #ifndef COMP_CONFIG_REF #define COMP_CONFIG_REF 1 #endif // <o> COMP_CONFIG_MAIN_MODE - Main mode // <0=> Single ended // <1=> Differential #ifndef COMP_CONFIG_MAIN_MODE #define COMP_CONFIG_MAIN_MODE 0 #endif // <o> COMP_CONFIG_SPEED_MODE - Speed mode // <0=> Low power // <1=> Normal // <2=> High speed #ifndef COMP_CONFIG_SPEED_MODE #define COMP_CONFIG_SPEED_MODE 2 #endif // <o> COMP_CONFIG_HYST - Hystheresis // <0=> No // <1=> 50mV #ifndef COMP_CONFIG_HYST #define COMP_CONFIG_HYST 0 #endif // <o> COMP_CONFIG_ISOURCE - Current Source // <0=> Off // <1=> 2.5 uA // <2=> 5 uA // <3=> 10 uA #ifndef COMP_CONFIG_ISOURCE #define COMP_CONFIG_ISOURCE 0 #endif // <o> COMP_CONFIG_INPUT - Analog input // <0=> 0 // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef COMP_CONFIG_INPUT #define COMP_CONFIG_INPUT 0 #endif // <o> COMP_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef COMP_CONFIG_IRQ_PRIORITY #define COMP_CONFIG_IRQ_PRIORITY 7 #endif // <e> COMP_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef COMP_CONFIG_LOG_ENABLED #define COMP_CONFIG_LOG_ENABLED 0 #endif #if COMP_CONFIG_LOG_ENABLED // <o> COMP_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef COMP_CONFIG_LOG_LEVEL #define COMP_CONFIG_LOG_LEVEL 3 #endif // <o> COMP_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMP_CONFIG_INFO_COLOR #define COMP_CONFIG_INFO_COLOR 0 #endif // <o> COMP_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMP_CONFIG_DEBUG_COLOR #define COMP_CONFIG_DEBUG_COLOR 0 #endif #endif //COMP_CONFIG_LOG_ENABLED // </e> #endif //COMP_ENABLED // </e> // <e> EGU_ENABLED - nrf_drv_swi - SWI(EGU) peripheral driver //========================================================== #ifndef EGU_ENABLED #define EGU_ENABLED 0 #endif #if EGU_ENABLED // <e> SWI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SWI_CONFIG_LOG_ENABLED #define SWI_CONFIG_LOG_ENABLED 0 #endif #if SWI_CONFIG_LOG_ENABLED // <o> SWI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SWI_CONFIG_LOG_LEVEL #define SWI_CONFIG_LOG_LEVEL 3 #endif // <o> SWI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SWI_CONFIG_INFO_COLOR #define SWI_CONFIG_INFO_COLOR 0 #endif // <o> SWI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SWI_CONFIG_DEBUG_COLOR #define SWI_CONFIG_DEBUG_COLOR 0 #endif #endif //SWI_CONFIG_LOG_ENABLED // </e> #endif //EGU_ENABLED // </e> // <e> GPIOTE_ENABLED - nrf_drv_gpiote - GPIOTE peripheral driver //========================================================== #ifndef GPIOTE_ENABLED #define GPIOTE_ENABLED 1 #endif #if GPIOTE_ENABLED // <o> GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS - Number of lower power input pins #ifndef GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS #define GPIOTE_CONFIG_NUM_OF_LOW_POWER_EVENTS 4 #endif // <o> GPIOTE_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef GPIOTE_CONFIG_IRQ_PRIORITY #define GPIOTE_CONFIG_IRQ_PRIORITY 7 #endif // <e> GPIOTE_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef GPIOTE_CONFIG_LOG_ENABLED #define GPIOTE_CONFIG_LOG_ENABLED 0 #endif #if GPIOTE_CONFIG_LOG_ENABLED // <o> GPIOTE_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef GPIOTE_CONFIG_LOG_LEVEL #define GPIOTE_CONFIG_LOG_LEVEL 3 #endif // <o> GPIOTE_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef GPIOTE_CONFIG_INFO_COLOR #define GPIOTE_CONFIG_INFO_COLOR 0 #endif // <o> GPIOTE_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef GPIOTE_CONFIG_DEBUG_COLOR #define GPIOTE_CONFIG_DEBUG_COLOR 0 #endif #endif //GPIOTE_CONFIG_LOG_ENABLED // </e> #endif //GPIOTE_ENABLED // </e> // <e> I2S_ENABLED - nrf_drv_i2s - I2S peripheral driver //========================================================== #ifndef I2S_ENABLED #define I2S_ENABLED 0 #endif #if I2S_ENABLED // <o> I2S_CONFIG_SCK_PIN - SCK pin <0-31> #ifndef I2S_CONFIG_SCK_PIN #define I2S_CONFIG_SCK_PIN 31 #endif // <o> I2S_CONFIG_LRCK_PIN - LRCK pin <1-31> #ifndef I2S_CONFIG_LRCK_PIN #define I2S_CONFIG_LRCK_PIN 30 #endif // <o> I2S_CONFIG_MCK_PIN - MCK pin #ifndef I2S_CONFIG_MCK_PIN #define I2S_CONFIG_MCK_PIN 255 #endif // <o> I2S_CONFIG_SDOUT_PIN - SDOUT pin <0-31> #ifndef I2S_CONFIG_SDOUT_PIN #define I2S_CONFIG_SDOUT_PIN 29 #endif // <o> I2S_CONFIG_SDIN_PIN - SDIN pin <0-31> #ifndef I2S_CONFIG_SDIN_PIN #define I2S_CONFIG_SDIN_PIN 28 #endif // <o> I2S_CONFIG_MASTER - Mode // <0=> Master // <1=> Slave #ifndef I2S_CONFIG_MASTER #define I2S_CONFIG_MASTER 0 #endif // <o> I2S_CONFIG_FORMAT - Format // <0=> I2S // <1=> Aligned #ifndef I2S_CONFIG_FORMAT #define I2S_CONFIG_FORMAT 0 #endif // <o> I2S_CONFIG_ALIGN - Alignment // <0=> Left // <1=> Right #ifndef I2S_CONFIG_ALIGN #define I2S_CONFIG_ALIGN 0 #endif // <o> I2S_CONFIG_SWIDTH - Sample width (bits) // <0=> 8 // <1=> 16 // <2=> 24 #ifndef I2S_CONFIG_SWIDTH #define I2S_CONFIG_SWIDTH 1 #endif // <o> I2S_CONFIG_CHANNELS - Channels // <0=> Stereo // <1=> Left // <2=> Right #ifndef I2S_CONFIG_CHANNELS #define I2S_CONFIG_CHANNELS 1 #endif // <o> I2S_CONFIG_MCK_SETUP - MCK behavior // <0=> Disabled // <2147483648=> 32MHz/2 // <1342177280=> 32MHz/3 // <1073741824=> 32MHz/4 // <805306368=> 32MHz/5 // <671088640=> 32MHz/6 // <536870912=> 32MHz/8 // <402653184=> 32MHz/10 // <369098752=> 32MHz/11 // <285212672=> 32MHz/15 // <268435456=> 32MHz/16 // <201326592=> 32MHz/21 // <184549376=> 32MHz/23 // <142606336=> 32MHz/30 // <138412032=> 32MHz/31 // <134217728=> 32MHz/32 // <100663296=> 32MHz/42 // <68157440=> 32MHz/63 // <34340864=> 32MHz/125 #ifndef I2S_CONFIG_MCK_SETUP #define I2S_CONFIG_MCK_SETUP 536870912 #endif // <o> I2S_CONFIG_RATIO - MCK/LRCK ratio // <0=> 32x // <1=> 48x // <2=> 64x // <3=> 96x // <4=> 128x // <5=> 192x // <6=> 256x // <7=> 384x // <8=> 512x #ifndef I2S_CONFIG_RATIO #define I2S_CONFIG_RATIO 2000 #endif // <o> I2S_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef I2S_CONFIG_IRQ_PRIORITY #define I2S_CONFIG_IRQ_PRIORITY 7 #endif // <e> I2S_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef I2S_CONFIG_LOG_ENABLED #define I2S_CONFIG_LOG_ENABLED 0 #endif #if I2S_CONFIG_LOG_ENABLED // <o> I2S_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef I2S_CONFIG_LOG_LEVEL #define I2S_CONFIG_LOG_LEVEL 3 #endif // <o> I2S_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef I2S_CONFIG_INFO_COLOR #define I2S_CONFIG_INFO_COLOR 0 #endif // <o> I2S_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef I2S_CONFIG_DEBUG_COLOR #define I2S_CONFIG_DEBUG_COLOR 0 #endif #endif //I2S_CONFIG_LOG_ENABLED // </e> #endif //I2S_ENABLED // </e> // <e> LPCOMP_ENABLED - nrf_drv_lpcomp - LPCOMP peripheral driver //========================================================== #ifndef LPCOMP_ENABLED #define LPCOMP_ENABLED 0 #endif #if LPCOMP_ENABLED // <o> LPCOMP_CONFIG_REFERENCE - Reference voltage // <0=> Supply 1/8 // <1=> Supply 2/8 // <2=> Supply 3/8 // <3=> Supply 4/8 // <4=> Supply 5/8 // <5=> Supply 6/8 // <6=> Supply 7/8 // <8=> Supply 1/16 (nRF52) // <9=> Supply 3/16 (nRF52) // <10=> Supply 5/16 (nRF52) // <11=> Supply 7/16 (nRF52) // <12=> Supply 9/16 (nRF52) // <13=> Supply 11/16 (nRF52) // <14=> Supply 13/16 (nRF52) // <15=> Supply 15/16 (nRF52) // <7=> External Ref 0 // <65543=> External Ref 1 #ifndef LPCOMP_CONFIG_REFERENCE #define LPCOMP_CONFIG_REFERENCE 3 #endif // <o> LPCOMP_CONFIG_DETECTION - Detection // <0=> Crossing // <1=> Up // <2=> Down #ifndef LPCOMP_CONFIG_DETECTION #define LPCOMP_CONFIG_DETECTION 2 #endif // <o> LPCOMP_CONFIG_INPUT - Analog input // <0=> 0 // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef LPCOMP_CONFIG_INPUT #define LPCOMP_CONFIG_INPUT 0 #endif // <q> LPCOMP_CONFIG_HYST - Hysteresis #ifndef LPCOMP_CONFIG_HYST #define LPCOMP_CONFIG_HYST 0 #endif // <o> LPCOMP_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef LPCOMP_CONFIG_IRQ_PRIORITY #define LPCOMP_CONFIG_IRQ_PRIORITY 7 #endif // <e> LPCOMP_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef LPCOMP_CONFIG_LOG_ENABLED #define LPCOMP_CONFIG_LOG_ENABLED 0 #endif #if LPCOMP_CONFIG_LOG_ENABLED // <o> LPCOMP_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef LPCOMP_CONFIG_LOG_LEVEL #define LPCOMP_CONFIG_LOG_LEVEL 3 #endif // <o> LPCOMP_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef LPCOMP_CONFIG_INFO_COLOR #define LPCOMP_CONFIG_INFO_COLOR 0 #endif // <o> LPCOMP_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef LPCOMP_CONFIG_DEBUG_COLOR #define LPCOMP_CONFIG_DEBUG_COLOR 0 #endif #endif //LPCOMP_CONFIG_LOG_ENABLED // </e> #endif //LPCOMP_ENABLED // </e> // <e> PDM_ENABLED - nrf_drv_pdm - PDM peripheral driver //========================================================== #ifndef PDM_ENABLED #define PDM_ENABLED 0 #endif #if PDM_ENABLED // <o> PDM_CONFIG_MODE - Mode // <0=> Stereo // <1=> Mono #ifndef PDM_CONFIG_MODE #define PDM_CONFIG_MODE 1 #endif // <o> PDM_CONFIG_EDGE - Edge // <0=> Left falling // <1=> Left rising #ifndef PDM_CONFIG_EDGE #define PDM_CONFIG_EDGE 0 #endif // <o> PDM_CONFIG_CLOCK_FREQ - Clock frequency // <134217728=> 1000k // <138412032=> 1032k (default) // <142606336=> 1067k #ifndef PDM_CONFIG_CLOCK_FREQ #define PDM_CONFIG_CLOCK_FREQ 138412032 #endif // <o> PDM_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef PDM_CONFIG_IRQ_PRIORITY #define PDM_CONFIG_IRQ_PRIORITY 7 #endif // <e> PDM_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef PDM_CONFIG_LOG_ENABLED #define PDM_CONFIG_LOG_ENABLED 0 #endif #if PDM_CONFIG_LOG_ENABLED // <o> PDM_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef PDM_CONFIG_LOG_LEVEL #define PDM_CONFIG_LOG_LEVEL 3 #endif // <o> PDM_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PDM_CONFIG_INFO_COLOR #define PDM_CONFIG_INFO_COLOR 0 #endif // <o> PDM_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PDM_CONFIG_DEBUG_COLOR #define PDM_CONFIG_DEBUG_COLOR 0 #endif #endif //PDM_CONFIG_LOG_ENABLED // </e> #endif //PDM_ENABLED // </e> // <e> PERIPHERAL_RESOURCE_SHARING_ENABLED - nrf_drv_common - Peripheral drivers common module //========================================================== #ifndef PERIPHERAL_RESOURCE_SHARING_ENABLED #define PERIPHERAL_RESOURCE_SHARING_ENABLED 0 #endif #if PERIPHERAL_RESOURCE_SHARING_ENABLED // <e> COMMON_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef COMMON_CONFIG_LOG_ENABLED #define COMMON_CONFIG_LOG_ENABLED 0 #endif #if COMMON_CONFIG_LOG_ENABLED // <o> COMMON_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef COMMON_CONFIG_LOG_LEVEL #define COMMON_CONFIG_LOG_LEVEL 3 #endif // <o> COMMON_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMMON_CONFIG_INFO_COLOR #define COMMON_CONFIG_INFO_COLOR 0 #endif // <o> COMMON_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef COMMON_CONFIG_DEBUG_COLOR #define COMMON_CONFIG_DEBUG_COLOR 0 #endif #endif //COMMON_CONFIG_LOG_ENABLED // </e> #endif //PERIPHERAL_RESOURCE_SHARING_ENABLED // </e> // <e> POWER_ENABLED - nrf_drv_power - POWER peripheral driver //========================================================== #ifndef POWER_ENABLED #define POWER_ENABLED 0 #endif #if POWER_ENABLED // <o> POWER_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef POWER_CONFIG_IRQ_PRIORITY #define POWER_CONFIG_IRQ_PRIORITY 7 #endif // <q> POWER_CONFIG_DEFAULT_DCDCEN - The default configuration of main DCDC regulator // <i> This settings means only that components for DCDC regulator are installed and it can be enabled. #ifndef POWER_CONFIG_DEFAULT_DCDCEN #define POWER_CONFIG_DEFAULT_DCDCEN 0 #endif // <q> POWER_CONFIG_DEFAULT_DCDCENHV - The default configuration of High Voltage DCDC regulator // <i> This settings means only that components for DCDC regulator are installed and it can be enabled. #ifndef POWER_CONFIG_DEFAULT_DCDCENHV #define POWER_CONFIG_DEFAULT_DCDCENHV 0 #endif #endif //POWER_ENABLED // </e> // <e> PPI_ENABLED - nrf_drv_ppi - PPI peripheral driver //========================================================== #ifndef PPI_ENABLED #define PPI_ENABLED 0 #endif #if PPI_ENABLED // <e> PPI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef PPI_CONFIG_LOG_ENABLED #define PPI_CONFIG_LOG_ENABLED 0 #endif #if PPI_CONFIG_LOG_ENABLED // <o> PPI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef PPI_CONFIG_LOG_LEVEL #define PPI_CONFIG_LOG_LEVEL 3 #endif // <o> PPI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PPI_CONFIG_INFO_COLOR #define PPI_CONFIG_INFO_COLOR 0 #endif // <o> PPI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PPI_CONFIG_DEBUG_COLOR #define PPI_CONFIG_DEBUG_COLOR 0 #endif #endif //PPI_CONFIG_LOG_ENABLED // </e> #endif //PPI_ENABLED // </e> // <e> PWM_ENABLED - nrf_drv_pwm - PWM peripheral driver //========================================================== #ifndef PWM_ENABLED #define PWM_ENABLED 0 #endif #if PWM_ENABLED // <o> PWM_DEFAULT_CONFIG_OUT0_PIN - Out0 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT0_PIN #define PWM_DEFAULT_CONFIG_OUT0_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_OUT1_PIN - Out1 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT1_PIN #define PWM_DEFAULT_CONFIG_OUT1_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_OUT2_PIN - Out2 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT2_PIN #define PWM_DEFAULT_CONFIG_OUT2_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_OUT3_PIN - Out3 pin <0-31> #ifndef PWM_DEFAULT_CONFIG_OUT3_PIN #define PWM_DEFAULT_CONFIG_OUT3_PIN 31 #endif // <o> PWM_DEFAULT_CONFIG_BASE_CLOCK - Base clock // <0=> 16 MHz // <1=> 8 MHz // <2=> 4 MHz // <3=> 2 MHz // <4=> 1 MHz // <5=> 500 kHz // <6=> 250 kHz // <7=> 125 MHz #ifndef PWM_DEFAULT_CONFIG_BASE_CLOCK #define PWM_DEFAULT_CONFIG_BASE_CLOCK 4 #endif // <o> PWM_DEFAULT_CONFIG_COUNT_MODE - Count mode // <0=> Up // <1=> Up and Down #ifndef PWM_DEFAULT_CONFIG_COUNT_MODE #define PWM_DEFAULT_CONFIG_COUNT_MODE 0 #endif // <o> PWM_DEFAULT_CONFIG_TOP_VALUE - Top value #ifndef PWM_DEFAULT_CONFIG_TOP_VALUE #define PWM_DEFAULT_CONFIG_TOP_VALUE 1000 #endif // <o> PWM_DEFAULT_CONFIG_LOAD_MODE - Load mode // <0=> Common // <1=> Grouped // <2=> Individual // <3=> Waveform #ifndef PWM_DEFAULT_CONFIG_LOAD_MODE #define PWM_DEFAULT_CONFIG_LOAD_MODE 0 #endif // <o> PWM_DEFAULT_CONFIG_STEP_MODE - Step mode // <0=> Auto // <1=> Triggered #ifndef PWM_DEFAULT_CONFIG_STEP_MODE #define PWM_DEFAULT_CONFIG_STEP_MODE 0 #endif // <o> PWM_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef PWM_DEFAULT_CONFIG_IRQ_PRIORITY #define PWM_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> PWM0_ENABLED - Enable PWM0 instance #ifndef PWM0_ENABLED #define PWM0_ENABLED 0 #endif // <q> PWM1_ENABLED - Enable PWM1 instance #ifndef PWM1_ENABLED #define PWM1_ENABLED 0 #endif // <q> PWM2_ENABLED - Enable PWM2 instance #ifndef PWM2_ENABLED #define PWM2_ENABLED 0 #endif // <e> PWM_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef PWM_CONFIG_LOG_ENABLED #define PWM_CONFIG_LOG_ENABLED 0 #endif #if PWM_CONFIG_LOG_ENABLED // <o> PWM_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef PWM_CONFIG_LOG_LEVEL #define PWM_CONFIG_LOG_LEVEL 3 #endif // <o> PWM_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PWM_CONFIG_INFO_COLOR #define PWM_CONFIG_INFO_COLOR 0 #endif // <o> PWM_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef PWM_CONFIG_DEBUG_COLOR #define PWM_CONFIG_DEBUG_COLOR 0 #endif #endif //PWM_CONFIG_LOG_ENABLED // </e> // <e> PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 Anomaly 109 workaround for PWM. // <i> The workaround uses interrupts to wake up the CPU and ensure // <i> it is active when PWM is about to start a DMA transfer. For // <i> initial transfer, done when a playback is started via PPI, // <i> a specific EGU instance is used to generate the interrupt. // <i> During the playback, the PWM interrupt triggered on SEQEND // <i> event of a preceding sequence is used to protect the transfer // <i> done for the next sequence to be played. //========================================================== #ifndef PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #if PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED // <o> PWM_NRF52_ANOMALY_109_EGU_INSTANCE - EGU instance used by the nRF52 Anomaly 109 workaround for PWM. // <0=> EGU0 // <1=> EGU1 // <2=> EGU2 // <3=> EGU3 // <4=> EGU4 // <5=> EGU5 #ifndef PWM_NRF52_ANOMALY_109_EGU_INSTANCE #define PWM_NRF52_ANOMALY_109_EGU_INSTANCE 5 #endif #endif //PWM_NRF52_ANOMALY_109_WORKAROUND_ENABLED // </e> #endif //PWM_ENABLED // </e> // <e> QDEC_ENABLED - nrf_drv_qdec - QDEC peripheral driver //========================================================== #ifndef QDEC_ENABLED #define QDEC_ENABLED 0 #endif #if QDEC_ENABLED // <o> QDEC_CONFIG_REPORTPER - Report period // <0=> 10 Samples // <1=> 40 Samples // <2=> 80 Samples // <3=> 120 Samples // <4=> 160 Samples // <5=> 200 Samples // <6=> 240 Samples // <7=> 280 Samples #ifndef QDEC_CONFIG_REPORTPER #define QDEC_CONFIG_REPORTPER 0 #endif // <o> QDEC_CONFIG_SAMPLEPER - Sample period // <0=> 128 us // <1=> 256 us // <2=> 512 us // <3=> 1024 us // <4=> 2048 us // <5=> 4096 us // <6=> 8192 us // <7=> 16384 us #ifndef QDEC_CONFIG_SAMPLEPER #define QDEC_CONFIG_SAMPLEPER 7 #endif // <o> QDEC_CONFIG_PIO_A - A pin <0-31> #ifndef QDEC_CONFIG_PIO_A #define QDEC_CONFIG_PIO_A 31 #endif // <o> QDEC_CONFIG_PIO_B - B pin <0-31> #ifndef QDEC_CONFIG_PIO_B #define QDEC_CONFIG_PIO_B 31 #endif // <o> QDEC_CONFIG_PIO_LED - LED pin <0-31> #ifndef QDEC_CONFIG_PIO_LED #define QDEC_CONFIG_PIO_LED 31 #endif // <o> QDEC_CONFIG_LEDPRE - LED pre #ifndef QDEC_CONFIG_LEDPRE #define QDEC_CONFIG_LEDPRE 511 #endif // <o> QDEC_CONFIG_LEDPOL - LED polarity // <0=> Active low // <1=> Active high #ifndef QDEC_CONFIG_LEDPOL #define QDEC_CONFIG_LEDPOL 1 #endif // <q> QDEC_CONFIG_DBFEN - Debouncing enable #ifndef QDEC_CONFIG_DBFEN #define QDEC_CONFIG_DBFEN 0 #endif // <q> QDEC_CONFIG_SAMPLE_INTEN - Sample ready interrupt enable #ifndef QDEC_CONFIG_SAMPLE_INTEN #define QDEC_CONFIG_SAMPLE_INTEN 0 #endif // <o> QDEC_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef QDEC_CONFIG_IRQ_PRIORITY #define QDEC_CONFIG_IRQ_PRIORITY 7 #endif // <e> QDEC_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef QDEC_CONFIG_LOG_ENABLED #define QDEC_CONFIG_LOG_ENABLED 0 #endif #if QDEC_CONFIG_LOG_ENABLED // <o> QDEC_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef QDEC_CONFIG_LOG_LEVEL #define QDEC_CONFIG_LOG_LEVEL 3 #endif // <o> QDEC_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef QDEC_CONFIG_INFO_COLOR #define QDEC_CONFIG_INFO_COLOR 0 #endif // <o> QDEC_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef QDEC_CONFIG_DEBUG_COLOR #define QDEC_CONFIG_DEBUG_COLOR 0 #endif #endif //QDEC_CONFIG_LOG_ENABLED // </e> #endif //QDEC_ENABLED // </e> // <e> RNG_ENABLED - nrf_drv_rng - RNG peripheral driver //========================================================== #ifndef RNG_ENABLED #define RNG_ENABLED 0 #endif #if RNG_ENABLED // <q> RNG_CONFIG_ERROR_CORRECTION - Error correction #ifndef RNG_CONFIG_ERROR_CORRECTION #define RNG_CONFIG_ERROR_CORRECTION 0 #endif // <o> RNG_CONFIG_POOL_SIZE - Pool size #ifndef RNG_CONFIG_POOL_SIZE #define RNG_CONFIG_POOL_SIZE 32 #endif // <o> RNG_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef RNG_CONFIG_IRQ_PRIORITY #define RNG_CONFIG_IRQ_PRIORITY 7 #endif // <e> RNG_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef RNG_CONFIG_LOG_ENABLED #define RNG_CONFIG_LOG_ENABLED 0 #endif #if RNG_CONFIG_LOG_ENABLED // <o> RNG_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef RNG_CONFIG_LOG_LEVEL #define RNG_CONFIG_LOG_LEVEL 3 #endif // <o> RNG_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RNG_CONFIG_INFO_COLOR #define RNG_CONFIG_INFO_COLOR 0 #endif // <o> RNG_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RNG_CONFIG_DEBUG_COLOR #define RNG_CONFIG_DEBUG_COLOR 0 #endif // <q> RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED - Enables logging of random numbers. #ifndef RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED #define RNG_CONFIG_RANDOM_NUMBER_LOG_ENABLED 0 #endif #endif //RNG_CONFIG_LOG_ENABLED // </e> #endif //RNG_ENABLED // </e> // <e> RTC_ENABLED - nrf_drv_rtc - RTC peripheral driver //========================================================== #ifndef RTC_ENABLED #define RTC_ENABLED 1 #endif #if RTC_ENABLED // <o> RTC_DEFAULT_CONFIG_FREQUENCY - Frequency <16-32768> #ifndef RTC_DEFAULT_CONFIG_FREQUENCY #define RTC_DEFAULT_CONFIG_FREQUENCY 32768 #endif // <q> RTC_DEFAULT_CONFIG_RELIABLE - Ensures safe compare event triggering #ifndef RTC_DEFAULT_CONFIG_RELIABLE #define RTC_DEFAULT_CONFIG_RELIABLE 0 #endif // <o> RTC_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef RTC_DEFAULT_CONFIG_IRQ_PRIORITY #define RTC_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> RTC0_ENABLED - Enable RTC0 instance #ifndef RTC0_ENABLED #define RTC0_ENABLED 0 #endif // <q> RTC1_ENABLED - Enable RTC1 instance #ifndef RTC1_ENABLED #define RTC1_ENABLED 0 #endif // <q> RTC2_ENABLED - Enable RTC2 instance #ifndef RTC2_ENABLED #define RTC2_ENABLED 1 #endif // <o> NRF_MAXIMUM_LATENCY_US - Maximum possible time[us] in highest priority interrupt #ifndef NRF_MAXIMUM_LATENCY_US #define NRF_MAXIMUM_LATENCY_US 2000 #endif // <e> RTC_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef RTC_CONFIG_LOG_ENABLED #define RTC_CONFIG_LOG_ENABLED 0 #endif #if RTC_CONFIG_LOG_ENABLED // <o> RTC_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef RTC_CONFIG_LOG_LEVEL #define RTC_CONFIG_LOG_LEVEL 3 #endif // <o> RTC_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RTC_CONFIG_INFO_COLOR #define RTC_CONFIG_INFO_COLOR 0 #endif // <o> RTC_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef RTC_CONFIG_DEBUG_COLOR #define RTC_CONFIG_DEBUG_COLOR 0 #endif #endif //RTC_CONFIG_LOG_ENABLED // </e> #endif //RTC_ENABLED // </e> // <e> SAADC_ENABLED - nrf_drv_saadc - SAADC peripheral driver //========================================================== #ifndef SAADC_ENABLED #define SAADC_ENABLED 0 #endif #if SAADC_ENABLED // <o> SAADC_CONFIG_RESOLUTION - Resolution // <0=> 8 bit // <1=> 10 bit // <2=> 12 bit // <3=> 14 bit #ifndef SAADC_CONFIG_RESOLUTION #define SAADC_CONFIG_RESOLUTION 1 #endif // <o> SAADC_CONFIG_OVERSAMPLE - Sample period // <0=> Disabled // <1=> 2x // <2=> 4x // <3=> 8x // <4=> 16x // <5=> 32x // <6=> 64x // <7=> 128x // <8=> 256x #ifndef SAADC_CONFIG_OVERSAMPLE #define SAADC_CONFIG_OVERSAMPLE 0 #endif // <q> SAADC_CONFIG_LP_MODE - Enabling low power mode #ifndef SAADC_CONFIG_LP_MODE #define SAADC_CONFIG_LP_MODE 0 #endif // <o> SAADC_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef SAADC_CONFIG_IRQ_PRIORITY #define SAADC_CONFIG_IRQ_PRIORITY 7 #endif // <e> SAADC_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SAADC_CONFIG_LOG_ENABLED #define SAADC_CONFIG_LOG_ENABLED 0 #endif #if SAADC_CONFIG_LOG_ENABLED // <o> SAADC_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SAADC_CONFIG_LOG_LEVEL #define SAADC_CONFIG_LOG_LEVEL 3 #endif // <o> SAADC_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SAADC_CONFIG_INFO_COLOR #define SAADC_CONFIG_INFO_COLOR 0 #endif // <o> SAADC_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SAADC_CONFIG_DEBUG_COLOR #define SAADC_CONFIG_DEBUG_COLOR 0 #endif #endif //SAADC_CONFIG_LOG_ENABLED // </e> #endif //SAADC_ENABLED // </e> // <e> SPIS_ENABLED - nrf_drv_spis - SPI Slave driver //========================================================== #ifndef SPIS_ENABLED #define SPIS_ENABLED 0 #endif #if SPIS_ENABLED // <o> SPIS_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef SPIS_DEFAULT_CONFIG_IRQ_PRIORITY #define SPIS_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <o> SPIS_DEFAULT_MODE - Mode // <0=> MODE_0 // <1=> MODE_1 // <2=> MODE_2 // <3=> MODE_3 #ifndef SPIS_DEFAULT_MODE #define SPIS_DEFAULT_MODE 0 #endif // <o> SPIS_DEFAULT_BIT_ORDER - SPIS default bit order // <0=> MSB first // <1=> LSB first #ifndef SPIS_DEFAULT_BIT_ORDER #define SPIS_DEFAULT_BIT_ORDER 0 #endif // <o> SPIS_DEFAULT_DEF - SPIS default DEF character <0-255> #ifndef SPIS_DEFAULT_DEF #define SPIS_DEFAULT_DEF 255 #endif // <o> SPIS_DEFAULT_ORC - SPIS default ORC character <0-255> #ifndef SPIS_DEFAULT_ORC #define SPIS_DEFAULT_ORC 255 #endif // <q> SPIS0_ENABLED - Enable SPIS0 instance #ifndef SPIS0_ENABLED #define SPIS0_ENABLED 0 #endif // <q> SPIS1_ENABLED - Enable SPIS1 instance #ifndef SPIS1_ENABLED #define SPIS1_ENABLED 0 #endif // <q> SPIS2_ENABLED - Enable SPIS2 instance #ifndef SPIS2_ENABLED #define SPIS2_ENABLED 0 #endif // <e> SPIS_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SPIS_CONFIG_LOG_ENABLED #define SPIS_CONFIG_LOG_ENABLED 0 #endif #if SPIS_CONFIG_LOG_ENABLED // <o> SPIS_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SPIS_CONFIG_LOG_LEVEL #define SPIS_CONFIG_LOG_LEVEL 3 #endif // <o> SPIS_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPIS_CONFIG_INFO_COLOR #define SPIS_CONFIG_INFO_COLOR 0 #endif // <o> SPIS_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPIS_CONFIG_DEBUG_COLOR #define SPIS_CONFIG_DEBUG_COLOR 0 #endif #endif //SPIS_CONFIG_LOG_ENABLED // </e> // <q> SPIS_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 Anomaly 109 workaround for SPIS. // <i> The workaround uses a GPIOTE channel to generate interrupts // <i> on falling edges detected on the CSN line. This will make // <i> the CPU active for the moment when SPIS starts DMA transfers, // <i> and this way the transfers will be protected. // <i> This workaround uses GPIOTE driver, so this driver must be // <i> enabled as well. #ifndef SPIS_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define SPIS_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #endif //SPIS_ENABLED // </e> // <e> SPI_ENABLED - nrf_drv_spi - SPI/SPIM peripheral driver //========================================================== #ifndef SPI_ENABLED #define SPI_ENABLED 0 #endif #if SPI_ENABLED // <o> SPI_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef SPI_DEFAULT_CONFIG_IRQ_PRIORITY #define SPI_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <e> SPI0_ENABLED - Enable SPI0 instance //========================================================== #ifndef SPI0_ENABLED #define SPI0_ENABLED 0 #endif #if SPI0_ENABLED // <q> SPI0_USE_EASY_DMA - Use EasyDMA #ifndef SPI0_USE_EASY_DMA #define SPI0_USE_EASY_DMA 1 #endif // <o> SPI0_DEFAULT_FREQUENCY - SPI frequency // <33554432=> 125 kHz // <67108864=> 250 kHz // <134217728=> 500 kHz // <268435456=> 1 MHz // <536870912=> 2 MHz // <1073741824=> 4 MHz // <2147483648=> 8 MHz #ifndef SPI0_DEFAULT_FREQUENCY #define SPI0_DEFAULT_FREQUENCY 1073741824 #endif #endif //SPI0_ENABLED // </e> // <e> SPI1_ENABLED - Enable SPI1 instance //========================================================== #ifndef SPI1_ENABLED #define SPI1_ENABLED 0 #endif #if SPI1_ENABLED // <q> SPI1_USE_EASY_DMA - Use EasyDMA #ifndef SPI1_USE_EASY_DMA #define SPI1_USE_EASY_DMA 1 #endif // <o> SPI1_DEFAULT_FREQUENCY - SPI frequency // <33554432=> 125 kHz // <67108864=> 250 kHz // <134217728=> 500 kHz // <268435456=> 1 MHz // <536870912=> 2 MHz // <1073741824=> 4 MHz // <2147483648=> 8 MHz #ifndef SPI1_DEFAULT_FREQUENCY #define SPI1_DEFAULT_FREQUENCY 1073741824 #endif #endif //SPI1_ENABLED // </e> // <e> SPI2_ENABLED - Enable SPI2 instance //========================================================== #ifndef SPI2_ENABLED #define SPI2_ENABLED 0 #endif #if SPI2_ENABLED // <q> SPI2_USE_EASY_DMA - Use EasyDMA #ifndef SPI2_USE_EASY_DMA #define SPI2_USE_EASY_DMA 1 #endif // <q> SPI2_DEFAULT_FREQUENCY - Use EasyDMA #ifndef SPI2_DEFAULT_FREQUENCY #define SPI2_DEFAULT_FREQUENCY 1 #endif #endif //SPI2_ENABLED // </e> // <e> SPI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef SPI_CONFIG_LOG_ENABLED #define SPI_CONFIG_LOG_ENABLED 0 #endif #if SPI_CONFIG_LOG_ENABLED // <o> SPI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef SPI_CONFIG_LOG_LEVEL #define SPI_CONFIG_LOG_LEVEL 3 #endif // <o> SPI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPI_CONFIG_INFO_COLOR #define SPI_CONFIG_INFO_COLOR 0 #endif // <o> SPI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef SPI_CONFIG_DEBUG_COLOR #define SPI_CONFIG_DEBUG_COLOR 0 #endif #endif //SPI_CONFIG_LOG_ENABLED // </e> // <q> SPIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 anomaly 109 workaround for SPIM. // <i> The workaround uses interrupts to wake up the CPU by catching // <i> a start event of zero-length transmission to start the clock. This // <i> ensures that the DMA transfer will be executed without issues and // <i> that the proper transfer will be started. See more in the Errata // <i> document or Anomaly 109 Addendum located at // <i> https://infocenter.nordicsemi.com/ #ifndef SPIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define SPIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #endif //SPI_ENABLED // </e> // <e> TIMER_ENABLED - nrf_drv_timer - TIMER periperal driver //========================================================== #ifndef TIMER_ENABLED #define TIMER_ENABLED 0 #endif #if TIMER_ENABLED // <o> TIMER_DEFAULT_CONFIG_FREQUENCY - Timer frequency if in Timer mode // <0=> 16 MHz // <1=> 8 MHz // <2=> 4 MHz // <3=> 2 MHz // <4=> 1 MHz // <5=> 500 kHz // <6=> 250 kHz // <7=> 125 kHz // <8=> 62.5 kHz // <9=> 31.25 kHz #ifndef TIMER_DEFAULT_CONFIG_FREQUENCY #define TIMER_DEFAULT_CONFIG_FREQUENCY 0 #endif // <o> TIMER_DEFAULT_CONFIG_MODE - Timer mode or operation // <0=> Timer // <1=> Counter #ifndef TIMER_DEFAULT_CONFIG_MODE #define TIMER_DEFAULT_CONFIG_MODE 0 #endif // <o> TIMER_DEFAULT_CONFIG_BIT_WIDTH - Timer counter bit width // <0=> 16 bit // <1=> 8 bit // <2=> 24 bit // <3=> 32 bit #ifndef TIMER_DEFAULT_CONFIG_BIT_WIDTH #define TIMER_DEFAULT_CONFIG_BIT_WIDTH 0 #endif // <o> TIMER_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef TIMER_DEFAULT_CONFIG_IRQ_PRIORITY #define TIMER_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> TIMER0_ENABLED - Enable TIMER0 instance #ifndef TIMER0_ENABLED #define TIMER0_ENABLED 0 #endif // <q> TIMER1_ENABLED - Enable TIMER1 instance #ifndef TIMER1_ENABLED #define TIMER1_ENABLED 0 #endif // <q> TIMER2_ENABLED - Enable TIMER2 instance #ifndef TIMER2_ENABLED #define TIMER2_ENABLED 0 #endif // <q> TIMER3_ENABLED - Enable TIMER3 instance #ifndef TIMER3_ENABLED #define TIMER3_ENABLED 0 #endif // <q> TIMER4_ENABLED - Enable TIMER4 instance #ifndef TIMER4_ENABLED #define TIMER4_ENABLED 0 #endif // <e> TIMER_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef TIMER_CONFIG_LOG_ENABLED #define TIMER_CONFIG_LOG_ENABLED 0 #endif #if TIMER_CONFIG_LOG_ENABLED // <o> TIMER_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef TIMER_CONFIG_LOG_LEVEL #define TIMER_CONFIG_LOG_LEVEL 3 #endif // <o> TIMER_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TIMER_CONFIG_INFO_COLOR #define TIMER_CONFIG_INFO_COLOR 0 #endif // <o> TIMER_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TIMER_CONFIG_DEBUG_COLOR #define TIMER_CONFIG_DEBUG_COLOR 0 #endif #endif //TIMER_CONFIG_LOG_ENABLED // </e> #endif //TIMER_ENABLED // </e> // <e> TWIS_ENABLED - nrf_drv_twis - TWIS peripheral driver //========================================================== #ifndef TWIS_ENABLED #define TWIS_ENABLED 0 #endif #if TWIS_ENABLED // <o> TWIS_DEFAULT_CONFIG_ADDR0 - Address0 #ifndef TWIS_DEFAULT_CONFIG_ADDR0 #define TWIS_DEFAULT_CONFIG_ADDR0 0 #endif // <o> TWIS_DEFAULT_CONFIG_ADDR1 - Address1 #ifndef TWIS_DEFAULT_CONFIG_ADDR1 #define TWIS_DEFAULT_CONFIG_ADDR1 0 #endif // <o> TWIS_DEFAULT_CONFIG_SCL_PULL - SCL pin pull configuration // <0=> Disabled // <1=> Pull down // <3=> Pull up #ifndef TWIS_DEFAULT_CONFIG_SCL_PULL #define TWIS_DEFAULT_CONFIG_SCL_PULL 0 #endif // <o> TWIS_DEFAULT_CONFIG_SDA_PULL - SDA pin pull configuration // <0=> Disabled // <1=> Pull down // <3=> Pull up #ifndef TWIS_DEFAULT_CONFIG_SDA_PULL #define TWIS_DEFAULT_CONFIG_SDA_PULL 0 #endif // <o> TWIS_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef TWIS_DEFAULT_CONFIG_IRQ_PRIORITY #define TWIS_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> TWIS0_ENABLED - Enable TWIS0 instance #ifndef TWIS0_ENABLED #define TWIS0_ENABLED 0 #endif // <q> TWIS1_ENABLED - Enable TWIS1 instance #ifndef TWIS1_ENABLED #define TWIS1_ENABLED 0 #endif // <q> TWIS_ASSUME_INIT_AFTER_RESET_ONLY - Assume that any instance would be initialized only once // <i> Optimization flag. Registers used by TWIS are shared by other peripherals. Normally, during initialization driver tries to clear all registers to known state before doing the initialization itself. This gives initialization safe procedure, no matter when it would be called. If you activate TWIS only once and do never uninitialize it - set this flag to 1 what gives more optimal code. #ifndef TWIS_ASSUME_INIT_AFTER_RESET_ONLY #define TWIS_ASSUME_INIT_AFTER_RESET_ONLY 0 #endif // <q> TWIS_NO_SYNC_MODE - Remove support for synchronous mode // <i> Synchronous mode would be used in specific situations. And it uses some additional code and data memory to safely process state machine by polling it in status functions. If this functionality is not required it may be disabled to free some resources. #ifndef TWIS_NO_SYNC_MODE #define TWIS_NO_SYNC_MODE 0 #endif // <e> TWIS_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef TWIS_CONFIG_LOG_ENABLED #define TWIS_CONFIG_LOG_ENABLED 0 #endif #if TWIS_CONFIG_LOG_ENABLED // <o> TWIS_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef TWIS_CONFIG_LOG_LEVEL #define TWIS_CONFIG_LOG_LEVEL 3 #endif // <o> TWIS_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWIS_CONFIG_INFO_COLOR #define TWIS_CONFIG_INFO_COLOR 0 #endif // <o> TWIS_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWIS_CONFIG_DEBUG_COLOR #define TWIS_CONFIG_DEBUG_COLOR 0 #endif #endif //TWIS_CONFIG_LOG_ENABLED // </e> #endif //TWIS_ENABLED // </e> // <e> TWI_ENABLED - nrf_drv_twi - TWI/TWIM peripheral driver //========================================================== #ifndef TWI_ENABLED #define TWI_ENABLED 0 #endif #if TWI_ENABLED // <o> TWI_DEFAULT_CONFIG_FREQUENCY - Frequency // <26738688=> 100k // <67108864=> 250k // <104857600=> 400k #ifndef TWI_DEFAULT_CONFIG_FREQUENCY #define TWI_DEFAULT_CONFIG_FREQUENCY 26738688 #endif // <q> TWI_DEFAULT_CONFIG_CLR_BUS_INIT - Enables bus clearing procedure during init #ifndef TWI_DEFAULT_CONFIG_CLR_BUS_INIT #define TWI_DEFAULT_CONFIG_CLR_BUS_INIT 0 #endif // <q> TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT - Enables bus holding after uninit #ifndef TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT #define TWI_DEFAULT_CONFIG_HOLD_BUS_UNINIT 0 #endif // <o> TWI_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef TWI_DEFAULT_CONFIG_IRQ_PRIORITY #define TWI_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <e> TWI0_ENABLED - Enable TWI0 instance //========================================================== #ifndef TWI0_ENABLED #define TWI0_ENABLED 0 #endif #if TWI0_ENABLED // <q> TWI0_USE_EASY_DMA - Use EasyDMA (if present) #ifndef TWI0_USE_EASY_DMA #define TWI0_USE_EASY_DMA 0 #endif #endif //TWI0_ENABLED // </e> // <e> TWI1_ENABLED - Enable TWI1 instance //========================================================== #ifndef TWI1_ENABLED #define TWI1_ENABLED 0 #endif #if TWI1_ENABLED // <q> TWI1_USE_EASY_DMA - Use EasyDMA (if present) #ifndef TWI1_USE_EASY_DMA #define TWI1_USE_EASY_DMA 0 #endif #endif //TWI1_ENABLED // </e> // <e> TWI_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef TWI_CONFIG_LOG_ENABLED #define TWI_CONFIG_LOG_ENABLED 0 #endif #if TWI_CONFIG_LOG_ENABLED // <o> TWI_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef TWI_CONFIG_LOG_LEVEL #define TWI_CONFIG_LOG_LEVEL 3 #endif // <o> TWI_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWI_CONFIG_INFO_COLOR #define TWI_CONFIG_INFO_COLOR 0 #endif // <o> TWI_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef TWI_CONFIG_DEBUG_COLOR #define TWI_CONFIG_DEBUG_COLOR 0 #endif #endif //TWI_CONFIG_LOG_ENABLED // </e> // <q> TWIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED - Enables nRF52 anomaly 109 workaround for TWIM. // <i> The workaround uses interrupts to wake up the CPU by catching // <i> the start event of zero-frequency transmission, clear the // <i> peripheral, set desired frequency, start the peripheral, and // <i> the proper transmission. See more in the Errata document or // <i> Anomaly 109 Addendum located at https://infocenter.nordicsemi.com/ #ifndef TWIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED #define TWIM_NRF52_ANOMALY_109_WORKAROUND_ENABLED 0 #endif #endif //TWI_ENABLED // </e> // <e> UART_ENABLED - nrf_drv_uart - UART/UARTE peripheral driver //========================================================== #ifndef UART_ENABLED #define UART_ENABLED 1 #endif #if UART_ENABLED // <o> UART_DEFAULT_CONFIG_HWFC - Hardware Flow Control // <0=> Disabled // <1=> Enabled #ifndef UART_DEFAULT_CONFIG_HWFC #define UART_DEFAULT_CONFIG_HWFC 0 #endif // <o> UART_DEFAULT_CONFIG_PARITY - Parity // <0=> Excluded // <14=> Included #ifndef UART_DEFAULT_CONFIG_PARITY #define UART_DEFAULT_CONFIG_PARITY 0 #endif // <o> UART_DEFAULT_CONFIG_BAUDRATE - Default Baudrate // <323584=> 1200 baud // <643072=> 2400 baud // <1290240=> 4800 baud // <2576384=> 9600 baud // <3862528=> 14400 baud // <5152768=> 19200 baud // <7716864=> 28800 baud // <10289152=> 38400 baud // <15400960=> 57600 baud // <20615168=> 76800 baud // <30801920=> 115200 baud // <61865984=> 230400 baud // <67108864=> 250000 baud // <121634816=> 460800 baud // <251658240=> 921600 baud // <268435456=> 57600 baud #ifndef UART_DEFAULT_CONFIG_BAUDRATE #define UART_DEFAULT_CONFIG_BAUDRATE 30801920 #endif // <o> UART_DEFAULT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef UART_DEFAULT_CONFIG_IRQ_PRIORITY #define UART_DEFAULT_CONFIG_IRQ_PRIORITY 7 #endif // <q> UART_EASY_DMA_SUPPORT - Driver supporting EasyDMA #ifndef UART_EASY_DMA_SUPPORT #define UART_EASY_DMA_SUPPORT 1 #endif // <q> UART_LEGACY_SUPPORT - Driver supporting Legacy mode #ifndef UART_LEGACY_SUPPORT #define UART_LEGACY_SUPPORT 1 #endif // <e> UART0_ENABLED - Enable UART0 instance //========================================================== #ifndef UART0_ENABLED #define UART0_ENABLED 1 #endif #if UART0_ENABLED // <q> UART0_CONFIG_USE_EASY_DMA - Default setting for using EasyDMA #ifndef UART0_CONFIG_USE_EASY_DMA #define UART0_CONFIG_USE_EASY_DMA 1 #endif #endif //UART0_ENABLED // </e> // <e> UART_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef UART_CONFIG_LOG_ENABLED #define UART_CONFIG_LOG_ENABLED 0 #endif #if UART_CONFIG_LOG_ENABLED // <o> UART_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef UART_CONFIG_LOG_LEVEL #define UART_CONFIG_LOG_LEVEL 3 #endif // <o> UART_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef UART_CONFIG_INFO_COLOR #define UART_CONFIG_INFO_COLOR 0 #endif // <o> UART_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef UART_CONFIG_DEBUG_COLOR #define UART_CONFIG_DEBUG_COLOR 0 #endif #endif //UART_CONFIG_LOG_ENABLED // </e> #endif //UART_ENABLED // </e> // <e> USBD_ENABLED - nrf_drv_usbd - USB driver //========================================================== #ifndef USBD_ENABLED #define USBD_ENABLED 0 #endif #if USBD_ENABLED // <o> USBD_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef USBD_CONFIG_IRQ_PRIORITY #define USBD_CONFIG_IRQ_PRIORITY 7 #endif // <o> NRF_DRV_USBD_DMASCHEDULER_MODE - USBD SMA scheduler working scheme // <0=> Prioritized access // <1=> Round Robin #ifndef NRF_DRV_USBD_DMASCHEDULER_MODE #define NRF_DRV_USBD_DMASCHEDULER_MODE 0 #endif // <q> NRF_USBD_DRV_LOG_ENABLED - Enable logging #ifndef NRF_USBD_DRV_LOG_ENABLED #define NRF_USBD_DRV_LOG_ENABLED 0 #endif #endif //USBD_ENABLED // </e> // <e> WDT_ENABLED - nrf_drv_wdt - WDT peripheral driver //========================================================== #ifndef WDT_ENABLED #define WDT_ENABLED 0 #endif #if WDT_ENABLED // <o> WDT_CONFIG_BEHAVIOUR - WDT behavior in CPU SLEEP or HALT mode // <1=> Run in SLEEP, Pause in HALT // <8=> Pause in SLEEP, Run in HALT // <9=> Run in SLEEP and HALT // <0=> Pause in SLEEP and HALT #ifndef WDT_CONFIG_BEHAVIOUR #define WDT_CONFIG_BEHAVIOUR 1 #endif // <o> WDT_CONFIG_RELOAD_VALUE - Reload value <15-4294967295> #ifndef WDT_CONFIG_RELOAD_VALUE #define WDT_CONFIG_RELOAD_VALUE 2000 #endif // <o> WDT_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef WDT_CONFIG_IRQ_PRIORITY #define WDT_CONFIG_IRQ_PRIORITY 7 #endif // <e> WDT_CONFIG_LOG_ENABLED - Enables logging in the module. //========================================================== #ifndef WDT_CONFIG_LOG_ENABLED #define WDT_CONFIG_LOG_ENABLED 0 #endif #if WDT_CONFIG_LOG_ENABLED // <o> WDT_CONFIG_LOG_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef WDT_CONFIG_LOG_LEVEL #define WDT_CONFIG_LOG_LEVEL 3 #endif // <o> WDT_CONFIG_INFO_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef WDT_CONFIG_INFO_COLOR #define WDT_CONFIG_INFO_COLOR 0 #endif // <o> WDT_CONFIG_DEBUG_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef WDT_CONFIG_DEBUG_COLOR #define WDT_CONFIG_DEBUG_COLOR 0 #endif #endif //WDT_CONFIG_LOG_ENABLED // </e> #endif //WDT_ENABLED // </e> // </h> //========================================================== // <h> nRF_Libraries //========================================================== // <q> APP_GPIOTE_ENABLED - app_gpiote - GPIOTE events dispatcher #ifndef APP_GPIOTE_ENABLED #define APP_GPIOTE_ENABLED 0 #endif // <q> APP_PWM_ENABLED - app_pwm - PWM functionality #ifndef APP_PWM_ENABLED #define APP_PWM_ENABLED 0 #endif // <e> APP_SCHEDULER_ENABLED - app_scheduler - Events scheduler //========================================================== #ifndef APP_SCHEDULER_ENABLED #define APP_SCHEDULER_ENABLED 1 #endif #if APP_SCHEDULER_ENABLED // <q> APP_SCHEDULER_WITH_PAUSE - Enabling pause feature #ifndef APP_SCHEDULER_WITH_PAUSE #define APP_SCHEDULER_WITH_PAUSE 0 #endif // <q> APP_SCHEDULER_WITH_PROFILER - Enabling scheduler profiling #ifndef APP_SCHEDULER_WITH_PROFILER #define APP_SCHEDULER_WITH_PROFILER 0 #endif #endif //APP_SCHEDULER_ENABLED // </e> // <e> APP_TIMER_ENABLED - app_timer - Application timer functionality //========================================================== #ifndef APP_TIMER_ENABLED #define APP_TIMER_ENABLED 1 #endif #if APP_TIMER_ENABLED // <o> APP_TIMER_CONFIG_RTC_FREQUENCY - Configure RTC prescaler. // <0=> 32768 Hz // <1=> 16384 Hz // <3=> 8192 Hz // <7=> 4096 Hz // <15=> 2048 Hz // <31=> 1024 Hz #ifndef APP_TIMER_CONFIG_RTC_FREQUENCY #define APP_TIMER_CONFIG_RTC_FREQUENCY 0 #endif // <o> APP_TIMER_CONFIG_IRQ_PRIORITY - Interrupt priority // <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice // <0=> 0 (highest) // <1=> 1 // <2=> 2 // <3=> 3 // <4=> 4 // <5=> 5 // <6=> 6 // <7=> 7 #ifndef APP_TIMER_CONFIG_IRQ_PRIORITY #define APP_TIMER_CONFIG_IRQ_PRIORITY 7 #endif // <o> APP_TIMER_CONFIG_OP_QUEUE_SIZE - Capacity of timer requests queue. // <i> Size of the queue depends on how many timers are used // <i> in the system, how often timers are started and overall // <i> system latency. If queue size is too small app_timer calls // <i> will fail. #ifndef APP_TIMER_CONFIG_OP_QUEUE_SIZE #define APP_TIMER_CONFIG_OP_QUEUE_SIZE 10 #endif // <q> APP_TIMER_CONFIG_USE_SCHEDULER - Enable scheduling app_timer events to app_scheduler #ifndef APP_TIMER_CONFIG_USE_SCHEDULER #define APP_TIMER_CONFIG_USE_SCHEDULER 0 #endif // <q> APP_TIMER_WITH_PROFILER - Enable app_timer profiling #ifndef APP_TIMER_WITH_PROFILER #define APP_TIMER_WITH_PROFILER 0 #endif // <q> APP_TIMER_KEEPS_RTC_ACTIVE - Enable RTC always on // <i> If option is enabled RTC is kept running even if there is no active timers. // <i> This option can be used when app_timer is used for timestamping. #ifndef APP_TIMER_KEEPS_RTC_ACTIVE #define APP_TIMER_KEEPS_RTC_ACTIVE 0 #endif // <o> APP_TIMER_CONFIG_SWI_NUMBER - Configure SWI instance used. // <0=> 0 // <1=> 1 #ifndef APP_TIMER_CONFIG_SWI_NUMBER #define APP_TIMER_CONFIG_SWI_NUMBER 0 #endif #endif //APP_TIMER_ENABLED // </e> // <q> APP_TWI_ENABLED - app_twi - TWI transaction manager #ifndef APP_TWI_ENABLED #define APP_TWI_ENABLED 0 #endif // <e> APP_UART_ENABLED - app_uart - UART driver //========================================================== #ifndef APP_UART_ENABLED #define APP_UART_ENABLED 0 #endif #if APP_UART_ENABLED // <o> APP_UART_DRIVER_INSTANCE - UART instance used // <0=> 0 #ifndef APP_UART_DRIVER_INSTANCE #define APP_UART_DRIVER_INSTANCE 0 #endif #endif //APP_UART_ENABLED // </e> // <q> APP_USBD_CLASS_AUDIO_ENABLED - app_usbd_audio - USB AUDIO class #ifndef APP_USBD_CLASS_AUDIO_ENABLED #define APP_USBD_CLASS_AUDIO_ENABLED 0 #endif // <q> APP_USBD_CLASS_HID_ENABLED - app_usbd_hid - USB HID class #ifndef APP_USBD_CLASS_HID_ENABLED #define APP_USBD_CLASS_HID_ENABLED 0 #endif // <q> APP_USBD_HID_GENERIC_ENABLED - app_usbd_hid_generic - USB HID generic #ifndef APP_USBD_HID_GENERIC_ENABLED #define APP_USBD_HID_GENERIC_ENABLED 0 #endif // <q> APP_USBD_HID_KBD_ENABLED - app_usbd_hid_kbd - USB HID keyboard #ifndef APP_USBD_HID_KBD_ENABLED #define APP_USBD_HID_KBD_ENABLED 0 #endif // <q> APP_USBD_HID_MOUSE_ENABLED - app_usbd_hid_mouse - USB HID mouse #ifndef APP_USBD_HID_MOUSE_ENABLED #define APP_USBD_HID_MOUSE_ENABLED 0 #endif // <q> BUTTON_ENABLED - app_button - buttons handling module #ifndef BUTTON_ENABLED #define BUTTON_ENABLED 1 #endif // <q> CRC16_ENABLED - crc16 - CRC16 calculation routines #ifndef CRC16_ENABLED #define CRC16_ENABLED 0 #endif // <q> CRC32_ENABLED - crc32 - CRC32 calculation routines #ifndef CRC32_ENABLED #define CRC32_ENABLED 0 #endif // <q> ECC_ENABLED - ecc - Elliptic Curve Cryptography Library #ifndef ECC_ENABLED #define ECC_ENABLED 0 #endif // <e> FDS_ENABLED - fds - Flash data storage module //========================================================== #ifndef FDS_ENABLED #define FDS_ENABLED 0 #endif #if FDS_ENABLED // <o> FDS_OP_QUEUE_SIZE - Size of the internal queue. #ifndef FDS_OP_QUEUE_SIZE #define FDS_OP_QUEUE_SIZE 4 #endif // <o> FDS_CHUNK_QUEUE_SIZE - Determines how many @ref fds_record_chunk_t structures can be buffered at any time. #ifndef FDS_CHUNK_QUEUE_SIZE #define FDS_CHUNK_QUEUE_SIZE 8 #endif // <o> FDS_MAX_USERS - Maximum number of callbacks that can be registered. #ifndef FDS_MAX_USERS #define FDS_MAX_USERS 8 #endif // <o> FDS_VIRTUAL_PAGES - Number of virtual flash pages to use. // <i> One of the virtual pages is reserved by the system for garbage collection. // <i> Therefore, the minimum is two virtual pages: one page to store data and // <i> one page to be used by the system for garbage collection. The total amount // <i> of flash memory that is used by FDS amounts to @ref FDS_VIRTUAL_PAGES // <i> @ref FDS_VIRTUAL_PAGE_SIZE * 4 bytes. #ifndef FDS_VIRTUAL_PAGES #define FDS_VIRTUAL_PAGES 3 #endif // <o> FDS_VIRTUAL_PAGE_SIZE - The size of a virtual page of flash memory, expressed in number of 4-byte words. // <i> By default, a virtual page is the same size as a physical page. // <i> The size of a virtual page must be a multiple of the size of a physical page. // <1024=> 1024 // <2048=> 2048 #ifndef FDS_VIRTUAL_PAGE_SIZE #define FDS_VIRTUAL_PAGE_SIZE 1024 #endif #endif //FDS_ENABLED // </e> // <e> FSTORAGE_ENABLED - fstorage - Flash storage module //========================================================== #ifndef FSTORAGE_ENABLED #define FSTORAGE_ENABLED 0 #endif #if FSTORAGE_ENABLED // <o> FS_QUEUE_SIZE - Configures the size of the internal queue. // <i> Increase this if there are many users, or if it is likely that many // <i> operation will be queued at once without waiting for the previous operations // <i> to complete. In general, increase the queue size if you frequently receive // <i> @ref FS_ERR_QUEUE_FULL errors when calling @ref fs_store or @ref fs_erase. #ifndef FS_QUEUE_SIZE #define FS_QUEUE_SIZE 4 #endif // <o> FS_OP_MAX_RETRIES - Number attempts to execute an operation if the SoftDevice fails. // <i> Increase this value if events return the @ref FS_ERR_OPERATION_TIMEOUT // <i> error often. The SoftDevice may fail to schedule flash access due to high BLE activity. #ifndef FS_OP_MAX_RETRIES #define FS_OP_MAX_RETRIES 3 #endif // <o> FS_MAX_WRITE_SIZE_WORDS - Maximum number of words to be written to flash in a single operation. // <i> Tweaking this value can increase the chances of the SoftDevice being // <i> able to fit flash operations in between radio activity. This value is bound by the // <i> maximum number of words which the SoftDevice can write to flash in a single call to // <i> @ref sd_flash_write, which is 256 words for nRF51 ICs and 1024 words for nRF52 ICs. #ifndef FS_MAX_WRITE_SIZE_WORDS #define FS_MAX_WRITE_SIZE_WORDS 1024 #endif #endif //FSTORAGE_ENABLED // </e> // <q> HARDFAULT_HANDLER_ENABLED - hardfault_default - HardFault default handler for debugging and release #ifndef HARDFAULT_HANDLER_ENABLED #define HARDFAULT_HANDLER_ENABLED 0 #endif // <e> HCI_MEM_POOL_ENABLED - hci_mem_pool - memory pool implementation used by HCI //========================================================== #ifndef HCI_MEM_POOL_ENABLED #define HCI_MEM_POOL_ENABLED 0 #endif #if HCI_MEM_POOL_ENABLED // <o> HCI_TX_BUF_SIZE - TX buffer size in bytes. #ifndef HCI_TX_BUF_SIZE #define HCI_TX_BUF_SIZE 600 #endif // <o> HCI_RX_BUF_SIZE - RX buffer size in bytes. #ifndef HCI_RX_BUF_SIZE #define HCI_RX_BUF_SIZE 600 #endif // <o> HCI_RX_BUF_QUEUE_SIZE - RX buffer queue size. #ifndef HCI_RX_BUF_QUEUE_SIZE #define HCI_RX_BUF_QUEUE_SIZE 4 #endif #endif //HCI_MEM_POOL_ENABLED // </e> // <e> HCI_SLIP_ENABLED - hci_slip - SLIP protocol implementation used by HCI //========================================================== #ifndef HCI_SLIP_ENABLED #define HCI_SLIP_ENABLED 0 #endif #if HCI_SLIP_ENABLED // <o> HCI_UART_BAUDRATE - Default Baudrate // <323584=> 1200 baud // <643072=> 2400 baud // <1290240=> 4800 baud // <2576384=> 9600 baud // <3862528=> 14400 baud // <5152768=> 19200 baud // <7716864=> 28800 baud // <10289152=> 38400 baud // <15400960=> 57600 baud // <20615168=> 76800 baud // <30801920=> 115200 baud // <61865984=> 230400 baud // <67108864=> 250000 baud // <121634816=> 460800 baud // <251658240=> 921600 baud // <268435456=> 57600 baud #ifndef HCI_UART_BAUDRATE #define HCI_UART_BAUDRATE 30801920 #endif // <o> HCI_UART_FLOW_CONTROL - Hardware Flow Control // <0=> Disabled // <1=> Enabled #ifndef HCI_UART_FLOW_CONTROL #define HCI_UART_FLOW_CONTROL 0 #endif // <o> HCI_UART_RX_PIN - UART RX pin #ifndef HCI_UART_RX_PIN #define HCI_UART_RX_PIN 8 #endif // <o> HCI_UART_TX_PIN - UART TX pin #ifndef HCI_UART_TX_PIN #define HCI_UART_TX_PIN 6 #endif // <o> HCI_UART_RTS_PIN - UART RTS pin #ifndef HCI_UART_RTS_PIN #define HCI_UART_RTS_PIN 5 #endif // <o> HCI_UART_CTS_PIN - UART CTS pin #ifndef HCI_UART_CTS_PIN #define HCI_UART_CTS_PIN 7 #endif #endif //HCI_SLIP_ENABLED // </e> // <e> HCI_TRANSPORT_ENABLED - hci_transport - HCI transport //========================================================== #ifndef HCI_TRANSPORT_ENABLED #define HCI_TRANSPORT_ENABLED 0 #endif #if HCI_TRANSPORT_ENABLED // <o> HCI_MAX_PACKET_SIZE_IN_BITS - Maximum size of a single application packet in bits. #ifndef HCI_MAX_PACKET_SIZE_IN_BITS #define HCI_MAX_PACKET_SIZE_IN_BITS 8000 #endif #endif //HCI_TRANSPORT_ENABLED // </e> // <q> LED_SOFTBLINK_ENABLED - led_softblink - led_softblink module #ifndef LED_SOFTBLINK_ENABLED #define LED_SOFTBLINK_ENABLED 0 #endif // <q> LOW_POWER_PWM_ENABLED - low_power_pwm - low_power_pwm module #ifndef LOW_POWER_PWM_ENABLED #define LOW_POWER_PWM_ENABLED 0 #endif // <e> MEM_MANAGER_ENABLED - mem_manager - Dynamic memory allocator //========================================================== #ifndef MEM_MANAGER_ENABLED #define MEM_MANAGER_ENABLED 0 #endif #if MEM_MANAGER_ENABLED // <o> MEMORY_MANAGER_SMALL_BLOCK_COUNT - Size of each memory blocks identified as 'small' block. <0-255> #ifndef MEMORY_MANAGER_SMALL_BLOCK_COUNT #define MEMORY_MANAGER_SMALL_BLOCK_COUNT 1 #endif // <o> MEMORY_MANAGER_SMALL_BLOCK_SIZE - Size of each memory blocks identified as 'small' block. // <i> Size of each memory blocks identified as 'small' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_SMALL_BLOCK_SIZE #define MEMORY_MANAGER_SMALL_BLOCK_SIZE 32 #endif // <o> MEMORY_MANAGER_MEDIUM_BLOCK_COUNT - Size of each memory blocks identified as 'medium' block. <0-255> #ifndef MEMORY_MANAGER_MEDIUM_BLOCK_COUNT #define MEMORY_MANAGER_MEDIUM_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_MEDIUM_BLOCK_SIZE - Size of each memory blocks identified as 'medium' block. // <i> Size of each memory blocks identified as 'medium' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_MEDIUM_BLOCK_SIZE #define MEMORY_MANAGER_MEDIUM_BLOCK_SIZE 256 #endif // <o> MEMORY_MANAGER_LARGE_BLOCK_COUNT - Size of each memory blocks identified as 'large' block. <0-255> #ifndef MEMORY_MANAGER_LARGE_BLOCK_COUNT #define MEMORY_MANAGER_LARGE_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_LARGE_BLOCK_SIZE - Size of each memory blocks identified as 'large' block. // <i> Size of each memory blocks identified as 'large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_LARGE_BLOCK_SIZE #define MEMORY_MANAGER_LARGE_BLOCK_SIZE 256 #endif // <o> MEMORY_MANAGER_XLARGE_BLOCK_COUNT - Size of each memory blocks identified as 'extra large' block. <0-255> #ifndef MEMORY_MANAGER_XLARGE_BLOCK_COUNT #define MEMORY_MANAGER_XLARGE_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XLARGE_BLOCK_SIZE - Size of each memory blocks identified as 'extra large' block. // <i> Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XLARGE_BLOCK_SIZE #define MEMORY_MANAGER_XLARGE_BLOCK_SIZE 1320 #endif // <o> MEMORY_MANAGER_XXLARGE_BLOCK_COUNT - Size of each memory blocks identified as 'extra extra large' block. <0-255> #ifndef MEMORY_MANAGER_XXLARGE_BLOCK_COUNT #define MEMORY_MANAGER_XXLARGE_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XXLARGE_BLOCK_SIZE - Size of each memory blocks identified as 'extra extra large' block. // <i> Size of each memory blocks identified as 'extra extra large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XXLARGE_BLOCK_SIZE #define MEMORY_MANAGER_XXLARGE_BLOCK_SIZE 3444 #endif // <o> MEMORY_MANAGER_XSMALL_BLOCK_COUNT - Size of each memory blocks identified as 'extra small' block. <0-255> #ifndef MEMORY_MANAGER_XSMALL_BLOCK_COUNT #define MEMORY_MANAGER_XSMALL_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XSMALL_BLOCK_SIZE - Size of each memory blocks identified as 'extra small' block. // <i> Size of each memory blocks identified as 'extra large' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XSMALL_BLOCK_SIZE #define MEMORY_MANAGER_XSMALL_BLOCK_SIZE 64 #endif // <o> MEMORY_MANAGER_XXSMALL_BLOCK_COUNT - Size of each memory blocks identified as 'extra extra small' block. <0-255> #ifndef MEMORY_MANAGER_XXSMALL_BLOCK_COUNT #define MEMORY_MANAGER_XXSMALL_BLOCK_COUNT 0 #endif // <o> MEMORY_MANAGER_XXSMALL_BLOCK_SIZE - Size of each memory blocks identified as 'extra extra small' block. // <i> Size of each memory blocks identified as 'extra extra small' block. Memory block are recommended to be word-sized. #ifndef MEMORY_MANAGER_XXSMALL_BLOCK_SIZE #define MEMORY_MANAGER_XXSMALL_BLOCK_SIZE 32 #endif // <q> MEM_MANAGER_ENABLE_LOGS - Enable debug trace in the module. #ifndef MEM_MANAGER_ENABLE_LOGS #define MEM_MANAGER_ENABLE_LOGS 0 #endif // <q> MEM_MANAGER_DISABLE_API_PARAM_CHECK - Disable API parameter checks in the module. #ifndef MEM_MANAGER_DISABLE_API_PARAM_CHECK #define MEM_MANAGER_DISABLE_API_PARAM_CHECK 0 #endif #endif //MEM_MANAGER_ENABLED // </e> // <e> NRF_CSENSE_ENABLED - nrf_csense - Capacitive sensor module //========================================================== #ifndef NRF_CSENSE_ENABLED #define NRF_CSENSE_ENABLED 0 #endif #if NRF_CSENSE_ENABLED // <o> NRF_CSENSE_PAD_HYSTERESIS - Minimum value of change required to determine that a pad was touched. #ifndef NRF_CSENSE_PAD_HYSTERESIS #define NRF_CSENSE_PAD_HYSTERESIS 15 #endif // <o> NRF_CSENSE_PAD_DEVIATION - Minimum value measured on a pad required to take it into account while calculating the step. #ifndef NRF_CSENSE_PAD_DEVIATION #define NRF_CSENSE_PAD_DEVIATION 70 #endif // <o> NRF_CSENSE_MIN_PAD_VALUE - Minimum normalized value on a pad required to take its value into account. #ifndef NRF_CSENSE_MIN_PAD_VALUE #define NRF_CSENSE_MIN_PAD_VALUE 20 #endif // <o> NRF_CSENSE_MAX_PADS_NUMBER - Maximum number of pads used for one instance. #ifndef NRF_CSENSE_MAX_PADS_NUMBER #define NRF_CSENSE_MAX_PADS_NUMBER 20 #endif // <o> NRF_CSENSE_MAX_VALUE - Maximum normalized value obtained from measurement. #ifndef NRF_CSENSE_MAX_VALUE #define NRF_CSENSE_MAX_VALUE 1000 #endif // <o> NRF_CSENSE_OUTPUT_PIN - Output pin used by the low-level module. // <i> This is used when capacitive sensor does not use COMP. #ifndef NRF_CSENSE_OUTPUT_PIN #define NRF_CSENSE_OUTPUT_PIN 26 #endif #endif //NRF_CSENSE_ENABLED // </e> // <e> NRF_DRV_CSENSE_ENABLED - nrf_drv_csense - Capacitive sensor low-level module //========================================================== #ifndef NRF_DRV_CSENSE_ENABLED #define NRF_DRV_CSENSE_ENABLED 0 #endif #if NRF_DRV_CSENSE_ENABLED // <e> USE_COMP - Use the comparator to implement the capacitive sensor driver. // <i> Due to Anomaly 84, COMP I_SOURCE is not functional. It has too high a varation. //========================================================== #ifndef USE_COMP #define USE_COMP 0 #endif #if USE_COMP // <o> TIMER0_FOR_CSENSE - First TIMER instance used by the driver (not used on nRF51). #ifndef TIMER0_FOR_CSENSE #define TIMER0_FOR_CSENSE 1 #endif // <o> TIMER1_FOR_CSENSE - Second TIMER instance used by the driver (not used on nRF51). #ifndef TIMER1_FOR_CSENSE #define TIMER1_FOR_CSENSE 2 #endif // <o> MEASUREMENT_PERIOD - Single measurement period. // <i> Time of a single measurement can be calculated as // <i> T = (1/2)*MEASUREMENT_PERIOD*(1/f_OSC) where f_OSC = I_SOURCE / (2C*(VUP-VDOWN) ). // <i> I_SOURCE, VUP, and VDOWN are values used to initialize COMP and C is the capacitance of the used pad. #ifndef MEASUREMENT_PERIOD #define MEASUREMENT_PERIOD 20 #endif #endif //USE_COMP // </e> #endif //NRF_DRV_CSENSE_ENABLED // </e> // <q> NRF_QUEUE_ENABLED - nrf_queue - Queue module #ifndef NRF_QUEUE_ENABLED #define NRF_QUEUE_ENABLED 0 #endif // <q> NRF_STRERROR_ENABLED - nrf_strerror - Library for converting error code to string. #ifndef NRF_STRERROR_ENABLED #define NRF_STRERROR_ENABLED 1 #endif // <q> SLIP_ENABLED - slip - SLIP encoding and decoding #ifndef SLIP_ENABLED #define SLIP_ENABLED 0 #endif // <h> app_usbd_cdc_acm - USB CDC ACM class //========================================================== // <q> APP_USBD_CLASS_CDC_ACM_ENABLED - Enabling USBD CDC ACM Class library #ifndef APP_USBD_CLASS_CDC_ACM_ENABLED #define APP_USBD_CLASS_CDC_ACM_ENABLED 0 #endif // <q> APP_USBD_CDC_ACM_LOG_ENABLED - Enables logging in the module. #ifndef APP_USBD_CDC_ACM_LOG_ENABLED #define APP_USBD_CDC_ACM_LOG_ENABLED 0 #endif // </h> //========================================================== // <h> app_usbd_msc - USB MSC class //========================================================== // <q> APP_USBD_CLASS_MSC_ENABLED - Enabling USBD MSC Class library #ifndef APP_USBD_CLASS_MSC_ENABLED #define APP_USBD_CLASS_MSC_ENABLED 0 #endif // <q> APP_USBD_MSC_CLASS_LOG_ENABLED - Enables logging in the module. #ifndef APP_USBD_MSC_CLASS_LOG_ENABLED #define APP_USBD_MSC_CLASS_LOG_ENABLED 0 #endif // </h> //========================================================== // </h> //========================================================== // <h> nRF_Log //========================================================== // <e> NRF_LOG_ENABLED - nrf_log - Logging //========================================================== #ifndef NRF_LOG_ENABLED #define NRF_LOG_ENABLED 1 #endif #if NRF_LOG_ENABLED // <e> NRF_LOG_USES_COLORS - If enabled then ANSI escape code for colors is prefixed to every string //========================================================== #ifndef NRF_LOG_USES_COLORS #define NRF_LOG_USES_COLORS 0 #endif #if NRF_LOG_USES_COLORS // <o> NRF_LOG_COLOR_DEFAULT - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef NRF_LOG_COLOR_DEFAULT #define NRF_LOG_COLOR_DEFAULT 0 #endif // <o> NRF_LOG_ERROR_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef NRF_LOG_ERROR_COLOR #define NRF_LOG_ERROR_COLOR 0 #endif // <o> NRF_LOG_WARNING_COLOR - ANSI escape code prefix. // <0=> Default // <1=> Black // <2=> Red // <3=> Green // <4=> Yellow // <5=> Blue // <6=> Magenta // <7=> Cyan // <8=> White #ifndef NRF_LOG_WARNING_COLOR #define NRF_LOG_WARNING_COLOR 0 #endif #endif //NRF_LOG_USES_COLORS // </e> // <o> NRF_LOG_DEFAULT_LEVEL - Default Severity level // <0=> Off // <1=> Error // <2=> Warning // <3=> Info // <4=> Debug #ifndef NRF_LOG_DEFAULT_LEVEL #define NRF_LOG_DEFAULT_LEVEL 3 #endif // <e> NRF_LOG_DEFERRED - Enable deffered logger. // <i> Log data is buffered and can be processed in idle. //========================================================== #ifndef NRF_LOG_DEFERRED #define NRF_LOG_DEFERRED 1 #endif #if NRF_LOG_DEFERRED // <o> NRF_LOG_DEFERRED_BUFSIZE - Size of the buffer for logs in words. // <i> Must be power of 2 #ifndef NRF_LOG_DEFERRED_BUFSIZE #define NRF_LOG_DEFERRED_BUFSIZE 256 #endif #endif //NRF_LOG_DEFERRED // </e> // <q> NRF_LOG_USES_TIMESTAMP - Enable timestamping // <i> Function for getting the timestamp is provided by the user #ifndef NRF_LOG_USES_TIMESTAMP #define NRF_LOG_USES_TIMESTAMP 0 #endif #endif //NRF_LOG_ENABLED // </e> // <h> nrf_log_backend - Logging sink //========================================================== // <o> NRF_LOG_BACKEND_MAX_STRING_LENGTH - Buffer for storing single output string // <i> Logger backend RAM usage is determined by this value. #ifndef NRF_LOG_BACKEND_MAX_STRING_LENGTH #define NRF_LOG_BACKEND_MAX_STRING_LENGTH 256 #endif // <o> NRF_LOG_TIMESTAMP_DIGITS - Number of digits for timestamp // <i> If higher resolution timestamp source is used it might be needed to increase that #ifndef NRF_LOG_TIMESTAMP_DIGITS #define NRF_LOG_TIMESTAMP_DIGITS 8 #endif // <e> NRF_LOG_BACKEND_SERIAL_USES_UART - If enabled data is printed over UART //========================================================== #ifndef NRF_LOG_BACKEND_SERIAL_USES_UART #define NRF_LOG_BACKEND_SERIAL_USES_UART 1 #endif #if NRF_LOG_BACKEND_SERIAL_USES_UART // <o> NRF_LOG_BACKEND_SERIAL_UART_BAUDRATE - Default Baudrate // <323584=> 1200 baud // <643072=> 2400 baud // <1290240=> 4800 baud // <2576384=> 9600 baud // <3862528=> 14400 baud // <5152768=> 19200 baud // <7716864=> 28800 baud // <10289152=> 38400 baud // <15400960=> 57600 baud // <20615168=> 76800 baud // <30801920=> 115200 baud // <61865984=> 230400 baud // <67108864=> 250000 baud // <121634816=> 460800 baud // <251658240=> 921600 baud // <268435456=> 57600 baud #ifndef NRF_LOG_BACKEND_SERIAL_UART_BAUDRATE #define NRF_LOG_BACKEND_SERIAL_UART_BAUDRATE 30801920 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_TX_PIN - UART TX pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_TX_PIN #define NRF_LOG_BACKEND_SERIAL_UART_TX_PIN 6 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_RX_PIN - UART RX pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_RX_PIN #define NRF_LOG_BACKEND_SERIAL_UART_RX_PIN 8 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_RTS_PIN - UART RTS pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_RTS_PIN #define NRF_LOG_BACKEND_SERIAL_UART_RTS_PIN 5 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_CTS_PIN - UART CTS pin #ifndef NRF_LOG_BACKEND_SERIAL_UART_CTS_PIN #define NRF_LOG_BACKEND_SERIAL_UART_CTS_PIN 7 #endif // <o> NRF_LOG_BACKEND_SERIAL_UART_FLOW_CONTROL - Hardware Flow Control // <0=> Disabled // <1=> Enabled #ifndef NRF_LOG_BACKEND_SERIAL_UART_FLOW_CONTROL #define NRF_LOG_BACKEND_SERIAL_UART_FLOW_CONTROL 0 #endif // <o> NRF_LOG_BACKEND_UART_INSTANCE - UART instance used // <0=> 0 #ifndef NRF_LOG_BACKEND_UART_INSTANCE #define NRF_LOG_BACKEND_UART_INSTANCE 0 #endif #endif //NRF_LOG_BACKEND_SERIAL_USES_UART // </e> // <e> NRF_LOG_BACKEND_SERIAL_USES_RTT - If enabled data is printed using RTT //========================================================== #ifndef NRF_LOG_BACKEND_SERIAL_USES_RTT #define NRF_LOG_BACKEND_SERIAL_USES_RTT 0 #endif #if NRF_LOG_BACKEND_SERIAL_USES_RTT // <o> NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE - RTT output buffer size. // <i> Should be equal or bigger than \ref NRF_LOG_BACKEND_MAX_STRING_LENGTH. // <i> This value is used in Segger RTT configuration to set the buffer size // <i> if it is bigger than default RTT buffer size. #ifndef NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE #define NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE 512 #endif #endif //NRF_LOG_BACKEND_SERIAL_USES_RTT // </e> // </h> //========================================================== // </h> //========================================================== // <h> nRF_Segger_RTT //========================================================== // <h> segger_rtt - SEGGER RTT //========================================================== // <o> SEGGER_RTT_CONFIG_BUFFER_SIZE_UP - Size of upstream buffer. // <i> Note that either @ref NRF_LOG_BACKEND_RTT_OUTPUT_BUFFER_SIZE // <i> or this value is actually used. It depends on which one is bigger. #ifndef SEGGER_RTT_CONFIG_BUFFER_SIZE_UP #define SEGGER_RTT_CONFIG_BUFFER_SIZE_UP 64 #endif // <o> SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS - Size of upstream buffer. #ifndef SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS #define SEGGER_RTT_CONFIG_MAX_NUM_UP_BUFFERS 2 #endif // <o> SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN - Size of upstream buffer. #ifndef SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN #define SEGGER_RTT_CONFIG_BUFFER_SIZE_DOWN 16 #endif // <o> SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS - Size of upstream buffer. #ifndef SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS #define SEGGER_RTT_CONFIG_MAX_NUM_DOWN_BUFFERS 2 #endif // <o> SEGGER_RTT_CONFIG_DEFAULT_MODE - RTT behavior if the buffer is full. // <i> The following modes are supported: // <i> - SKIP - Do not block, output nothing. // <i> - TRIM - Do not block, output as much as fits. // <i> - BLOCK - Wait until there is space in the buffer. // <0=> SKIP // <1=> TRIM // <2=> BLOCK_IF_FIFO_FULL #ifndef SEGGER_RTT_CONFIG_DEFAULT_MODE #define SEGGER_RTT_CONFIG_DEFAULT_MODE 0 #endif // </h> //========================================================== // </h> //========================================================== // <<< end of configuration section >>> #endif //SDK_CONFIG_H
Java
<?php namespace spf\swoole\worker; interface IWebSocketWorker { public function onStart($server, $workerId); public function onShutdown($server, $workerId); public function onTask($server, $taskId, $fromId, $data); public function onFinish($server, $taskId, $data); public function onOpen($server, $request); public function onClose(); public function onMessage($server, $frame); }
Java
// // UDPConnection.hpp for server in /home/galibe_s/rendu/Spider/server/core // // Made by stephane galibert // Login <galibe_s@epitech.net> // // Started on Sun Nov 6 17:00:50 2016 stephane galibert // Last update Thu Nov 10 12:34:21 2016 stephane galibert // #pragma once #include <iostream> #include <string> #include <queue> #include <memory> #include <boost/bind.hpp> #include "AConnection.hpp" class ConnectionManager; class UDPConnection : public AConnection { public: UDPConnection(boost::asio::io_service &io_service, RequestHandler &reqHandler, PluginManager &pluginManager, ConnectionManager &cm, ServerConfig &config, int port); virtual ~UDPConnection(void); virtual void start(void); virtual void write(Packet *packet); virtual void addLog(std::string const& toadd); virtual void connectDB(void); virtual void disconnectDB(void); virtual void broadcast(std::string const& msg); virtual void kill(void); protected: virtual void do_write(boost::system::error_code const& ec, size_t len); virtual void do_read(boost::system::error_code const& ec, size_t len); virtual void do_handshake(boost::system::error_code const& ec); void write(void); void read(void); boost::asio::ip::udp::socket _socket; boost::asio::ip::udp::endpoint _endpoint; boost::asio::streambuf _read; std::queue<Packet *> _toWrites; };
Java
#pagefrog-big-logo { width: 200px; margin-top:20px; } #pagefrog-settings-container { padding:15px; margin-right:20px; } #pagefrog-settings-box, .white-settings-box { background: white; border-color: #ddd; border-width: 1px; border-style: solid; border-radius: 5px; } #pagefrog-logo-button > span { color:#aaa; } .pagefrog-font-selector { width:80%; } .row { margin-left: -15px; margin-right: -15px; display:block; } @media (min-width: 400px) { .col-xs-8 { width: 60.66666667%; } .col-xs-4 { width: 34.33333333%; } .col-xs-10 { width: 83.66666667%; } .col-xs-12 { width: 100%; } .col-xs-1 { width: 8.33333333%; } .col-xs-2 { width: 16.5%; } .col-xs-3 { width: 25%; } .col-xs-6 { width: 50%; } .col-xs-8, .col-xs-4, .col-xs-12, .col-xs-1, .col-xs-3, .col-xs-6 { float:left; } } @media (min-width: 768px) { .col-sm-8 { width: 60.66666667%; } .col-sm-4 { width: 34.33333333%; } .col-sm-10 { width: 83.66666667%; } .col-sm-12 { width: 100%; } .col-sm-1 { width: 8.33333333%; } .col-sm-2 { width: 16.5%; } .col-sm-3 { width: 25%; } .col-sm-6 { width: 50%; } .col-sm-7 { width: 58.33333333%; } .col-sm-9 { width: 75%; } .col-sm-8, .col-sm-4, .col-sm-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-6, .col-sm-7, .col-sm-9 { float:left; } } .col-sm-8, .col-sm-10, .col-sm-4, .col-sm-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-6, .col-sm-7, .col-sm-9 { min-height: 1px; position: relative; padding-left: 15px; padding-right: 15px; } .nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover { cursor: default; background-color: #fff; border: 1px solid #ddd; border-bottom-color: transparent; box-shadow: none; -webkit-box-shadow: none; } .nav-tabs>li>a { margin-right: 2px; line-height: 1.42857143; border: 1px solid transparent; border-radius: 4px 4px 0 0; text-decoration: none; color: #555; } .nav>li>a { position: relative; display: block; padding: 10px 15px; border: 1px solid #ddd; } .nav-tabs>li { float: left; margin-bottom: -1px; } .nav>li { position: relative; display: block; top: 0px; z-index: 99; } .nav { padding-left: 0; margin-bottom: 0; list-style: none; } .tab-content>.tab-pane { display: none; } .tab-content>.active { display: block; } .padding-container { padding-left:15px; padding-right:15px; } .input-group { position: relative; display: table; border-collapse: separate; } .input-group .form-control:first-child { border-bottom-right-radius: 0; border-top-right-radius: 0; } .input-group .form-control { position: relative; z-index: 2; float: left; width:100%; margin-bottom: 0px; } .input-group-button, .input-group .form-control { display: table-cell; } .input-group-button { position: relative; font-size: 0; white-space: nowrap; width: 1%; white-space: nowrap; vertical-align: middle; } .input-group-button > .button { height:35px; border-top-left-radius: 0; border-bottom-left-radius: 0; } textarea.form-control { height:auto; } .form-control { display: block; width: 100%; height: 36px; padding: 7px 12px; font-size: 13px; line-height: 1.5384616; color: #333; background-color: #fff; background-image: none; border: 1px solid #ddd; border-radius: 3px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; } .margin-top-bottom { margin-top: 9px; margin-bottom: 10px; } .margin-top { margin-top: 10px; } .margin-bottom { margin-bottom: 10px; } .big-margin-bottom { margin-bottom: 50px; } .small-margin-top { margin-top:5px; } .no-margin { margin:0; } :after, :before, * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing:border-box; } .row:before, .row:after { display: table; content: " "; clear:both; } .colorpicker-container { float:right; } .smaller-text { font-size: 10px; } .wide-selector { width:100%; } .pagefrog-rules .with-border { border: 1px solid #ddd; border-radius: 10px; border-top-right-radius: 0px; border-top-left-radius: 0px; padding-left:10px; padding-right:10px; } .pagefrog-rules-explanation ul { list-style: disc outside none; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 0px; -webkit-margin-end: 0px; -webkit-padding-start: 40px; } #pagefrog-preview-format { margin-bottom: 0px; line-height: 0.5em; } .pagefrog-preview-phone-frame-wrapper { width:100%; display:inline-block; position: relative; max-width: 300px; text-align: initial; } .pagefrog-preview-phone-frame-wrapper:after { padding-top: 180%; /* aspect ratio of phone: (627px + phone frame top padding + phone frame bottom padding) / (375px + phone frame left padding + phone frame right padding) (627 + 35 + 50) / 375 + 10 + 10) = 180% */ display:block; content: ''; } .pagefrog-preview-phone-frame { position: absolute; top: 0; bottom: 0; right: 0; left: 0; border: 1px solid #e5e5e5; border-radius: 40px; padding-top:50px; padding-bottom: 35px; padding-left: 10px; padding-right: 10px; background: #f1f1f1; } .pagefrog-preview-container { height: 97.7%; position: relative; width: 100%; border: 1px solid #e5e5e5; overflow: hidden; } .pagefrog-preview-container > iframe { height: 100%; width: 100%; background-color: black; transform: scale(1, 1); /* this should be updated on the preview setup in the javascript */ transform-origin: top left; } .wide-selector { width:100%; } .pull-right { float:right; } h3 .button { position: relative; top:-5px; } .button.block { width:100%; text-align: center; } .well { min-height: 20px; padding:19px; background-color: #f5f5f5; border: 1px solid #e3e3e3; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.05); box-shadow: inset 0 1px 1px rgba(0,0,0,.05); } .fullwidth { width: 100%; } .logo-max-width { max-width: 100px; margin:auto; display: block; } .button.button-lg { padding-left:20px; padding-right: 20px; padding-top: 10px; padding-bottom: 10px; display: inline; font-size: 20px; height:auto; } .button.yellow, .button.yellow:focus { background-color: #ffba00; border-color: #ffba00; color: white; box-shadow: 0 1px 0 #edb20f; } .button.yellow:hover { background-color: #E0A500; border-color: #E0A500; color:white; } .button.pink, .button.pink:focus { background-color: #f289b1; border-color: #f289b1; color: white; } .button.pink:hover { background-color: #ea6ca0; border-color: #ea6ca0; color:white; } .button.blackoutline, .button.blackoutline:disabled { background-color: #ffffff!important; border-color: #494949!important; color: #494949!important; } .button.greenoutline, .button.greenoutline:disabled { background-color: #ffffff!important; border-color: #44bb66!important; color: #44bb66!important; } .button.green, .button.green:focus { background-color: #44bb66; border-color: #44bb66; color: white; } .button.green:hover { background-color: #3fad5e; border-color: #3fad5e; color:white; } .button.green:active { background-color: #3a9e56; border-color: #3a9e56; color:white; } .button.blue, .button.blue:focus { background-color: #527dbf; border-color: #527dbf; color: white; } .button.blue:hover { background-color: #416498; border-color: #416498; color: white; } .text-center { text-align: center; } .green-text { color: #44bb66; } .circled.green { color:#3fad5e; border-color:#3fad5e; } .circled { height: 40px; width: 40px; -moz-border-radius: 50%; border-radius: 50%; font-size: 30px; border-width: 2px; border-style: solid; padding-top: 4px; padding-right: 4px; display: inline-block; } .pagefrog-status-toggle:disabled, label.disabled { cursor: not-allowed; } .alert { padding:10px; border-color:#eee; border-width: 1px; border-style: solid; border-left-width: 4px; } .alert.yellow { border-left-color: #ffba00; } .alert.green { border-left-color: #44bb66; } .alert.red { border-left-color: #ff4542; } .required { color:#888; font-size: 10px; } .pagefrog-status-circle { margin-left: 14px; margin-top: 5px; height: 15px; width: 15px; background-color: #a1a1a1; display: inline-block; border-radius: 10px; overflow: hidden; cursor: pointer; } .pagefrog-status-circle.small { height:10px; width:10px; } .pagefrog-status-circle-inner { width: 100%; height:100%; display: block; border-radius: 10px; } .pagefrog-status-circle-inner.empty { width:0; } .pagefrog-status-circle-inner.half { width: 50%; border-radius: 0px; border-color: white; } .pagefrog-status-circle-inner.green { background-color: #44bb66; } .pagefrog-status-circle-inner.yellow { background-color: #ffba00; } .pagefrog-status-circle-inner.grey { background-color: #aaa; } .hover-cursor { cursor: pointer; } .grey-background { background-color: #f1f1f1; } .grey-bottom-border { border-bottom-color: #dddddd; border-bottom-style: solid; border-bottom-width: 2px; } .padding-box { padding:20px; padding-bottom: 0px; } #pagefrog-settings-box table.form-table { display:none; } .alert.error-box p { margin-top:0; margin-bottom:0; } .alert.error-box { position: relative; top:29px; padding-bottom: 5px; padding-top: 5px; } .fb-like { transform: scale(1.4); -ms-transform: scale(1.4); -webkit-transform: scale(1.4); -o-transform: scale(1.4); -moz-transform: scale(1.4); } .fb_iframe_widget { height: 60px; }
Java
<?php /* * Central de conhecimento FEJESP * Contato: ti@fejesp.org.br * Autor: Guilherme de Oliveira Souza (http://sitegui.com.br) * Data: 07/08/2013 */ // Retorna a árvore inicial para um dado caminho $caminho = @$_GET['caminho']; $pastas = preg_split('@/@', $caminho, -1, PREG_SPLIT_NO_EMPTY); $arvore = array('' => NULL); $nivelAtual = &$arvore['']; $pai = 0; for ($i=0; $i<count($pastas); $i++) { // Carrega cada nível da árvore, a partir da raiz $nivelAtual = array(); $subpastas = Query::query(false, NULL, 'SELECT id, nome, visibilidade, criador FROM pastas WHERE pai=? AND id!=0 ORDER BY nome', $pai); $achou = false; foreach ($subpastas as $dados) if (verificarVisibilidade('pasta', $dados['id'], $dados['visibilidade'], $dados['criador'])) { $nivelAtual[$dados['nome']] = NULL; if ($dados['nome'] == $pastas[$i]) { $achou = true; $pai = $dados['id']; } } // Verifica se a pasta está no caminho if (!$achou) retornarErro(); $nivelAtual = &$nivelAtual[$pastas[$i]]; } retornar($arvore);
Java
<?php namespace Test\Deserializer; use Test\Serializer\EntityNode\Vehicle; class VehicleChecker { public function acceptAndReturnVehicle(Vehicle $vehicle) { return $vehicle; } }
Java
function print_last_modif_date(v) { document.write("Last updated " + v.substr(7, 19)); }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sshd.common; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.Pair; /** * A wrapper that exposes a read-only {@link Map} access to the system * properties. Any attempt to modify it will throw {@link UnsupportedOperationException}. * The mapper uses the {@link #SYSPROPS_MAPPED_PREFIX} to filter and access' * only these properties, ignoring all others * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public final class SyspropsMapWrapper implements Map<String, Object> { /** * Prefix of properties used by the mapper to identify SSHD related settings */ public static final String SYSPROPS_MAPPED_PREFIX = "org.apache.sshd.config"; /** * The one and only wrapper instance */ public static final SyspropsMapWrapper INSTANCE = new SyspropsMapWrapper(); /** * A {@link PropertyResolver} with no parent that exposes the system properties */ public static final PropertyResolver SYSPROPS_RESOLVER = new PropertyResolver() { @Override public Map<String, Object> getProperties() { return SyspropsMapWrapper.INSTANCE; } @Override public PropertyResolver getParentPropertyResolver() { return null; } @Override public String toString() { return "SYSPROPS"; } }; private SyspropsMapWrapper() { super(); } @Override public void clear() { throw new UnsupportedOperationException("sysprops#clear() N/A"); } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public boolean containsValue(Object value) { // not the most efficient implementation, but we do not expect it to be called much Properties props = System.getProperties(); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (Objects.equals(v, value)) { return true; } } return false; } @Override public Set<Entry<String, Object>> entrySet() { Properties props = System.getProperties(); // return a copy in order to avoid concurrent modifications Set<Entry<String, Object>> entries = new TreeSet<Entry<String, Object>>(Pair.<String, Object>byKeyEntryComparator()); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (v != null) { entries.add(new Pair<>(getUnmappedSyspropKey(key), v)); } } return entries; } @Override public Object get(Object key) { return (key instanceof String) ? System.getProperty(getMappedSyspropKey(key)) : null; } @Override public boolean isEmpty() { return GenericUtils.isEmpty(keySet()); } @Override public Set<String> keySet() { Properties props = System.getProperties(); Set<String> keys = new TreeSet<>(); // filter out any non-SSHD properties for (String key : props.stringPropertyNames()) { if (isMappedSyspropKey(key)) { keys.add(getUnmappedSyspropKey(key)); } } return keys; } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException("sysprops#put(" + key + ")[" + value + "] N/A"); } @Override public void putAll(Map<? extends String, ? extends Object> m) { throw new UnsupportedOperationException("sysprops#putAll(" + m + ") N/A"); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("sysprops#remove(" + key + ") N/A"); } @Override public int size() { return GenericUtils.size(keySet()); } @Override public Collection<Object> values() { Properties props = System.getProperties(); // return a copy in order to avoid concurrent modifications List<Object> values = new ArrayList<>(props.size()); for (String key : props.stringPropertyNames()) { if (!isMappedSyspropKey(key)) { continue; } Object v = props.getProperty(key); if (v != null) { values.add(v); } } return values; } @Override public String toString() { return Objects.toString(System.getProperties(), null); } /** * @param key Key to be tested * @return {@code true} if key starts with {@link #SYSPROPS_MAPPED_PREFIX} * and continues with a dot followed by some characters */ public static boolean isMappedSyspropKey(String key) { return (GenericUtils.length(key) > (SYSPROPS_MAPPED_PREFIX.length() + 1)) && key.startsWith(SYSPROPS_MAPPED_PREFIX) && (key.charAt(SYSPROPS_MAPPED_PREFIX.length()) == '.'); } /** * @param key Key to be transformed * @return The &quot;pure&quot; key name if a mapped one, same as input otherwise * @see #isMappedSyspropKey(String) */ public static String getUnmappedSyspropKey(Object key) { String s = Objects.toString(key); return isMappedSyspropKey(s) ? s.substring(SYSPROPS_MAPPED_PREFIX.length() + 1 /* skip dot */) : s; } /** * @param key The original key * @return A key prefixed by {@link #SYSPROPS_MAPPED_PREFIX} * @see #isMappedSyspropKey(String) */ public static String getMappedSyspropKey(Object key) { return SYSPROPS_MAPPED_PREFIX + "." + key; } }
Java
package com.baeldung.jhipster5.web.rest; import com.baeldung.jhipster5.BookstoreApp; import com.baeldung.jhipster5.config.Constants; import com.baeldung.jhipster5.domain.Authority; import com.baeldung.jhipster5.domain.User; import com.baeldung.jhipster5.repository.AuthorityRepository; import com.baeldung.jhipster5.repository.UserRepository; import com.baeldung.jhipster5.security.AuthoritiesConstants; import com.baeldung.jhipster5.service.MailService; import com.baeldung.jhipster5.service.UserService; import com.baeldung.jhipster5.service.dto.PasswordChangeDTO; import com.baeldung.jhipster5.service.dto.UserDTO; import com.baeldung.jhipster5.web.rest.errors.ExceptionTranslator; import com.baeldung.jhipster5.web.rest.vm.KeyAndPasswordVM; import com.baeldung.jhipster5.web.rest.vm.ManagedUserVM; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import java.time.Instant; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the AccountResource REST controller. * * @see AccountResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) public class AccountResourceIntTest { @Autowired private UserRepository userRepository; @Autowired private AuthorityRepository authorityRepository; @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; @Autowired private HttpMessageConverter<?>[] httpMessageConverters; @Autowired private ExceptionTranslator exceptionTranslator; @Mock private UserService mockUserService; @Mock private MailService mockMailService; private MockMvc restMvc; private MockMvc restUserMockMvc; @Before public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(mockMailService).sendActivationEmail(any()); AccountResource accountResource = new AccountResource(userRepository, userService, mockMailService); AccountResource accountUserMockResource = new AccountResource(userRepository, mockUserService, mockMailService); this.restMvc = MockMvcBuilders.standaloneSetup(accountResource) .setMessageConverters(httpMessageConverters) .setControllerAdvice(exceptionTranslator) .build(); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource) .setControllerAdvice(exceptionTranslator) .build(); } @Test public void testNonAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); } @Test public void testAuthenticatedUser() throws Exception { restUserMockMvc.perform(get("/api/authenticate") .with(request -> { request.setRemoteUser("test"); return request; }) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("test")); } @Test public void testGetExistingAccount() throws Exception { Set<Authority> authorities = new HashSet<>(); Authority authority = new Authority(); authority.setName(AuthoritiesConstants.ADMIN); authorities.add(authority); User user = new User(); user.setLogin("test"); user.setFirstName("john"); user.setLastName("doe"); user.setEmail("john.doe@jhipster.com"); user.setImageUrl("http://placehold.it/50x50"); user.setLangKey("en"); user.setAuthorities(authorities); when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user)); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.login").value("test")) .andExpect(jsonPath("$.firstName").value("john")) .andExpect(jsonPath("$.lastName").value("doe")) .andExpect(jsonPath("$.email").value("john.doe@jhipster.com")) .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50")) .andExpect(jsonPath("$.langKey").value("en")) .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN)); } @Test public void testGetUnknownAccount() throws Exception { when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty()); restUserMockMvc.perform(get("/api/account") .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isInternalServerError()); } @Test @Transactional public void testRegisterValid() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("test-register-valid"); validUser.setPassword("password"); validUser.setFirstName("Alice"); validUser.setLastName("Test"); validUser.setEmail("test-register-valid@example.com"); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse(); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue(); } @Test @Transactional public void testRegisterInvalidLogin() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("funky-log!n");// <-- invalid invalidUser.setPassword("password"); invalidUser.setFirstName("Funky"); invalidUser.setLastName("One"); invalidUser.setEmail("funky@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidEmail() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("password"); invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("invalid");// <-- invalid invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterInvalidPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword("123");// password with only 3 digits invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterNullPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); invalidUser.setPassword(null);// invalid null password invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); } @Test @Transactional public void testRegisterDuplicateLogin() throws Exception { // First registration ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("alice"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Something"); firstUser.setEmail("alice@example.com"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Duplicate login, different email ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin(firstUser.getLogin()); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail("alice2@example.com"); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setCreatedBy(firstUser.getCreatedBy()); secondUser.setCreatedDate(firstUser.getCreatedDate()); secondUser.setLastModifiedBy(firstUser.getLastModifiedBy()); secondUser.setLastModifiedDate(firstUser.getLastModifiedDate()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // First user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); // Second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); assertThat(testUser.isPresent()).isTrue(); testUser.get().setActivated(true); userRepository.save(testUser.get()); // Second (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterDuplicateEmail() throws Exception { // First user ManagedUserVM firstUser = new ManagedUserVM(); firstUser.setLogin("test-register-duplicate-email"); firstUser.setPassword("password"); firstUser.setFirstName("Alice"); firstUser.setLastName("Test"); firstUser.setEmail("test-register-duplicate-email@example.com"); firstUser.setImageUrl("http://placehold.it/50x50"); firstUser.setLangKey(Constants.DEFAULT_LANGUAGE); firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Register first user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser1.isPresent()).isTrue(); // Duplicate email, different login ManagedUserVM secondUser = new ManagedUserVM(); secondUser.setLogin("test-register-duplicate-email-2"); secondUser.setPassword(firstUser.getPassword()); secondUser.setFirstName(firstUser.getFirstName()); secondUser.setLastName(firstUser.getLastName()); secondUser.setEmail(firstUser.getEmail()); secondUser.setImageUrl(firstUser.getImageUrl()); secondUser.setLangKey(firstUser.getLangKey()); secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register second (non activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); assertThat(testUser2.isPresent()).isFalse(); Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2"); assertThat(testUser3.isPresent()).isTrue(); // Duplicate email - with uppercase email address ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM(); userWithUpperCaseEmail.setId(firstUser.getId()); userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3"); userWithUpperCaseEmail.setPassword(firstUser.getPassword()); userWithUpperCaseEmail.setFirstName(firstUser.getFirstName()); userWithUpperCaseEmail.setLastName(firstUser.getLastName()); userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com"); userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl()); userWithUpperCaseEmail.setLangKey(firstUser.getLangKey()); userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register third (not activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) .andExpect(status().isCreated()); Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); assertThat(testUser4.isPresent()).isTrue(); assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); testUser4.get().setActivated(true); userService.updateUser((new UserDTO(testUser4.get()))); // Register 4th (already activated) user restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @Test @Transactional public void testRegisterAdminIsIgnored() throws Exception { ManagedUserVM validUser = new ManagedUserVM(); validUser.setLogin("badguy"); validUser.setPassword("password"); validUser.setFirstName("Bad"); validUser.setLastName("Guy"); validUser.setEmail("badguy@example.com"); validUser.setActivated(true); validUser.setImageUrl("http://placehold.it/50x50"); validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); Optional<User> userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup.isPresent()).isTrue(); assertThat(userDup.get().getAuthorities()).hasSize(1) .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @Test @Transactional public void testActivateAccount() throws Exception { final String activationKey = "some activation key"; User user = new User(); user.setLogin("activate-account"); user.setEmail("activate-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(false); user.setActivationKey(activationKey); userRepository.saveAndFlush(user); restMvc.perform(get("/api/activate?key={activationKey}", activationKey)) .andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); } @Test @Transactional public void testActivateAccountWithWrongKey() throws Exception { restMvc.perform(get("/api/activate?key=wrongActivationKey")) .andExpect(status().isInternalServerError()); } @Test @Transactional @WithMockUser("save-account") public void testSaveAccount() throws Exception { User user = new User(); user.setLogin("save-account"); user.setEmail("save-account@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-account@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName()); assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName()); assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail()); assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey()); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl()); assertThat(updatedUser.getActivated()).isEqualTo(true); assertThat(updatedUser.getAuthorities()).isEmpty(); } @Test @Transactional @WithMockUser("save-invalid-email") public void testSaveInvalidEmail() throws Exception { User user = new User(); user.setLogin("save-invalid-email"); user.setEmail("save-invalid-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("invalid email"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); } @Test @Transactional @WithMockUser("save-existing-email") public void testSaveExistingEmail() throws Exception { User user = new User(); user.setLogin("save-existing-email"); user.setEmail("save-existing-email@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); User anotherUser = new User(); anotherUser.setLogin("save-existing-email2"); anotherUser.setEmail("save-existing-email2@example.com"); anotherUser.setPassword(RandomStringUtils.random(60)); anotherUser.setActivated(true); userRepository.saveAndFlush(anotherUser); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-existing-email2@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com"); } @Test @Transactional @WithMockUser("save-existing-email-and-login") public void testSaveExistingEmailAndLogin() throws Exception { User user = new User(); user.setLogin("save-existing-email-and-login"); user.setEmail("save-existing-email-and-login@example.com"); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); userRepository.saveAndFlush(user); UserDTO userDTO = new UserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); userDTO.setEmail("save-existing-email-and-login@example.com"); userDTO.setActivated(false); userDTO.setImageUrl("http://placehold.it/50x50"); userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); restMvc.perform( post("/api/account") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com"); } @Test @Transactional @WithMockUser("change-password-wrong-existing-password") public void testChangePasswordWrongExistingPassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-wrong-existing-password"); user.setEmail("change-password-wrong-existing-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse(); assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password") public void testChangePassword() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password"); user.setEmail("change-password@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password")))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue(); } @Test @Transactional @WithMockUser("change-password-too-small") public void testChangePasswordTooSmall() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-small"); user.setEmail("change-password-too-small@example.com"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-too-long") public void testChangePasswordTooLong() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-too-long"); user.setEmail("change-password-too-long@example.com"); userRepository.saveAndFlush(user); String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword)))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional @WithMockUser("change-password-empty") public void testChangePasswordEmpty() throws Exception { User user = new User(); String currentPassword = RandomStringUtils.random(60); user.setPassword(passwordEncoder.encode(currentPassword)); user.setLogin("change-password-empty"); user.setEmail("change-password-empty@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/change-password") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "")))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword()); } @Test @Transactional public void testRequestPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@example.com")) .andExpect(status().isOk()); } @Test @Transactional public void testRequestPasswordResetUpperCaseEmail() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setActivated(true); user.setLogin("password-reset"); user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); restMvc.perform(post("/api/account/reset-password/init") .content("password-reset@EXAMPLE.COM")) .andExpect(status().isOk()); } @Test public void testRequestPasswordResetWrongEmail() throws Exception { restMvc.perform( post("/api/account/reset-password/init") .content("password-reset-wrong-email@example.com")) .andExpect(status().isBadRequest()); } @Test @Transactional public void testFinishPasswordReset() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset"); user.setEmail("finish-password-reset@example.com"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue(); } @Test @Transactional public void testFinishPasswordResetTooSmall() throws Exception { User user = new User(); user.setPassword(RandomStringUtils.random(60)); user.setLogin("finish-password-reset-too-small"); user.setEmail("finish-password-reset-too-small@example.com"); user.setResetDate(Instant.now().plusSeconds(60)); user.setResetKey("reset key too small"); userRepository.saveAndFlush(user); KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("foo"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse(); } @Test @Transactional public void testFinishPasswordResetWrongKey() throws Exception { KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM(); keyAndPassword.setKey("wrong reset key"); keyAndPassword.setNewPassword("new password"); restMvc.perform( post("/api/account/reset-password/finish") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) .andExpect(status().isInternalServerError()); } }
Java
import { defineMessages } from 'react-intl'; export default defineMessages({ save: { id: 'cboard.components.FormDialog.save', defaultMessage: 'Save' }, cancel: { id: 'cboard.components.FormDialog.cancel', defaultMessage: 'Cancel' } });
Java
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Defines various restore steps that will be used by common tasks in restore * * @package core_backup * @subpackage moodle2 * @category backup * @copyright 2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * delete old directories and conditionally create backup_temp_ids table */ class restore_create_and_clean_temp_stuff extends restore_execution_step { protected function define_execution() { $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally // If the table already exists, it's because restore_prechecks have been executed in the same // request (without problems) and it already contains a bunch of preloaded information (users...) // that we aren't going to execute again if ($exists) { // Inform plan about preloaded information $this->task->set_preloaded_information(); } // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_contextid(); $newitemid = context_course::instance($this->get_courseid())->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning $itemid = $this->task->get_old_system_contextid(); $newitemid = context_system::instance()->id; restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid); // Create the old-course-id to new-course-id mapping, we need that available since the beginning $itemid = $this->task->get_old_courseid(); $newitemid = $this->get_courseid(); restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid); } } /** * delete the temp dir used by backup/restore (conditionally), * delete old directories and drop temp ids table */ class restore_drop_and_clean_temp_stuff extends restore_execution_step { protected function define_execution() { global $CFG; restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table $progress = $this->task->get_progress(); $progress->start_progress('Deleting backup dir'); backup_helper::delete_old_backup_dirs(strtotime('-1 week'), $progress); // Delete > 1 week old temp dirs. if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir } $progress->end_progress(); } } /** * Restore calculated grade items, grade categories etc */ class restore_gradebook_structure_step extends restore_structure_step { /** * To conditionally decide if this step must be executed * Note the "settings" conditions are evaluated in the * corresponding task. Here we check for other conditions * not being restore settings (files, site settings...) */ protected function execute_condition() { global $CFG, $DB; if ($this->get_courseid() == SITEID) { return false; } // No gradebook info found, don't execute $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Some module present in backup file isn't available to restore // in this site, don't execute if ($this->task->is_missing_modules()) { return false; } // Some activity has been excluded to be restored, don't execute if ($this->task->is_excluding_activities()) { return false; } // There should only be one grade category (the 1 associated with the course itself) // If other categories already exist we're restoring into an existing course. // Restoring categories into a course with an existing category structure is unlikely to go well $category = new stdclass(); $category->courseid = $this->get_courseid(); $catcount = $DB->count_records('grade_categories', (array)$category); if ($catcount>1) { return false; } // Arrived here, execute the step return true; } protected function define_structure() { $paths = array(); $userinfo = $this->task->get_setting_value('users'); $paths[] = new restore_path_element('gradebook', '/gradebook'); $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category'); $paths[] = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item'); if ($userinfo) { $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade'); } $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter'); $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting'); return $paths; } protected function process_gradebook($data) { } protected function process_grade_item($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->courseid = $this->get_courseid(); if ($data->itemtype=='manual') { // manual grade items store category id in categoryid $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL); // if mapping failed put in course's grade category if (NULL == $data->categoryid) { $coursecat = grade_category::fetch_course_category($this->get_courseid()); $data->categoryid = $coursecat->id; } } else if ($data->itemtype=='course') { // course grade item stores their category id in iteminstance $coursecat = grade_category::fetch_course_category($this->get_courseid()); $data->iteminstance = $coursecat->id; } else if ($data->itemtype=='category') { // category grade items store their category id in iteminstance $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL); } else { throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype); } $data->scaleid = $this->get_mappingid('scale', $data->scaleid, NULL); $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL); $data->locktime = $this->apply_date_offset($data->locktime); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $coursecategory = $newitemid = null; //course grade item should already exist so updating instead of inserting if($data->itemtype=='course') { //get the ID of the already created grade item $gi = new stdclass(); $gi->courseid = $this->get_courseid(); $gi->itemtype = $data->itemtype; //need to get the id of the grade_category that was automatically created for the course $category = new stdclass(); $category->courseid = $this->get_courseid(); $category->parent = null; //course category fullname starts out as ? but may be edited //$category->fullname = '?'; $coursecategory = $DB->get_record('grade_categories', (array)$category); $gi->iteminstance = $coursecategory->id; $existinggradeitem = $DB->get_record('grade_items', (array)$gi); if (!empty($existinggradeitem)) { $data->id = $newitemid = $existinggradeitem->id; $DB->update_record('grade_items', $data); } } else if ($data->itemtype == 'manual') { // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists. $gi = array( 'itemtype' => $data->itemtype, 'courseid' => $data->courseid, 'itemname' => $data->itemname, 'categoryid' => $data->categoryid, ); $newitemid = $DB->get_field('grade_items', 'id', $gi); } if (empty($newitemid)) { //in case we found the course category but still need to insert the course grade item if ($data->itemtype=='course' && !empty($coursecategory)) { $data->iteminstance = $coursecategory->id; } $newitemid = $DB->insert_record('grade_items', $data); } $this->set_mapping('grade_item', $oldid, $newitemid); } protected function process_grade_grade($data) { global $DB; $data = (object)$data; $oldid = $data->id; $olduserid = $data->userid; $data->itemid = $this->get_new_parentid('grade_item'); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->locktime = $this->apply_date_offset($data->locktime); // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? $data->overridden = $this->apply_date_offset($data->overridden); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid)); if ($gradeexists) { $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } else { $newitemid = $DB->insert_record('grade_grades', $data); $this->set_mapping('grade_grades', $oldid, $newitemid); } } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } protected function process_grade_category($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->course = $this->get_courseid(); $data->courseid = $data->course; $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $newitemid = null; //no parent means a course level grade category. That may have been created when the course was created if(empty($data->parent)) { //parent was being saved as 0 when it should be null $data->parent = null; //get the already created course level grade category $category = new stdclass(); $category->courseid = $this->get_courseid(); $category->parent = null; $coursecategory = $DB->get_record('grade_categories', (array)$category); if (!empty($coursecategory)) { $data->id = $newitemid = $coursecategory->id; $DB->update_record('grade_categories', $data); } } // Add a warning about a removed setting. if (!empty($data->aggregatesubcats)) { set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1); } //need to insert a course category if (empty($newitemid)) { $newitemid = $DB->insert_record('grade_categories', $data); } $this->set_mapping('grade_category', $oldid, $newitemid); } protected function process_grade_letter($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->contextid = context_course::instance($this->get_courseid())->id; $gradeletter = (array)$data; unset($gradeletter['id']); if (!$DB->record_exists('grade_letters', $gradeletter)) { $newitemid = $DB->insert_record('grade_letters', $data); } else { $newitemid = $data->id; } $this->set_mapping('grade_letter', $oldid, $newitemid); } protected function process_grade_setting($data) { global $DB; $data = (object)$data; $oldid = $data->id; $data->courseid = $this->get_courseid(); if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) { $newitemid = $DB->insert_record('grade_settings', $data); } else { $newitemid = $data->id; } $this->set_mapping('grade_setting', $oldid, $newitemid); } /** * put all activity grade items in the correct grade category and mark all for recalculation */ protected function after_execute() { global $DB; $conditions = array( 'backupid' => $this->get_restoreid(), 'itemname' => 'grade_item'//, //'itemid' => $itemid ); $rs = $DB->get_recordset('backup_ids_temp', $conditions); // We need this for calculation magic later on. $mappings = array(); if (!empty($rs)) { foreach($rs as $grade_item_backup) { // Store the oldid with the new id. $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid; $updateobj = new stdclass(); $updateobj->id = $grade_item_backup->newitemid; //if this is an activity grade item that needs to be put back in its correct category if (!empty($grade_item_backup->parentitemid)) { $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null); if (!is_null($oldcategoryid)) { $updateobj->categoryid = $oldcategoryid; $DB->update_record('grade_items', $updateobj); } } else { //mark course and category items as needing to be recalculated $updateobj->needsupdate=1; $DB->update_record('grade_items', $updateobj); } } } $rs->close(); // We need to update the calculations for calculated grade items that may reference old // grade item ids using ##gi\d+##. // $mappings can be empty, use 0 if so (won't match ever) list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0); $sql = "SELECT gi.id, gi.calculation FROM {grade_items} gi WHERE gi.id {$sql} AND calculation IS NOT NULL"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $gradeitem) { // Collect all of the used grade item id references if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) { // This calculation doesn't reference any other grade items... EASY! continue; } // For this next bit we are going to do the replacement of id's in two steps: // 1. We will replace all old id references with a special mapping reference. // 2. We will replace all mapping references with id's // Why do we do this? // Because there potentially there will be an overlap of ids within the query and we // we substitute the wrong id.. safest way around this is the two step system $calculationmap = array(); $mapcount = 0; foreach ($matches[1] as $match) { // Check that the old id is known to us, if not it was broken to begin with and will // continue to be broken. if (!array_key_exists($match, $mappings)) { continue; } // Our special mapping key $mapping = '##MAPPING'.$mapcount.'##'; // The old id that exists within the calculation now $oldid = '##gi'.$match.'##'; // The new id that we want to replace the old one with. $newid = '##gi'.$mappings[$match].'##'; // Replace in the special mapping key $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation); // And record the mapping $calculationmap[$mapping] = $newid; $mapcount++; } // Iterate all special mappings for this calculation and replace in the new id's foreach ($calculationmap as $mapping => $newid) { $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation); } // Update the calculation now that its being remapped $DB->update_record('grade_items', $gradeitem); } $rs->close(); // Need to correct the grade category path and parent $conditions = array( 'courseid' => $this->get_courseid() ); $rs = $DB->get_recordset('grade_categories', $conditions); // Get all the parents correct first as grade_category::build_path() loads category parents from the DB foreach ($rs as $gc) { if (!empty($gc->parent)) { $grade_category = new stdClass(); $grade_category->id = $gc->id; $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent); $DB->update_record('grade_categories', $grade_category); } } $rs->close(); // Now we can rebuild all the paths $rs = $DB->get_recordset('grade_categories', $conditions); foreach ($rs as $gc) { $grade_category = new stdClass(); $grade_category->id = $gc->id; $grade_category->path = grade_category::build_path($gc); $grade_category->depth = substr_count($grade_category->path, '/') - 1; $DB->update_record('grade_categories', $grade_category); } $rs->close(); // Restore marks items as needing update. Update everything now. grade_regrade_final_grades($this->get_courseid()); } } /** * Step in charge of restoring the grade history of a course. * * The execution conditions are itendical to {@link restore_gradebook_structure_step} because * we do not want to restore the history if the gradebook and its content has not been * restored. At least for now. */ class restore_grade_history_structure_step extends restore_structure_step { protected function execute_condition() { global $CFG, $DB; if ($this->get_courseid() == SITEID) { return false; } // No gradebook info found, don't execute. $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Some module present in backup file isn't available to restore in this site, don't execute. if ($this->task->is_missing_modules()) { return false; } // Some activity has been excluded to be restored, don't execute. if ($this->task->is_excluding_activities()) { return false; } // There should only be one grade category (the 1 associated with the course itself). $category = new stdclass(); $category->courseid = $this->get_courseid(); $catcount = $DB->count_records('grade_categories', (array)$category); if ($catcount > 1) { return false; } // Arrived here, execute the step. return true; } protected function define_structure() { $paths = array(); // Settings to use. $userinfo = $this->get_setting_value('users'); $history = $this->get_setting_value('grade_histories'); if ($userinfo && $history) { $paths[] = new restore_path_element('grade_grade', '/grade_history/grade_grades/grade_grade'); } return $paths; } protected function process_grade_grade($data) { global $DB; $data = (object)($data); $olduserid = $data->userid; unset($data->id); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { // Do not apply the date offsets as this is history. $data->itemid = $this->get_mappingid('grade_item', $data->itemid); $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); $DB->insert_record('grade_grades_history', $data); } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } } /** * decode all the interlinks present in restored content * relying 100% in the restore_decode_processor that handles * both the contents to modify and the rules to be applied */ class restore_decode_interlinks extends restore_execution_step { protected function define_execution() { // Get the decoder (from the plan) $decoder = $this->task->get_decoder(); restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules // And launch it, everything will be processed $decoder->execute(); } } /** * first, ensure that we have no gaps in section numbers * and then, rebuid the course cache */ class restore_rebuild_course_cache extends restore_execution_step { protected function define_execution() { global $DB; // Although there is some sort of auto-recovery of missing sections // present in course/formats... here we check that all the sections // from 0 to MAX(section->section) exist, creating them if necessary $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid())); // Iterate over all sections for ($i = 0; $i <= $maxsection; $i++) { // If the section $i doesn't exist, create it if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) { $sectionrec = array( 'course' => $this->get_courseid(), 'section' => $i); $DB->insert_record('course_sections', $sectionrec); // missing section created } } // Rebuild cache now that all sections are in place rebuild_course_cache($this->get_courseid()); cache_helper::purge_by_event('changesincourse'); cache_helper::purge_by_event('changesincoursecat'); } } /** * Review all the tasks having one after_restore method * executing it to perform some final adjustments of information * not available when the task was executed. */ class restore_execute_after_restore extends restore_execution_step { protected function define_execution() { // Simply call to the execute_after_restore() method of the task // that always is the restore_final_task $this->task->launch_execute_after_restore(); } } /** * Review all the (pending) block positions in backup_ids, matching by * contextid, creating positions as needed. This is executed by the * final task, once all the contexts have been created */ class restore_review_pending_block_positions extends restore_execution_step { protected function define_execution() { global $DB; // Get all the block_position objects pending to match $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); // Process block positions, creating them or accumulating for final step foreach($rs as $posrec) { // Get the complete position object out of the info field. $position = backup_controller_dbops::decode_backup_temp_info($posrec->info); // If position is for one already mapped (known) contextid // process it now, creating the position, else nothing to // do, position finally discarded if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) { $position->contextid = $newctx->newitemid; // Create the block position $DB->insert_record('block_positions', $position); } } $rs->close(); } } /** * Updates the availability data for course modules and sections. * * Runs after the restore of all course modules, sections, and grade items has * completed. This is necessary in order to update IDs that have changed during * restore. * * @package core_backup * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_update_availability extends restore_execution_step { protected function define_execution() { global $CFG, $DB; // Note: This code runs even if availability is disabled when restoring. // That will ensure that if you later turn availability on for the site, // there will be no incorrect IDs. (It doesn't take long if the restored // data does not contain any availability information.) // Get modinfo with all data after resetting cache. rebuild_course_cache($this->get_courseid(), true); $modinfo = get_fast_modinfo($this->get_courseid()); // Get the date offset for this restore. $dateoffset = $this->apply_date_offset(1) - 1; // Update all sections that were restored. $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); $sectionsbyid = null; foreach ($rs as $rec) { if (is_null($sectionsbyid)) { $sectionsbyid = array(); foreach ($modinfo->get_section_info_all() as $section) { $sectionsbyid[$section->id] = $section; } } if (!array_key_exists($rec->newitemid, $sectionsbyid)) { // If the section was not fully restored for some reason // (e.g. due to an earlier error), skip it. $this->get_logger()->process('Section not fully restored: id ' . $rec->newitemid, backup::LOG_WARNING); continue; } $section = $sectionsbyid[$rec->newitemid]; if (!is_null($section->availability)) { $info = new \core_availability\info_section($section); $info->update_after_restore($this->get_restoreid(), $this->get_courseid(), $this->get_logger(), $dateoffset); } } $rs->close(); // Update all modules that were restored. $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid'); foreach ($rs as $rec) { if (!array_key_exists($rec->newitemid, $modinfo->cms)) { // If the module was not fully restored for some reason // (e.g. due to an earlier error), skip it. $this->get_logger()->process('Module not fully restored: id ' . $rec->newitemid, backup::LOG_WARNING); continue; } $cm = $modinfo->get_cm($rec->newitemid); if (!is_null($cm->availability)) { $info = new \core_availability\info_module($cm); $info->update_after_restore($this->get_restoreid(), $this->get_courseid(), $this->get_logger(), $dateoffset); } } $rs->close(); } } /** * Process legacy module availability records in backup_ids. * * Matches course modules and grade item id once all them have been already restored. * Only if all matchings are satisfied the availability condition will be created. * At the same time, it is required for the site to have that functionality enabled. * * This step is included only to handle legacy backups (2.6 and before). It does not * do anything for newer backups. * * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU Public License */ class restore_process_course_modules_availability extends restore_execution_step { protected function define_execution() { global $CFG, $DB; // Site hasn't availability enabled if (empty($CFG->enableavailability)) { return; } // Do both modules and sections. foreach (array('module', 'section') as $table) { // Get all the availability objects to process. $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability'); $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info'); // Process availabilities, creating them if everything matches ok. foreach ($rs as $availrec) { $allmatchesok = true; // Get the complete legacy availability object. $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info); // Note: This code used to update IDs, but that is now handled by the // current code (after restore) instead of this legacy code. // Get showavailability option. $thingid = ($table === 'module') ? $availability->coursemoduleid : $availability->coursesectionid; $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), $table . '_showavailability', $thingid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availability object is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_' . $table . 's', 'availability', array('id' => $thingid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_condition( $currentvalue, $availability, $show); $DB->set_field('course_' . $table . 's', 'availability', $newvalue, array('id' => $thingid)); } } $rs->close(); } } /* * Execution step that, *conditionally* (if there isn't preloaded information) * will load the inforef files for all the included course/section/activity tasks * to backup_temp_ids. They will be stored with "xxxxref" as itemname */ class restore_load_included_inforef_records extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } // Get all the included tasks $tasks = restore_dbops::get_included_tasks($this->get_restoreid()); $progress = $this->task->get_progress(); $progress->start_progress($this->get_name(), count($tasks)); foreach ($tasks as $task) { // Load the inforef.xml file if exists $inforefpath = $task->get_taskbasepath() . '/inforef.xml'; if (file_exists($inforefpath)) { // Load each inforef file to temp_ids. restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress); } } $progress->end_progress(); } } /* * Execution step that will load all the needed files into backup_files_temp * - info: contains the whole original object (times, names...) * (all them being original ids as loaded from xml) */ class restore_load_included_files extends restore_structure_step { protected function define_structure() { $file = new restore_path_element('file', '/files/file'); return array($file); } /** * Process one <file> element from files.xml * * @param array $data the element data */ public function process_file($data) { $data = (object)$data; // handy // load it if needed: // - it it is one of the annotated inforef files (course/section/activity/block) // - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever) // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use, // but then we'll need to change it to load plugins itself (because this is executed too early in restore) $isfileref = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id); $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' || $data->component == 'grouping' || $data->component == 'grade' || $data->component == 'question' || substr($data->component, 0, 5) == 'qtype'); if ($isfileref || $iscomponent) { restore_dbops::set_backup_files_record($this->get_restoreid(), $data); } } } /** * Execution step that, *conditionally* (if there isn't preloaded information), * will load all the needed roles to backup_temp_ids. They will be stored with * "role" itemname. Also it will perform one automatic mapping to roles existing * in the target site, based in permissions of the user performing the restore, * archetypes and other bits. At the end, each original role will have its associated * target role or 0 if it's going to be skipped. Note we wrap everything over one * restore_dbops method, as far as the same stuff is going to be also executed * by restore prechecks */ class restore_load_and_map_roles extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded return; } $file = $this->get_basepath() . '/roles.xml'; // Load needed toles to temp_ids restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file); // Process roles, mapping/skipping. Any error throws exception // Note we pass controller's info because it can contain role mapping information // about manual mappings performed by UI restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * and users have been selected in settings, will load all the needed users * to backup_temp_ids. They will be stored with "user" itemname and with * their original contextid as paremitemid */ class restore_load_included_users extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do return; } $file = $this->get_basepath() . '/users.xml'; // Load needed users to temp_ids. restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress()); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * and users have been selected in settings, will process all the needed users * in order to decide and perform any action with them (create / map / error) * Note: Any error will cause exception, as far as this is the same processing * than the one into restore prechecks (that should have stopped process earlier) */ class restore_process_included_users extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do return; } restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress()); } } /** * Execution step that will create all the needed users as calculated * by @restore_process_included_users (those having newiteind = 0) */ class restore_create_included_users extends restore_execution_step { protected function define_execution() { restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(), $this->task->get_userid(), $this->task->get_progress()); } } /** * Structure step that will create all the needed groups and groupings * by loading them from the groups.xml file performing the required matches. * Note group members only will be added if restoring user info */ class restore_groups_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('group', '/groups/group'); $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping'); $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group'); return $paths; } // Processing functions go here public function process_group($data) { global $DB; $data = (object)$data; // handy $data->courseid = $this->get_courseid(); // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another a group in the same course $context = context_course::instance($data->courseid); if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) { unset($data->idnumber); } } else { unset($data->idnumber); } $oldid = $data->id; // need this saved for later $restorefiles = false; // Only if we end creating the group // Search if the group already exists (by name & description) in the target course $description_clause = ''; $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); if (!empty($data->description)) { $description_clause = ' AND ' . $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); $params['description'] = $data->description; } if (!$groupdb = $DB->get_record_sql("SELECT * FROM {groups} WHERE courseid = :courseid AND name = :grname $description_clause", $params)) { // group doesn't exist, create $newitemid = $DB->insert_record('groups', $data); $restorefiles = true; // We'll restore the files } else { // group exists, use it $newitemid = $groupdb->id; } // Save the id mapping $this->set_mapping('group', $oldid, $newitemid, $restorefiles); // Invalidate the course group data cache just in case. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); } public function process_grouping($data) { global $DB; $data = (object)$data; // handy $data->courseid = $this->get_courseid(); // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another a grouping in the same course $context = context_course::instance($data->courseid); if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) { if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) { unset($data->idnumber); } } else { unset($data->idnumber); } $oldid = $data->id; // need this saved for later $restorefiles = false; // Only if we end creating the grouping // Search if the grouping already exists (by name & description) in the target course $description_clause = ''; $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name); if (!empty($data->description)) { $description_clause = ' AND ' . $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description'); $params['description'] = $data->description; } if (!$groupingdb = $DB->get_record_sql("SELECT * FROM {groupings} WHERE courseid = :courseid AND name = :grname $description_clause", $params)) { // grouping doesn't exist, create $newitemid = $DB->insert_record('groupings', $data); $restorefiles = true; // We'll restore the files } else { // grouping exists, use it $newitemid = $groupingdb->id; } // Save the id mapping $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles); // Invalidate the course group data cache just in case. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid)); } public function process_grouping_group($data) { global $CFG; require_once($CFG->dirroot.'/group/lib.php'); $data = (object)$data; groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded); } protected function after_execute() { // Add group related files, matching with "group" mappings $this->add_related_files('group', 'icon', 'group'); $this->add_related_files('group', 'description', 'group'); // Add grouping related files, matching with "grouping" mappings $this->add_related_files('grouping', 'description', 'grouping'); // Invalidate the course group data. cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid())); } } /** * Structure step that will create all the needed group memberships * by loading them from the groups.xml file performing the required matches. */ class restore_groups_members_structure_step extends restore_structure_step { protected $plugins = null; protected function define_structure() { $paths = array(); // Add paths here if ($this->get_setting_value('users')) { $paths[] = new restore_path_element('group', '/groups/group'); $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member'); } return $paths; } public function process_group($data) { $data = (object)$data; // handy // HACK ALERT! // Not much to do here, this groups mapping should be already done from restore_groups_structure_step. // Let's fake internal state to make $this->get_new_parentid('group') work. $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id)); } public function process_member($data) { global $DB, $CFG; require_once("$CFG->dirroot/group/lib.php"); // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled. $data = (object)$data; // handy // get parent group->id $data->groupid = $this->get_new_parentid('group'); // map user newitemid and insert if not member already if ($data->userid = $this->get_mappingid('user', $data->userid)) { if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) { // Check the component, if any, exists. if (empty($data->component)) { groups_add_member($data->groupid, $data->userid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment groups - ignore the component and just find out the instance via new id, // it is possible that enrolment was restored using different plugin type. if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid); } } } } else { $dir = core_component::get_component_directory($data->component); if ($dir and is_dir($dir)) { if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) { return; } } // Bad luck, plugin could not restore the data, let's add normal membership. groups_add_member($data->groupid, $data->userid); $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead."; $this->log($message, backup::LOG_WARNING); } } } } } /** * Structure step that will create all the needed scales * by loading them from the scales.xml */ class restore_scales_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('scale', '/scales_definition/scale'); return $paths; } protected function process_scale($data) { global $DB; $data = (object)$data; $restorefiles = false; // Only if we end creating the group $oldid = $data->id; // need this saved for later // Look for scale (by 'scale' both in standard (course=0) and current course // with priority to standard scales (ORDER clause) // scale is not course unique, use get_record_sql to suppress warning // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides $compare_scale_clause = $DB->sql_compare_text('scale') . ' = ' . $DB->sql_compare_text(':scaledesc'); $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale); if (!$scadb = $DB->get_record_sql("SELECT * FROM {scale} WHERE courseid IN (0, :courseid) AND $compare_scale_clause ORDER BY courseid", $params, IGNORE_MULTIPLE)) { // Remap the user if possible, defaut to user performing the restore if not $userid = $this->get_mappingid('user', $data->userid); $data->userid = $userid ? $userid : $this->task->get_userid(); // Remap the course if course scale $data->courseid = $data->courseid ? $this->get_courseid() : 0; // If global scale (course=0), check the user has perms to create it // falling to course scale if not $systemctx = context_system::instance(); if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } // scale doesn't exist, create $newitemid = $DB->insert_record('scale', $data); $restorefiles = true; // We'll restore the files } else { // scale exists, use it $newitemid = $scadb->id; } // Save the id mapping (with files support at system context) $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); } protected function after_execute() { // Add scales related files, matching with "scale" mappings $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid()); } } /** * Structure step that will create all the needed outocomes * by loading them from the outcomes.xml */ class restore_outcomes_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); // Add paths here $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome'); return $paths; } protected function process_outcome($data) { global $DB; $data = (object)$data; $restorefiles = false; // Only if we end creating the group $oldid = $data->id; // need this saved for later // Look for outcome (by shortname both in standard (courseid=null) and current course // with priority to standard outcomes (ORDER clause) // outcome is not course unique, use get_record_sql to suppress warning $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname); if (!$outdb = $DB->get_record_sql('SELECT * FROM {grade_outcomes} WHERE shortname = :shortname AND (courseid = :courseid OR courseid IS NULL) ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) { // Remap the user $userid = $this->get_mappingid('user', $data->usermodified); $data->usermodified = $userid ? $userid : $this->task->get_userid(); // Remap the scale $data->scaleid = $this->get_mappingid('scale', $data->scaleid); // Remap the course if course outcome $data->courseid = $data->courseid ? $this->get_courseid() : null; // If global outcome (course=null), check the user has perms to create it // falling to course outcome if not $systemctx = context_system::instance(); if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) { $data->courseid = $this->get_courseid(); } // outcome doesn't exist, create $newitemid = $DB->insert_record('grade_outcomes', $data); $restorefiles = true; // We'll restore the files } else { // scale exists, use it $newitemid = $outdb->id; } // Set the corresponding grade_outcomes_courses record $outcourserec = new stdclass(); $outcourserec->courseid = $this->get_courseid(); $outcourserec->outcomeid = $newitemid; if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) { $DB->insert_record('grade_outcomes_courses', $outcourserec); } // Save the id mapping (with files support at system context) $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid()); } protected function after_execute() { // Add outcomes related files, matching with "outcome" mappings $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid()); } } /** * Execution step that, *conditionally* (if there isn't preloaded information * will load all the question categories and questions (header info only) * to backup_temp_ids. They will be stored with "question_category" and * "question" itemnames and with their original contextid and question category * id as paremitemids */ class restore_load_categories_and_questions extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } $file = $this->get_basepath() . '/questions.xml'; restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file); } } /** * Execution step that, *conditionally* (if there isn't preloaded information) * will process all the needed categories and questions * in order to decide and perform any action with them (create / map / error) * Note: Any error will cause exception, as far as this is the same processing * than the one into restore prechecks (that should have stopped process earlier) */ class restore_process_categories_and_questions extends restore_execution_step { protected function define_execution() { if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do return; } restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite()); } } /** * Structure step that will read the section.xml creating/updating sections * as needed, rebuilding course cache and other friends */ class restore_section_structure_step extends restore_structure_step { protected function define_structure() { global $CFG; $paths = array(); $section = new restore_path_element('section', '/section'); $paths[] = $section; if ($CFG->enableavailability) { $paths[] = new restore_path_element('availability', '/section/availability'); $paths[] = new restore_path_element('availability_field', '/section/availability_field'); } $paths[] = new restore_path_element('course_format_options', '/section/course_format_options'); // Apply for 'format' plugins optional paths at section level $this->add_plugin_structure('format', $section); // Apply for 'local' plugins optional paths at section level $this->add_plugin_structure('local', $section); return $paths; } public function process_section($data) { global $CFG, $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later $restorefiles = false; // Look for the section $section = new stdclass(); $section->course = $this->get_courseid(); $section->section = $data->number; // Section doesn't exist, create it with all the info from backup if (!$secrec = $DB->get_record('course_sections', (array)$section)) { $section->name = $data->name; $section->summary = $data->summary; $section->summaryformat = $data->summaryformat; $section->sequence = ''; $section->visible = $data->visible; if (empty($CFG->enableavailability)) { // Process availability information only if enabled. $section->availability = null; } else { $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null; // Include legacy [<2.7] availability data if provided. if (is_null($section->availability)) { $section->availability = \core_availability\info::convert_legacy_fields( $data, true); } } $newitemid = $DB->insert_record('course_sections', $section); $restorefiles = true; // Section exists, update non-empty information } else { $section->id = $secrec->id; if ((string)$secrec->name === '') { $section->name = $data->name; } if (empty($secrec->summary)) { $section->summary = $data->summary; $section->summaryformat = $data->summaryformat; $restorefiles = true; } // Don't update availability (I didn't see a useful way to define // whether existing or new one should take precedence). $DB->update_record('course_sections', $section); $newitemid = $secrec->id; } // Annotate the section mapping, with restorefiles option if needed $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles); // set the new course_section id in the task $this->task->set_sectionid($newitemid); // If there is the legacy showavailability data, store this for later use. // (This data is not present when restoring 'new' backups.) if (isset($data->showavailability)) { // Cache the showavailability flag using the backup_ids data field. restore_dbops::set_backup_ids_record($this->get_restoreid(), 'section_showavailability', $newitemid, 0, null, (object)array('showavailability' => $data->showavailability)); } // Commented out. We never modify course->numsections as far as that is used // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x) // Note: We keep the code here, to know about and because of the possibility of making this // optional based on some setting/attribute in the future // If needed, adjust course->numsections //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) { // if ($numsections < $section->section) { // $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid())); // } //} } /** * Process the legacy availability table record. This table does not exist * in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ public function process_availability($data) { $data = (object)$data; // Simply going to store the whole availability record now, we'll process // all them later in the final task (once all activities have been restored) // Let's call the low level one to be able to store the whole object. $data->coursesectionid = $this->task->get_sectionid(); restore_dbops::set_backup_ids_record($this->get_restoreid(), 'section_availability', $data->id, 0, null, $data); } /** * Process the legacy availability fields table record. This table does not * exist in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ public function process_availability_field($data) { global $DB; $data = (object)$data; // Mark it is as passed by default $passed = true; $customfieldid = null; // If a customfield has been used in order to pass we must be able to match an existing // customfield by name (data->customfield) and type (data->customfieldtype) if (is_null($data->customfield) xor is_null($data->customfieldtype)) { // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. // If one is null but the other isn't something clearly went wrong and we'll skip this condition. $passed = false; } else if (!is_null($data->customfield)) { $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); $customfieldid = $DB->get_field('user_info_field', 'id', $params); $passed = ($customfieldid !== false); } if ($passed) { // Create the object to insert into the database $availfield = new stdClass(); $availfield->coursesectionid = $this->task->get_sectionid(); $availfield->userfield = $data->userfield; $availfield->customfieldid = $customfieldid; $availfield->operator = $data->operator; $availfield->value = $data->value; // Get showavailability option. $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'section_showavailability', $availfield->coursesectionid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availfield object is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_sections', 'availability', array('id' => $availfield->coursesectionid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_field_condition( $currentvalue, $availfield, $show); $DB->set_field('course_sections', 'availability', $newvalue, array('id' => $availfield->coursesectionid)); } } public function process_course_format_options($data) { global $DB; $data = (object)$data; $oldid = $data->id; unset($data->id); $data->sectionid = $this->task->get_sectionid(); $data->courseid = $this->get_courseid(); $newid = $DB->insert_record('course_format_options', $data); $this->set_mapping('course_format_options', $oldid, $newid); } protected function after_execute() { // Add section related files, with 'course_section' itemid to match $this->add_related_files('course', 'section', 'course_section'); } } /** * Structure step that will read the course.xml file, loading it and performing * various actions depending of the site/restore settings. Note that target * course always exist before arriving here so this step will be updating * the course record (never inserting) */ class restore_course_structure_step extends restore_structure_step { /** * @var bool this gets set to true by {@link process_course()} if we are * restoring an old coures that used the legacy 'module security' feature. * If so, we have to do more work in {@link after_execute()}. */ protected $legacyrestrictmodules = false; /** * @var array Used when {@link $legacyrestrictmodules} is true. This is an * array with array keys the module names ('forum', 'quiz', etc.). These are * the modules that are allowed according to the data in the backup file. * In {@link after_execute()} we then have to prevent adding of all the other * types of activity. */ protected $legacyallowedmodules = array(); protected function define_structure() { $course = new restore_path_element('course', '/course'); $category = new restore_path_element('category', '/course/category'); $tag = new restore_path_element('tag', '/course/tags/tag'); $allowed_module = new restore_path_element('allowed_module', '/course/allowed_modules/module'); // Apply for 'format' plugins optional paths at course level $this->add_plugin_structure('format', $course); // Apply for 'theme' plugins optional paths at course level $this->add_plugin_structure('theme', $course); // Apply for 'report' plugins optional paths at course level $this->add_plugin_structure('report', $course); // Apply for 'course report' plugins optional paths at course level $this->add_plugin_structure('coursereport', $course); // Apply for plagiarism plugins optional paths at course level $this->add_plugin_structure('plagiarism', $course); // Apply for local plugins optional paths at course level $this->add_plugin_structure('local', $course); return array($course, $category, $tag, $allowed_module); } /** * Processing functions go here * * @global moodledatabase $DB * @param stdClass $data */ public function process_course($data) { global $CFG, $DB; $data = (object)$data; $fullname = $this->get_setting_value('course_fullname'); $shortname = $this->get_setting_value('course_shortname'); $startdate = $this->get_setting_value('course_startdate'); // Calculate final course names, to avoid dupes list($fullname, $shortname) = restore_dbops::calculate_course_names($this->get_courseid(), $fullname, $shortname); // Need to change some fields before updating the course record $data->id = $this->get_courseid(); $data->fullname = $fullname; $data->shortname= $shortname; // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by // another course on this site. $context = context::instance_by_id($this->task->get_contextid()); if (!empty($data->idnumber) && has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid()) && $this->task->is_samesite() && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) { // Do not reset idnumber. } else { $data->idnumber = ''; } // Any empty value for course->hiddensections will lead to 0 (default, show collapsed). // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532 if (empty($data->hiddensections)) { $data->hiddensections = 0; } // Set legacyrestrictmodules to true if the course was resticting modules. If so // then we will need to process restricted modules after execution. $this->legacyrestrictmodules = !empty($data->restrictmodules); $data->startdate= $this->apply_date_offset($data->startdate); if ($data->defaultgroupingid) { $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid); } if (empty($CFG->enablecompletion)) { $data->enablecompletion = 0; $data->completionstartonenrol = 0; $data->completionnotify = 0; } $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search if (!array_key_exists($data->lang, $languages)) { $data->lang = ''; } $themes = get_list_of_themes(); // Get themes for quick search later if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) { $data->theme = ''; } // Check if this is an old SCORM course format. if ($data->format == 'scorm') { $data->format = 'singleactivity'; $data->activitytype = 'scorm'; } // Course record ready, update it $DB->update_record('course', $data); course_get_format($data)->update_course_format_options($data); // Role name aliases restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid()); } public function process_category($data) { // Nothing to do with the category. UI sets it before restore starts } public function process_tag($data) { global $CFG, $DB; $data = (object)$data; if (!empty($CFG->usetags)) { // if enabled in server // TODO: This is highly inneficient. Each time we add one tag // we fetch all the existing because tag_set() deletes them // so everything must be reinserted on each call $tags = array(); $existingtags = tag_get_tags('course', $this->get_courseid()); // Re-add all the existitng tags foreach ($existingtags as $existingtag) { $tags[] = $existingtag->rawname; } // Add the one being restored $tags[] = $data->rawname; // Send all the tags back to the course tag_set('course', $this->get_courseid(), $tags, 'core', context_course::instance($this->get_courseid())->id); } } public function process_allowed_module($data) { $data = (object)$data; // Backwards compatiblity support for the data that used to be in the // course_allowed_modules table. if ($this->legacyrestrictmodules) { $this->legacyallowedmodules[$data->modulename] = 1; } } protected function after_execute() { global $DB; // Add course related files, without itemid to match $this->add_related_files('course', 'summary', null); $this->add_related_files('course', 'overviewfiles', null); // Deal with legacy allowed modules. if ($this->legacyrestrictmodules) { $context = context_course::instance($this->get_courseid()); list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities'); list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config'); foreach ($managerroleids as $roleid) { unset($roleids[$roleid]); } foreach (core_component::get_plugin_list('mod') as $modname => $notused) { if (isset($this->legacyallowedmodules[$modname])) { // Module is allowed, no worries. continue; } $capability = 'mod/' . $modname . ':addinstance'; foreach ($roleids as $roleid) { assign_capability($capability, CAP_PREVENT, $roleid, $context); } } } } } /** * Execution step that will migrate legacy files if present. */ class restore_course_legacy_files_step extends restore_execution_step { public function define_execution() { global $DB; // Do a check for legacy files and skip if there are none. $sql = 'SELECT count(*) FROM {backup_files_temp} WHERE backupid = ? AND contextid = ? AND component = ? AND filearea = ?'; $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy'); if ($DB->count_records_sql($sql, $params)) { $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid())); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course', 'legacy', $this->task->get_old_contextid(), $this->task->get_userid()); } } } /* * Structure step that will read the roles.xml file (at course/activity/block levels) * containing all the role_assignments and overrides for that context. If corresponding to * one mapped role, they will be applied to target context. Will observe the role_assignments * setting to decide if ras are restored. * * Note: this needs to be executed after all users are enrolled. */ class restore_ras_and_caps_structure_step extends restore_structure_step { protected $plugins = null; protected function define_structure() { $paths = array(); // Observe the role_assignments setting if ($this->get_setting_value('role_assignments')) { $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment'); } $paths[] = new restore_path_element('override', '/roles/role_overrides/override'); return $paths; } /** * Assign roles * * This has to be called after enrolments processing. * * @param mixed $data * @return void */ public function process_assignment($data) { global $DB; $data = (object)$data; // Check roleid, userid are one of the mapped ones if (!$newroleid = $this->get_mappingid('role', $data->roleid)) { return; } if (!$newuserid = $this->get_mappingid('user', $data->userid)) { return; } if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) { // Only assign roles to not deleted users return; } if (!$contextid = $this->task->get_contextid()) { return; } if (empty($data->component)) { // assign standard manual roles // TODO: role_assign() needs one userid param to be able to specify our restore userid role_assign($newroleid, $newuserid, $contextid); } else if ((strpos($data->component, 'enrol_') === 0)) { // Deal with enrolment roles - ignore the component and just find out the instance via new id, // it is possible that enrolment was restored using different plugin type. if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) { if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid); } } } } else { $data->roleid = $newroleid; $data->userid = $newuserid; $data->contextid = $contextid; $dir = core_component::get_component_directory($data->component); if ($dir and is_dir($dir)) { if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) { return; } } // Bad luck, plugin could not restore the data, let's add normal membership. role_assign($data->roleid, $data->userid, $data->contextid); $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead."; $this->log($message, backup::LOG_WARNING); } } public function process_override($data) { $data = (object)$data; // Check roleid is one of the mapped ones $newroleid = $this->get_mappingid('role', $data->roleid); // If newroleid and context are valid assign it via API (it handles dupes and so on) if ($newroleid && $this->task->get_contextid()) { // TODO: assign_capability() needs one userid param to be able to specify our restore userid // TODO: it seems that assign_capability() doesn't check for valid capabilities at all ??? assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid()); } } } /** * If no instances yet add default enrol methods the same way as when creating new course in UI. */ class restore_default_enrolments_step extends restore_execution_step { public function define_execution() { global $DB; // No enrolments in front page. if ($this->get_courseid() == SITEID) { return; } $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST); if ($DB->record_exists('enrol', array('courseid'=>$this->get_courseid(), 'enrol'=>'manual'))) { // Something already added instances, do not add default instances. $plugins = enrol_get_plugins(true); foreach ($plugins as $plugin) { $plugin->restore_sync_course($course); } } else { // Looks like a newly created course. enrol_course_updated(true, $course, null); } } } /** * This structure steps restores the enrol plugins and their underlying * enrolments, performing all the mappings and/or movements required */ class restore_enrolments_structure_step extends restore_structure_step { protected $enrolsynced = false; protected $plugins = null; protected $originalstatus = array(); /** * Conditionally decide if this step should be executed. * * This function checks the following parameter: * * 1. the course/enrolments.xml file exists * * @return bool true is safe to execute, false otherwise */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore enrolments info return false; } return true; } protected function define_structure() { $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol'); $enrolment = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment'); // Attach local plugin stucture to enrol element. $this->add_plugin_structure('enrol', $enrol); return array($enrol, $enrolment); } /** * Create enrolment instances. * * This has to be called after creation of roles * and before adding of role assignments. * * @param mixed $data * @return void */ public function process_enrol($data) { global $DB; $data = (object)$data; $oldid = $data->id; // We'll need this later. unset($data->id); $this->originalstatus[$oldid] = $data->status; if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) { $this->set_mapping('enrol', $oldid, 0); return; } if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } if (!$this->enrolsynced) { // Make sure that all plugin may create instances and enrolments automatically // before the first instance restore - this is suitable especially for plugins // that synchronise data automatically using course->idnumber or by course categories. foreach ($this->plugins as $plugin) { $plugin->restore_sync_course($courserec); } $this->enrolsynced = true; } // Map standard fields - plugin has to process custom fields manually. $data->roleid = $this->get_mappingid('role', $data->roleid); $data->courseid = $courserec->id; if ($this->get_setting_value('enrol_migratetomanual')) { unset($data->sortorder); // Remove useless sortorder from <2.4 backups. if (!enrol_is_enabled('manual')) { $this->set_mapping('enrol', $oldid, 0); return; } if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) { $instance = reset($instances); $this->set_mapping('enrol', $oldid, $instance->id); } else { if ($data->enrol === 'manual') { $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data); } else { $instanceid = $this->plugins['manual']->add_default_instance($courserec); } $this->set_mapping('enrol', $oldid, $instanceid); } } else { if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) { $this->set_mapping('enrol', $oldid, 0); $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, use migration to manual enrolments"; $this->log($message, backup::LOG_WARNING); return; } if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) { // Let's keep the sortorder in old backups. } else { // Prevent problems with colliding sortorders in old backups, // new 2.4 backups do not need sortorder because xml elements are ordered properly. unset($data->sortorder); } // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type. $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid); } } /** * Create user enrolments. * * This has to be called after creation of enrolment instances * and before adding of role assignments. * * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards. * * @param mixed $data * @return void */ public function process_enrolment($data) { global $DB; if (!isset($this->plugins)) { $this->plugins = enrol_get_plugins(true); } $data = (object)$data; // Process only if parent instance have been mapped. if ($enrolid = $this->get_new_parentid('enrol')) { $oldinstancestatus = ENROL_INSTANCE_ENABLED; $oldenrolid = $this->get_old_parentid('enrol'); if (isset($this->originalstatus[$oldenrolid])) { $oldinstancestatus = $this->originalstatus[$oldenrolid]; } if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) { // And only if user is a mapped one. if ($userid = $this->get_mappingid('user', $data->userid)) { if (isset($this->plugins[$instance->enrol])) { $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus); } } } } } } /** * Make sure the user restoring the course can actually access it. */ class restore_fix_restorer_access_step extends restore_execution_step { protected function define_execution() { global $CFG, $DB; if (!$userid = $this->task->get_userid()) { return; } if (empty($CFG->restorernewroleid)) { // Bad luck, no fallback role for restorers specified return; } $courseid = $this->get_courseid(); $context = context_course::instance($courseid); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Current user may access the course (admin, category manager or restored teacher enrolment usually) return; } // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled role_assign($CFG->restorernewroleid, $userid, $context); if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) { // Extra role is enough, yay! return; } // The last chance is to create manual enrol if it does not exist and and try to enrol the current user, // hopefully admin selected suitable $CFG->restorernewroleid ... if (!enrol_is_enabled('manual')) { return; } if (!$enrol = enrol_get_plugin('manual')) { return; } if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) { $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST); $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0)); $enrol->add_instance($course, $fields); } enrol_try_internal_enrol($courseid, $userid); } } /** * This structure steps restores the filters and their configs */ class restore_filters_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active'); $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config'); return $paths; } public function process_active($data) { $data = (object)$data; if (strpos($data->filter, 'filter/') === 0) { $data->filter = substr($data->filter, 7); } else if (strpos($data->filter, '/') !== false) { // Unsupported old filter. return; } if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do return; } filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active); } public function process_config($data) { $data = (object)$data; if (strpos($data->filter, 'filter/') === 0) { $data->filter = substr($data->filter, 7); } else if (strpos($data->filter, '/') !== false) { // Unsupported old filter. return; } if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do return; } filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value); } } /** * This structure steps restores the comments * Note: Cannot use the comments API because defaults to USER->id. * That should change allowing to pass $userid */ class restore_comments_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('comment', '/comments/comment'); return $paths; } public function process_comment($data) { global $DB; $data = (object)$data; // First of all, if the comment has some itemid, ask to the task what to map $mapping = false; if ($data->itemid) { $mapping = $this->task->get_comment_mapping_itemname($data->commentarea); $data->itemid = $this->get_mappingid($mapping, $data->itemid); } // Only restore the comment if has no mapping OR we have found the matching mapping if (!$mapping || $data->itemid) { // Only if user mapping and context $data->userid = $this->get_mappingid('user', $data->userid); if ($data->userid && $this->task->get_contextid()) { $data->contextid = $this->task->get_contextid(); // Only if there is another comment with same context/user/timecreated $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated); if (!$DB->record_exists('comments', $params)) { $DB->insert_record('comments', $data); } } } } } /** * This structure steps restores the badges and their configs */ class restore_badges_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks the following parameters: * * 1. Badges and course badges are enabled on the site. * 2. The course/badges.xml file exists. * 3. All modules are restorable. * 4. All modules are marked for restore. * * @return bool True is safe to execute, false otherwise */ protected function execute_condition() { global $CFG; // First check is badges and course level badges are enabled on this site. if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) { // Disabled, don't restore course badges. return false; } // Check if badges.xml is included in the backup. $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course badges. return false; } // Check we are able to restore all backed up modules. if ($this->task->is_missing_modules()) { return false; } // Finally check all modules within the backup are being restored. if ($this->task->is_excluding_activities()) { return false; } return true; } protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('badge', '/badges/badge'); $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion'); $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter'); $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award'); return $paths; } public function process_badge($data) { global $DB, $CFG; require_once($CFG->libdir . '/badgeslib.php'); $data = (object)$data; $data->usercreated = $this->get_mappingid('user', $data->usercreated); if (empty($data->usercreated)) { $data->usercreated = $this->task->get_userid(); } $data->usermodified = $this->get_mappingid('user', $data->usermodified); if (empty($data->usermodified)) { $data->usermodified = $this->task->get_userid(); } // We'll restore the badge image. $restorefiles = true; $courseid = $this->get_courseid(); $params = array( 'name' => $data->name, 'description' => $data->description, 'timecreated' => $this->apply_date_offset($data->timecreated), 'timemodified' => $this->apply_date_offset($data->timemodified), 'usercreated' => $data->usercreated, 'usermodified' => $data->usermodified, 'issuername' => $data->issuername, 'issuerurl' => $data->issuerurl, 'issuercontact' => $data->issuercontact, 'expiredate' => $this->apply_date_offset($data->expiredate), 'expireperiod' => $data->expireperiod, 'type' => BADGE_TYPE_COURSE, 'courseid' => $courseid, 'message' => $data->message, 'messagesubject' => $data->messagesubject, 'attachment' => $data->attachment, 'notification' => $data->notification, 'status' => BADGE_STATUS_INACTIVE, 'nextcron' => $this->apply_date_offset($data->nextcron) ); $newid = $DB->insert_record('badge', $params); $this->set_mapping('badge', $data->id, $newid, $restorefiles); } public function process_criterion($data) { global $DB; $data = (object)$data; $params = array( 'badgeid' => $this->get_new_parentid('badge'), 'criteriatype' => $data->criteriatype, 'method' => $data->method ); $newid = $DB->insert_record('badge_criteria', $params); $this->set_mapping('criterion', $data->id, $newid); } public function process_parameter($data) { global $DB, $CFG; require_once($CFG->libdir . '/badgeslib.php'); $data = (object)$data; $criteriaid = $this->get_new_parentid('criterion'); // Parameter array that will go to database. $params = array(); $params['critid'] = $criteriaid; $oldparam = explode('_', $data->name); if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) { $module = $this->get_mappingid('course_module', $oldparam[1]); $params['name'] = $oldparam[0] . '_' . $module; $params['value'] = $oldparam[0] == 'module' ? $module : $data->value; } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) { $params['name'] = $oldparam[0] . '_' . $this->get_courseid(); $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value; } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) { $role = $this->get_mappingid('role', $data->value); if (!empty($role)) { $params['name'] = 'role_' . $role; $params['value'] = $role; } else { return; } } if (!$DB->record_exists('badge_criteria_param', $params)) { $DB->insert_record('badge_criteria_param', $params); } } public function process_manual_award($data) { global $DB; $data = (object)$data; $role = $this->get_mappingid('role', $data->issuerrole); if (!empty($role)) { $award = array( 'badgeid' => $this->get_new_parentid('badge'), 'recipientid' => $this->get_mappingid('user', $data->recipientid), 'issuerid' => $this->get_mappingid('user', $data->issuerid), 'issuerrole' => $role, 'datemet' => $this->apply_date_offset($data->datemet) ); // Skip the manual award if recipient or issuer can not be mapped to. if (empty($award['recipientid']) || empty($award['issuerid'])) { return; } $DB->insert_record('badge_manual_award', $award); } } protected function after_execute() { // Add related files. $this->add_related_files('badges', 'badgeimage', 'badge'); } } /** * This structure steps restores the calendar events */ class restore_calendarevents_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('calendarevents', '/events/event'); return $paths; } public function process_calendarevents($data) { global $DB, $SITE, $USER; $data = (object)$data; $oldid = $data->id; $restorefiles = true; // We'll restore the files // Find the userid and the groupid associated with the event. $data->userid = $this->get_mappingid('user', $data->userid); if ($data->userid === false) { // Blank user ID means that we are dealing with module generated events such as quiz starting times. // Use the current user ID for these events. $data->userid = $USER->id; } if (!empty($data->groupid)) { $data->groupid = $this->get_mappingid('group', $data->groupid); if ($data->groupid === false) { return; } } // Handle events with empty eventtype //MDL-32827 if(empty($data->eventtype)) { if ($data->courseid == $SITE->id) { // Site event $data->eventtype = "site"; } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) { // Course assingment event $data->eventtype = "due"; } else if ($data->courseid != 0 && $data->groupid == 0) { // Course event $data->eventtype = "course"; } else if ($data->groupid) { // Group event $data->eventtype = "group"; } else if ($data->userid) { // User event $data->eventtype = "user"; } else { return; } } $params = array( 'name' => $data->name, 'description' => $data->description, 'format' => $data->format, 'courseid' => $this->get_courseid(), 'groupid' => $data->groupid, 'userid' => $data->userid, 'repeatid' => $data->repeatid, 'modulename' => $data->modulename, 'eventtype' => $data->eventtype, 'timestart' => $this->apply_date_offset($data->timestart), 'timeduration' => $data->timeduration, 'visible' => $data->visible, 'uuid' => $data->uuid, 'sequence' => $data->sequence, 'timemodified' => $this->apply_date_offset($data->timemodified)); if ($this->name == 'activity_calendar') { $params['instance'] = $this->task->get_activityid(); } else { $params['instance'] = 0; } $sql = "SELECT id FROM {event} WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . " AND courseid = ? AND repeatid = ? AND modulename = ? AND timestart = ? AND timeduration = ? AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255); $arg = array ($params['name'], $params['courseid'], $params['repeatid'], $params['modulename'], $params['timestart'], $params['timeduration'], $params['description']); $result = $DB->record_exists_sql($sql, $arg); if (empty($result)) { $newitemid = $DB->insert_record('event', $params); $this->set_mapping('event', $oldid, $newitemid); $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles); } } protected function after_execute() { // Add related files $this->add_related_files('calendar', 'event_description', 'event_description'); } } class restore_course_completion_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks parameters that are not immediate settings to ensure * that the enviroment is suitable for the restore of course completion info. * * This function checks the following four parameters: * * 1. Course completion is enabled on the site * 2. The backup includes course completion information * 3. All modules are restorable * 4. All modules are marked for restore. * * @return bool True is safe to execute, false otherwise */ protected function execute_condition() { global $CFG; // First check course completion is enabled on this site if (empty($CFG->enablecompletion)) { // Disabled, don't restore course completion return false; } // No course completion on the front page. if ($this->get_courseid() == SITEID) { return false; } // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course completion return false; } // Check we are able to restore all backed up modules if ($this->task->is_missing_modules()) { return false; } // Finally check all modules within the backup are being restored. if ($this->task->is_excluding_activities()) { return false; } return true; } /** * Define the course completion structure * * @return array Array of restore_path_element */ protected function define_structure() { // To know if we are including user completion info $userinfo = $this->get_setting_value('userscompletion'); $paths = array(); $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria'); $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd'); if ($userinfo) { $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl'); $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions'); } return $paths; } /** * Process course completion criteria * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_criteria($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); // Apply the date offset to the time end field $data->timeend = $this->apply_date_offset($data->timeend); // Map the role from the criteria if (!empty($data->role)) { $data->role = $this->get_mappingid('role', $data->role); } $skipcriteria = false; // If the completion criteria is for a module we need to map the module instance // to the new module id. if (!empty($data->moduleinstance) && !empty($data->module)) { $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance); if (empty($data->moduleinstance)) { $skipcriteria = true; } } else { $data->module = null; $data->moduleinstance = null; } // We backup the course shortname rather than the ID so that we can match back to the course if (!empty($data->courseinstanceshortname)) { $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname)); if (!$courseinstanceid) { $skipcriteria = true; } } else { $courseinstanceid = null; } $data->courseinstance = $courseinstanceid; if (!$skipcriteria) { $params = array( 'course' => $data->course, 'criteriatype' => $data->criteriatype, 'enrolperiod' => $data->enrolperiod, 'courseinstance' => $data->courseinstance, 'module' => $data->module, 'moduleinstance' => $data->moduleinstance, 'timeend' => $data->timeend, 'gradepass' => $data->gradepass, 'role' => $data->role ); $newid = $DB->insert_record('course_completion_criteria', $params); $this->set_mapping('course_completion_criteria', $data->id, $newid); } } /** * Processes course compltion criteria complete records * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_crit_compl($data) { global $DB; $data = (object)$data; // This may be empty if criteria could not be restored $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid); $data->course = $this->get_courseid(); $data->userid = $this->get_mappingid('user', $data->userid); if (!empty($data->criteriaid) && !empty($data->userid)) { $params = array( 'userid' => $data->userid, 'course' => $data->course, 'criteriaid' => $data->criteriaid, 'timecompleted' => $this->apply_date_offset($data->timecompleted) ); if (isset($data->gradefinal)) { $params['gradefinal'] = $data->gradefinal; } if (isset($data->unenroled)) { $params['unenroled'] = $data->unenroled; } $DB->insert_record('course_completion_crit_compl', $params); } } /** * Process course completions * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completions($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); $data->userid = $this->get_mappingid('user', $data->userid); if (!empty($data->userid)) { $params = array( 'userid' => $data->userid, 'course' => $data->course, 'timeenrolled' => $this->apply_date_offset($data->timeenrolled), 'timestarted' => $this->apply_date_offset($data->timestarted), 'timecompleted' => $this->apply_date_offset($data->timecompleted), 'reaggregate' => $data->reaggregate ); $existing = $DB->get_record('course_completions', array( 'userid' => $data->userid, 'course' => $data->course )); // MDL-46651 - If cron writes out a new record before we get to it // then we should replace it with the Truth data from the backup. // This may be obsolete after MDL-48518 is resolved if ($existing) { $params['id'] = $existing->id; $DB->update_record('course_completions', $params); } else { $DB->insert_record('course_completions', $params); } } } /** * Process course completion aggregate methods * * @global moodle_database $DB * @param stdClass $data */ public function process_course_completion_aggr_methd($data) { global $DB; $data = (object)$data; $data->course = $this->get_courseid(); // Only create the course_completion_aggr_methd records if // the target course has not them defined. MDL-28180 if (!$DB->record_exists('course_completion_aggr_methd', array( 'course' => $data->course, 'criteriatype' => $data->criteriatype))) { $params = array( 'course' => $data->course, 'criteriatype' => $data->criteriatype, 'method' => $data->method, 'value' => $data->value, ); $DB->insert_record('course_completion_aggr_methd', $params); } } } /** * This structure step restores course logs (cmid = 0), delegating * the hard work to the corresponding {@link restore_logs_processor} passing the * collection of {@link restore_log_rule} rules to be observed as they are defined * by the task. Note this is only executed based in the 'logs' setting. * * NOTE: This is executed by final task, to have all the activities already restored * * NOTE: Not all course logs are being restored. For now only 'course' and 'user' * records are. There are others like 'calendar' and 'upload' that will be handled * later. * * NOTE: All the missing actions (not able to be restored) are sent to logs for * debugging purposes */ class restore_course_logs_structure_step extends restore_structure_step { /** * Conditionally decide if this step should be executed. * * This function checks the following parameter: * * 1. the course/logs.xml file exists * * @return bool true is safe to execute, false otherwise */ protected function execute_condition() { // Check it is included in the backup $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { // Not found, can't restore course logs return false; } return true; } protected function define_structure() { $paths = array(); // Simple, one plain level of information contains them $paths[] = new restore_path_element('log', '/logs/log'); return $paths; } protected function process_log($data) { global $DB; $data = (object)($data); $data->time = $this->apply_date_offset($data->time); $data->userid = $this->get_mappingid('user', $data->userid); $data->course = $this->get_courseid(); $data->cmid = 0; // For any reason user wasn't remapped ok, stop processing this if (empty($data->userid)) { return; } // Everything ready, let's delegate to the restore_logs_processor // Set some fixed values that will save tons of DB requests $values = array( 'course' => $this->get_courseid()); // Get instance and process log record $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); // If we have data, insert it, else something went wrong in the restore_logs_processor if ($data) { if (empty($data->url)) { $data->url = ''; } if (empty($data->info)) { $data->info = ''; } // Store the data in the legacy log table if we are still using it. $manager = get_log_manager(); if (method_exists($manager, 'legacy_add_to_log')) { $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, $data->info, $data->cmid, $data->userid); } } } } /** * This structure step restores activity logs, extending {@link restore_course_logs_structure_step} * sharing its same structure but modifying the way records are handled */ class restore_activity_logs_structure_step extends restore_course_logs_structure_step { protected function process_log($data) { global $DB; $data = (object)($data); $data->time = $this->apply_date_offset($data->time); $data->userid = $this->get_mappingid('user', $data->userid); $data->course = $this->get_courseid(); $data->cmid = $this->task->get_moduleid(); // For any reason user wasn't remapped ok, stop processing this if (empty($data->userid)) { return; } // Everything ready, let's delegate to the restore_logs_processor // Set some fixed values that will save tons of DB requests $values = array( 'course' => $this->get_courseid(), 'course_module' => $this->task->get_moduleid(), $this->task->get_modulename() => $this->task->get_activityid()); // Get instance and process log record $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data); // If we have data, insert it, else something went wrong in the restore_logs_processor if ($data) { if (empty($data->url)) { $data->url = ''; } if (empty($data->info)) { $data->info = ''; } // Store the data in the legacy log table if we are still using it. $manager = get_log_manager(); if (method_exists($manager, 'legacy_add_to_log')) { $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url, $data->info, $data->cmid, $data->userid); } } } } /** * Defines the restore step for advanced grading methods attached to the activity module */ class restore_activity_grading_structure_step extends restore_structure_step { /** * This step is executed only if the grading file is present */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } return true; } /** * Declares paths in the grading.xml file we are interested in */ protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); $area = new restore_path_element('grading_area', '/areas/area'); $paths[] = $area; // attach local plugin stucture to $area element $this->add_plugin_structure('local', $area); $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition'); $paths[] = $definition; $this->add_plugin_structure('gradingform', $definition); // attach local plugin stucture to $definition element $this->add_plugin_structure('local', $definition); if ($userinfo) { $instance = new restore_path_element('grading_instance', '/areas/area/definitions/definition/instances/instance'); $paths[] = $instance; $this->add_plugin_structure('gradingform', $instance); // attach local plugin stucture to $intance element $this->add_plugin_structure('local', $instance); } return $paths; } /** * Processes one grading area element * * @param array $data element data */ protected function process_grading_area($data) { global $DB; $task = $this->get_task(); $data = (object)$data; $oldid = $data->id; $data->component = 'mod_'.$task->get_modulename(); $data->contextid = $task->get_contextid(); $newid = $DB->insert_record('grading_areas', $data); $this->set_mapping('grading_area', $oldid, $newid); } /** * Processes one grading definition element * * @param array $data element data */ protected function process_grading_definition($data) { global $DB; $task = $this->get_task(); $data = (object)$data; $oldid = $data->id; $data->areaid = $this->get_new_parentid('grading_area'); $data->copiedfromid = null; $data->timecreated = time(); $data->usercreated = $task->get_userid(); $data->timemodified = $data->timecreated; $data->usermodified = $data->usercreated; $newid = $DB->insert_record('grading_definitions', $data); $this->set_mapping('grading_definition', $oldid, $newid, true); } /** * Processes one grading form instance element * * @param array $data element data */ protected function process_grading_instance($data) { global $DB; $data = (object)$data; // new form definition id $newformid = $this->get_new_parentid('grading_definition'); // get the name of the area we are restoring to $sql = "SELECT ga.areaname FROM {grading_definitions} gd JOIN {grading_areas} ga ON gd.areaid = ga.id WHERE gd.id = ?"; $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST); // get the mapped itemid - the activity module is expected to define the mappings // for each gradable area $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid); $oldid = $data->id; $data->definitionid = $newformid; $data->raterid = $this->get_mappingid('user', $data->raterid); $data->itemid = $newitemid; $newid = $DB->insert_record('grading_instances', $data); $this->set_mapping('grading_instance', $oldid, $newid); } /** * Final operations when the database records are inserted */ protected function after_execute() { // Add files embedded into the definition description $this->add_related_files('grading', 'description', 'grading_definition'); } } /** * This structure step restores the grade items associated with one activity * All the grade items are made child of the "course" grade item but the original * categoryid is saved as parentitemid in the backup_ids table, so, when restoring * the complete gradebook (categories and calculations), that information is * available there */ class restore_activity_grades_structure_step extends restore_structure_step { /** * No grades in front page. * @return bool */ protected function execute_condition() { return ($this->get_courseid() != SITEID); } protected function define_structure() { $paths = array(); $userinfo = $this->get_setting_value('userinfo'); $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item'); $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter'); if ($userinfo) { $paths[] = new restore_path_element('grade_grade', '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade'); } return $paths; } protected function process_grade_item($data) { global $DB; $data = (object)($data); $oldid = $data->id; // We'll need these later $oldparentid = $data->categoryid; $courseid = $this->get_courseid(); // make sure top course category exists, all grade items will be associated // to it. Later, if restoring the whole gradebook, categories will be introduced $coursecat = grade_category::fetch_course_category($courseid); $coursecatid = $coursecat->id; // Get the categoryid to be used $idnumber = null; if (!empty($data->idnumber)) { // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop) // so the best is to keep the ones already in the gradebook // Potential problem: duplicates if same items are restored more than once. :-( // This needs to be fixed in some way (outcomes & activities with multiple items) // $data->idnumber = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber; // In any case, verify always for uniqueness $sql = "SELECT cm.id FROM {course_modules} cm WHERE cm.course = :courseid AND cm.idnumber = :idnumber AND cm.id <> :cmid"; $params = array( 'courseid' => $courseid, 'idnumber' => $data->idnumber, 'cmid' => $this->task->get_moduleid() ); if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) { $idnumber = $data->idnumber; } } unset($data->id); $data->categoryid = $coursecatid; $data->courseid = $this->get_courseid(); $data->iteminstance = $this->task->get_activityid(); $data->idnumber = $idnumber; $data->scaleid = $this->get_mappingid('scale', $data->scaleid); $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->timemodified = $this->apply_date_offset($data->timemodified); $gradeitem = new grade_item($data, false); $gradeitem->insert('restore'); //sortorder is automatically assigned when inserting. Re-instate the previous sortorder $gradeitem->sortorder = $data->sortorder; $gradeitem->update('restore'); // Set mapping, saving the original category id into parentitemid // gradebook restore (final task) will need it to reorganise items $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid); } protected function process_grade_grade($data) { $data = (object)($data); $olduserid = $data->userid; $oldid = $data->id; unset($data->id); $data->itemid = $this->get_new_parentid('grade_item'); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); // TODO: Ask, all the rest of locktime/exported... work with time... to be rolled? $data->overridden = $this->apply_date_offset($data->overridden); $grade = new grade_grade($data, false); $grade->insert('restore'); $this->set_mapping('grade_grades', $oldid, $grade->id); } else { debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"); } } /** * process activity grade_letters. Note that, while these are possible, * because grade_letters are contextid based, in practice, only course * context letters can be defined. So we keep here this method knowing * it won't be executed ever. gradebook restore will restore course letters. */ protected function process_grade_letter($data) { global $DB; $data['contextid'] = $this->task->get_contextid(); $gradeletter = (object)$data; // Check if it exists before adding it unset($data['id']); if (!$DB->record_exists('grade_letters', $data)) { $newitemid = $DB->insert_record('grade_letters', $gradeletter); } // no need to save any grade_letter mapping } public function after_restore() { // Fix grade item's sortorder after restore, as it might have duplicates. $courseid = $this->get_task()->get_courseid(); grade_item::fix_duplicate_sortorder($courseid); } } /** * Step in charge of restoring the grade history of an activity. * * This step is added to the task regardless of the setting 'grade_histories'. * The reason is to allow for a more flexible step in case the logic needs to be * split accross different settings to control the history of items and/or grades. */ class restore_activity_grade_history_structure_step extends restore_structure_step { /** * This step is executed only if the grade history file is present. */ protected function execute_condition() { if ($this->get_courseid() == SITEID) { return false; } $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } return true; } protected function define_structure() { $paths = array(); // Settings to use. $userinfo = $this->get_setting_value('userinfo'); $history = $this->get_setting_value('grade_histories'); if ($userinfo && $history) { $paths[] = new restore_path_element('grade_grade', '/grade_history/grade_grades/grade_grade'); } return $paths; } protected function process_grade_grade($data) { global $DB; $data = (object) $data; $olduserid = $data->userid; unset($data->id); $data->userid = $this->get_mappingid('user', $data->userid, null); if (!empty($data->userid)) { // Do not apply the date offsets as this is history. $data->itemid = $this->get_mappingid('grade_item', $data->itemid); $data->oldid = $this->get_mappingid('grade_grades', $data->oldid); $data->usermodified = $this->get_mappingid('user', $data->usermodified, null); $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid); $DB->insert_record('grade_grades_history', $data); } else { $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'"; $this->log($message, backup::LOG_DEBUG); } } } /** * This structure steps restores one instance + positions of one block * Note: Positions corresponding to one existing context are restored * here, but all the ones having unknown contexts are sent to backup_ids * for a later chance to be restored at the end (final task) */ class restore_block_instance_structure_step extends restore_structure_step { protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position'); return $paths; } public function process_block($data) { global $DB, $CFG; $data = (object)$data; // Handy $oldcontextid = $data->contextid; $oldid = $data->id; $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array(); // Look for the parent contextid if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) { throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid); } // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple() // If there is already one block of that type in the parent context // and the block is not multiple, stop processing // Use blockslib loader / method executor if (!$bi = block_instance($data->blockname)) { return false; } if (!$bi->instance_allow_multiple()) { // The block cannot be added twice, so we will check if the same block is already being // displayed on the same page. For this, rather than mocking a page and using the block_manager // we use a similar query to the one in block_manager::load_blocks(), this will give us // a very good idea of the blocks already displayed in the context. $params = array( 'blockname' => $data->blockname ); // Context matching test. $context = context::instance_by_id($data->parentcontextid); $contextsql = 'bi.parentcontextid = :contextid'; $params['contextid'] = $context->id; $parentcontextids = $context->get_parent_context_ids(); if ($parentcontextids) { list($parentcontextsql, $parentcontextparams) = $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED); $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))"; $params = array_merge($params, $parentcontextparams); } // Page type pattern test. $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern); list($pagetypepatternsql, $pagetypepatternparams) = $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED); $params = array_merge($params, $pagetypepatternparams); // Sub page pattern test. $subpagepatternsql = 'bi.subpagepattern IS NULL'; if ($data->subpagepattern !== null) { $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)"; $params['subpagepattern'] = $data->subpagepattern; } $exists = $DB->record_exists_sql("SELECT bi.id FROM {block_instances} bi JOIN {block} b ON b.name = bi.blockname WHERE bi.blockname = :blockname AND $contextsql AND bi.pagetypepattern $pagetypepatternsql AND $subpagepatternsql", $params); if ($exists) { // There is at least one very similar block visible on the page where we // are trying to restore the block. In these circumstances the block API // would not allow the user to add another instance of the block, so we // apply the same rule here. return false; } } // If there is already one block of that type in the parent context // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata // stop processing $params = array( 'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion); if ($birecs = $DB->get_records('block_instances', $params)) { foreach($birecs as $birec) { if ($birec->configdata == $data->configdata) { return false; } } } // Set task old contextid, blockid and blockname once we know them $this->task->set_old_contextid($oldcontextid); $this->task->set_old_blockid($oldid); $this->task->set_blockname($data->blockname); // Let's look for anything within configdata neededing processing // (nulls and uses of legacy file.php) if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) { $configdata = (array)unserialize(base64_decode($data->configdata)); foreach ($configdata as $attribute => $value) { if (in_array($attribute, $attrstotransform)) { $configdata[$attribute] = $this->contentprocessor->process_cdata($value); } } $data->configdata = base64_encode(serialize((object)$configdata)); } // Create the block instance $newitemid = $DB->insert_record('block_instances', $data); // Save the mapping (with restorefiles support) $this->set_mapping('block_instance', $oldid, $newitemid, true); // Create the block context $newcontextid = context_block::instance($newitemid)->id; // Save the block contexts mapping and sent it to task $this->set_mapping('context', $oldcontextid, $newcontextid); $this->task->set_contextid($newcontextid); $this->task->set_blockid($newitemid); // Restore block fileareas if declared $component = 'block_' . $this->task->get_blockname(); foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed $this->add_related_files($component, $filearea, null); } // Process block positions, creating them or accumulating for final step foreach($positions as $position) { $position = (object)$position; $position->blockinstanceid = $newitemid; // The instance is always the restored one // If position is for one already mapped (known) contextid // process it now, creating the position if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) { $position->contextid = $newpositionctxid; // Create the block position $DB->insert_record('block_positions', $position); // The position belongs to an unknown context, send it to backup_ids // to process them as part of the final steps of restore. We send the // whole $position object there, hence use the low level method. } else { restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position); } } } } /** * Structure step to restore common course_module information * * This step will process the module.xml file for one activity, in order to restore * the corresponding information to the course_modules table, skipping various bits * of information based on CFG settings (groupings, completion...) in order to fullfill * all the reqs to be able to create the context to be used by all the rest of steps * in the activity restore task */ class restore_module_structure_step extends restore_structure_step { protected function define_structure() { global $CFG; $paths = array(); $module = new restore_path_element('module', '/module'); $paths[] = $module; if ($CFG->enableavailability) { $paths[] = new restore_path_element('availability', '/module/availability_info/availability'); $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field'); } // Apply for 'format' plugins optional paths at module level $this->add_plugin_structure('format', $module); // Apply for 'plagiarism' plugins optional paths at module level $this->add_plugin_structure('plagiarism', $module); // Apply for 'local' plugins optional paths at module level $this->add_plugin_structure('local', $module); return $paths; } protected function process_module($data) { global $CFG, $DB; $data = (object)$data; $oldid = $data->id; $this->task->set_old_moduleversion($data->version); $data->course = $this->task->get_courseid(); $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename)); // Map section (first try by course_section mapping match. Useful in course and section restores) $data->section = $this->get_mappingid('course_section', $data->sectionid); if (!$data->section) { // mapping failed, try to get section by sectionnumber matching $params = array( 'course' => $this->get_courseid(), 'section' => $data->sectionnumber); $data->section = $DB->get_field('course_sections', 'id', $params); } if (!$data->section) { // sectionnumber failed, try to get first section in course $params = array( 'course' => $this->get_courseid()); $data->section = $DB->get_field('course_sections', 'MIN(id)', $params); } if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1 $sectionrec = array( 'course' => $this->get_courseid(), 'section' => 0); $DB->insert_record('course_sections', $sectionrec); // section 0 $sectionrec = array( 'course' => $this->get_courseid(), 'section' => 1); $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1 } $data->groupingid= $this->get_mappingid('grouping', $data->groupingid); // grouping if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) { // idnumber uniqueness $data->idnumber = ''; } if (empty($CFG->enablecompletion)) { // completion $data->completion = 0; $data->completiongradeitemnumber = null; $data->completionview = 0; $data->completionexpected = 0; } else { $data->completionexpected = $this->apply_date_offset($data->completionexpected); } if (empty($CFG->enableavailability)) { $data->availability = null; } // Backups that did not include showdescription, set it to default 0 // (this is not totally necessary as it has a db default, but just to // be explicit). if (!isset($data->showdescription)) { $data->showdescription = 0; } $data->instance = 0; // Set to 0 for now, going to create it soon (next step) if (empty($data->availability)) { // If there are legacy availablility data fields (and no new format data), // convert the old fields. $data->availability = \core_availability\info::convert_legacy_fields( $data, false); } else if (!empty($data->groupmembersonly)) { // There is current availability data, but it still has groupmembersonly // as well (2.7 backups), convert just that part. require_once($CFG->dirroot . '/lib/db/upgradelib.php'); $data->availability = upgrade_group_members_only($data->groupingid, $data->availability); } // course_module record ready, insert it $newitemid = $DB->insert_record('course_modules', $data); // save mapping $this->set_mapping('course_module', $oldid, $newitemid); // set the new course_module id in the task $this->task->set_moduleid($newitemid); // we can now create the context safely $ctxid = context_module::instance($newitemid)->id; // set the new context id in the task $this->task->set_contextid($ctxid); // update sequence field in course_section if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) { $sequence .= ',' . $newitemid; } else { $sequence = $newitemid; } $DB->set_field('course_sections', 'sequence', $sequence, array('id' => $data->section)); // If there is the legacy showavailability data, store this for later use. // (This data is not present when restoring 'new' backups.) if (isset($data->showavailability)) { // Cache the showavailability flag using the backup_ids data field. restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_showavailability', $newitemid, 0, null, (object)array('showavailability' => $data->showavailability)); } } /** * Process the legacy availability table record. This table does not exist * in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ protected function process_availability($data) { $data = (object)$data; // Simply going to store the whole availability record now, we'll process // all them later in the final task (once all activities have been restored) // Let's call the low level one to be able to store the whole object $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data); } /** * Process the legacy availability fields table record. This table does not * exist in Moodle 2.7+ but we still support restore. * * @param stdClass $data Record data */ protected function process_availability_field($data) { global $DB; $data = (object)$data; // Mark it is as passed by default $passed = true; $customfieldid = null; // If a customfield has been used in order to pass we must be able to match an existing // customfield by name (data->customfield) and type (data->customfieldtype) if (!empty($data->customfield) xor !empty($data->customfieldtype)) { // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both. // If one is null but the other isn't something clearly went wrong and we'll skip this condition. $passed = false; } else if (!empty($data->customfield)) { $params = array('shortname' => $data->customfield, 'datatype' => $data->customfieldtype); $customfieldid = $DB->get_field('user_info_field', 'id', $params); $passed = ($customfieldid !== false); } if ($passed) { // Create the object to insert into the database $availfield = new stdClass(); $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid $availfield->userfield = $data->userfield; $availfield->customfieldid = $customfieldid; $availfield->operator = $data->operator; $availfield->value = $data->value; // Get showavailability option. $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'module_showavailability', $availfield->coursemoduleid); if (!$showrec) { // Should not happen. throw new coding_exception('No matching showavailability record'); } $show = $showrec->info->showavailability; // The $availfieldobject is now in the format used in the old // system. Interpret this and convert to new system. $currentvalue = $DB->get_field('course_modules', 'availability', array('id' => $availfield->coursemoduleid), MUST_EXIST); $newvalue = \core_availability\info::add_legacy_availability_field_condition( $currentvalue, $availfield, $show); $DB->set_field('course_modules', 'availability', $newvalue, array('id' => $availfield->coursemoduleid)); } } } /** * Structure step that will process the user activity completion * information if all these conditions are met: * - Target site has completion enabled ($CFG->enablecompletion) * - Activity includes completion info (file_exists) */ class restore_userscompletion_structure_step extends restore_structure_step { /** * To conditionally decide if this step must be executed * Note the "settings" conditions are evaluated in the * corresponding task. Here we check for other conditions * not being restore settings (files, site settings...) */ protected function execute_condition() { global $CFG; // Completion disabled in this site, don't execute if (empty($CFG->enablecompletion)) { return false; } // No completion on the front page. if ($this->get_courseid() == SITEID) { return false; } // No user completion info found, don't execute $fullpath = $this->task->get_taskbasepath(); $fullpath = rtrim($fullpath, '/') . '/' . $this->filename; if (!file_exists($fullpath)) { return false; } // Arrived here, execute the step return true; } protected function define_structure() { $paths = array(); $paths[] = new restore_path_element('completion', '/completions/completion'); return $paths; } protected function process_completion($data) { global $DB; $data = (object)$data; $data->coursemoduleid = $this->task->get_moduleid(); $data->userid = $this->get_mappingid('user', $data->userid); $data->timemodified = $this->apply_date_offset($data->timemodified); // Find the existing record $existing = $DB->get_record('course_modules_completion', array( 'coursemoduleid' => $data->coursemoduleid, 'userid' => $data->userid), 'id, timemodified'); // Check we didn't already insert one for this cmid and userid // (there aren't supposed to be duplicates in that field, but // it was possible until MDL-28021 was fixed). if ($existing) { // Update it to these new values, but only if the time is newer if ($existing->timemodified < $data->timemodified) { $data->id = $existing->id; $DB->update_record('course_modules_completion', $data); } } else { // Normal entry where it doesn't exist already $DB->insert_record('course_modules_completion', $data); } } } /** * Abstract structure step, parent of all the activity structure steps. Used to suuport * the main <activity ...> tag and process it. Also provides subplugin support for * activities. */ abstract class restore_activity_structure_step extends restore_structure_step { protected function add_subplugin_structure($subplugintype, $element) { global $CFG; // Check the requested subplugintype is a valid one $subpluginsfile = $CFG->dirroot . '/mod/' . $this->task->get_modulename() . '/db/subplugins.php'; if (!file_exists($subpluginsfile)) { throw new restore_step_exception('activity_missing_subplugins_php_file', $this->task->get_modulename()); } include($subpluginsfile); if (!array_key_exists($subplugintype, $subplugins)) { throw new restore_step_exception('incorrect_subplugin_type', $subplugintype); } // Get all the restore path elements, looking across all the subplugin dirs $subpluginsdirs = core_component::get_plugin_list($subplugintype); foreach ($subpluginsdirs as $name => $subpluginsdir) { $classname = 'restore_' . $subplugintype . '_' . $name . '_subplugin'; $restorefile = $subpluginsdir . '/backup/moodle2/' . $classname . '.class.php'; if (file_exists($restorefile)) { require_once($restorefile); $restoresubplugin = new $classname($subplugintype, $name, $this); // Add subplugin paths to the step $this->prepare_pathelements($restoresubplugin->define_subplugin_structure($element)); } } } /** * As far as activity restore steps are implementing restore_subplugin stuff, they need to * have the parent task available for wrapping purposes (get course/context....) * @return restore_task */ public function get_task() { return $this->task; } /** * Adds support for the 'activity' path that is common to all the activities * and will be processed globally here */ protected function prepare_activity_structure($paths) { $paths[] = new restore_path_element('activity', '/activity'); return $paths; } /** * Process the activity path, informing the task about various ids, needed later */ protected function process_activity($data) { $data = (object)$data; $this->task->set_old_contextid($data->contextid); // Save old contextid in task $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping $this->task->set_old_activityid($data->id); // Save old activityid in task } /** * This must be invoked immediately after creating the "module" activity record (forum, choice...) * and will adjust the new activity id (the instance) in various places */ protected function apply_activity_instance($newitemid) { global $DB; $this->task->set_activityid($newitemid); // Save activity id in task // Apply the id to course_sections->instanceid $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid())); // Do the mapping for modulename, preparing it for files by oldcontext $modulename = $this->task->get_modulename(); $oldid = $this->task->get_old_activityid(); $this->set_mapping($modulename, $oldid, $newitemid, true); } } /** * Structure step in charge of creating/mapping all the qcats and qs * by parsing the questions.xml file and checking it against the * results calculated by {@link restore_process_categories_and_questions} * and stored in backup_ids_temp */ class restore_create_categories_and_questions extends restore_structure_step { /** @var array $cachecategory store a question category */ protected $cachedcategory = null; protected function define_structure() { $category = new restore_path_element('question_category', '/question_categories/question_category'); $question = new restore_path_element('question', '/question_categories/question_category/questions/question'); $hint = new restore_path_element('question_hint', '/question_categories/question_category/questions/question/question_hints/question_hint'); $tag = new restore_path_element('tag','/question_categories/question_category/questions/question/tags/tag'); // Apply for 'qtype' plugins optional paths at question level $this->add_plugin_structure('qtype', $question); // Apply for 'local' plugins optional paths at question level $this->add_plugin_structure('local', $question); return array($category, $question, $hint, $tag); } protected function process_question_category($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Check we have one mapping for this category if (!$mapping = $this->get_mapping('question_category', $oldid)) { return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped } // Check we have to create the category (newitemid = 0) if ($mapping->newitemid) { return; // newitemid != 0, this category is going to be mapped. Nothing to do } // Arrived here, newitemid = 0, we need to create the category // we'll do it at parentitemid context, but for CONTEXT_MODULE // categories, that will be created at CONTEXT_COURSE and moved // to module context later when the activity is created if ($mapping->info->contextlevel == CONTEXT_MODULE) { $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid()); } $data->contextid = $mapping->parentitemid; // Let's create the question_category and save mapping $newitemid = $DB->insert_record('question_categories', $data); $this->set_mapping('question_category', $oldid, $newitemid); // Also annotate them as question_category_created, we need // that later when remapping parents $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid); } protected function process_question($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Check we have one mapping for this question if (!$questionmapping = $this->get_mapping('question', $oldid)) { return; // No mapping = this question doesn't need to be created/mapped } // Get the mapped category (cannot use get_new_parentid() because not // all the categories have been created, so it is not always available // Instead we get the mapping for the question->parentitemid because // we have loaded qcatids there for all parsed questions $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid); // In the past, there were some very sloppy values of penalty. Fix them. if ($data->penalty >= 0.33 && $data->penalty <= 0.34) { $data->penalty = 0.3333333; } if ($data->penalty >= 0.66 && $data->penalty <= 0.67) { $data->penalty = 0.6666667; } if ($data->penalty >= 1) { $data->penalty = 1; } $userid = $this->get_mappingid('user', $data->createdby); $data->createdby = $userid ? $userid : $this->task->get_userid(); $userid = $this->get_mappingid('user', $data->modifiedby); $data->modifiedby = $userid ? $userid : $this->task->get_userid(); // With newitemid = 0, let's create the question if (!$questionmapping->newitemid) { $newitemid = $DB->insert_record('question', $data); $this->set_mapping('question', $oldid, $newitemid); // Also annotate them as question_created, we need // that later when remapping parents (keeping the old categoryid as parentid) $this->set_mapping('question_created', $oldid, $newitemid, false, null, $questionmapping->parentitemid); } else { // By performing this set_mapping() we make get_old/new_parentid() to work for all the // children elements of the 'question' one (so qtype plugins will know the question they belong to) $this->set_mapping('question', $oldid, $questionmapping->newitemid); } // Note, we don't restore any question files yet // as far as the CONTEXT_MODULE categories still // haven't their contexts to be restored to // The {@link restore_create_question_files}, executed in the final step // step will be in charge of restoring all the question files } protected function process_question_hint($data) { global $DB; $data = (object)$data; $oldid = $data->id; // Detect if the question is created or mapped $oldquestionid = $this->get_old_parentid('question'); $newquestionid = $this->get_new_parentid('question'); $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false; // If the question has been created by restore, we need to create its question_answers too if ($questioncreated) { // Adjust some columns $data->questionid = $newquestionid; // Insert record $newitemid = $DB->insert_record('question_hints', $data); // The question existed, we need to map the existing question_hints } else { // Look in question_hints by hint text matching $sql = 'SELECT id FROM {question_hints} WHERE questionid = ? AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255); $params = array($newquestionid, $data->hint); $newitemid = $DB->get_field_sql($sql, $params); // Not able to find the hint, let's try cleaning the hint text // of all the question's hints in DB as slower fallback. MDL-33863. if (!$newitemid) { $potentialhints = $DB->get_records('question_hints', array('questionid' => $newquestionid), '', 'id, hint'); foreach ($potentialhints as $potentialhint) { // Clean in the same way than {@link xml_writer::xml_safe_utf8()}. $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars. $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending. if ($cleanhint === $data->hint) { $newitemid = $data->id; } } } // If we haven't found the newitemid, something has gone really wrong, question in DB // is missing hints, exception if (!$newitemid) { $info = new stdClass(); $info->filequestionid = $oldquestionid; $info->dbquestionid = $newquestionid; $info->hint = $data->hint; throw new restore_step_exception('error_question_hint_missing_in_db', $info); } } // Create mapping (I'm not sure if this is really needed?) $this->set_mapping('question_hint', $oldid, $newitemid); } protected function process_tag($data) { global $CFG, $DB; $data = (object)$data; $newquestion = $this->get_new_parentid('question'); if (!empty($CFG->usetags)) { // if enabled in server // TODO: This is highly inefficient. Each time we add one tag // we fetch all the existing because tag_set() deletes them // so everything must be reinserted on each call $tags = array(); $existingtags = tag_get_tags('question', $newquestion); // Re-add all the existitng tags foreach ($existingtags as $existingtag) { $tags[] = $existingtag->rawname; } // Add the one being restored $tags[] = $data->rawname; // Get the category, so we can then later get the context. $categoryid = $this->get_new_parentid('question_category'); if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) { $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid)); } // Send all the tags back to the question tag_set('question', $newquestion, $tags, 'core_question', $this->cachedcategory->contextid); } } protected function after_execute() { global $DB; // First of all, recode all the created question_categories->parent fields $qcats = $DB->get_records('backup_ids_temp', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_category_created')); foreach ($qcats as $qcat) { $newparent = 0; $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid)); // Get new parent (mapped or created, so we look in quesiton_category mappings) if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_category', 'itemid' => $dbcat->parent))) { // contextids must match always, as far as we always include complete qbanks, just check it $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent)); if ($dbcat->contextid == $newparentctxid) { $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id)); } else { $newparent = 0; // No ctx match for both cats, no parent relationship } } // Here with $newparent empty, problem with contexts or remapping, set it to top cat if (!$newparent) { $DB->set_field('question_categories', 'parent', 0, array('id' => $dbcat->id)); } } // Now, recode all the created question->parent fields $qs = $DB->get_records('backup_ids_temp', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question_created')); foreach ($qs as $q) { $newparent = 0; $dbq = $DB->get_record('question', array('id' => $q->newitemid)); // Get new parent (mapped or created, so we look in question mappings) if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array( 'backupid' => $this->get_restoreid(), 'itemname' => 'question', 'itemid' => $dbq->parent))) { $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id)); } } // Note, we don't restore any question files yet // as far as the CONTEXT_MODULE categories still // haven't their contexts to be restored to // The {@link restore_create_question_files}, executed in the final step // step will be in charge of restoring all the question files } } /** * Execution step that will move all the CONTEXT_MODULE question categories * created at early stages of restore in course context (because modules weren't * created yet) to their target module (matching by old-new-contextid mapping) */ class restore_move_module_questions_categories extends restore_execution_step { protected function define_execution() { global $DB; $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE); foreach ($contexts as $contextid => $contextlevel) { // Only if context mapping exists (i.e. the module has been restored) if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) { // Update all the qcats having their parentitemid set to the original contextid $modulecats = $DB->get_records_sql("SELECT itemid, newitemid FROM {backup_ids_temp} WHERE backupid = ? AND itemname = 'question_category' AND parentitemid = ?", array($this->get_restoreid(), $contextid)); foreach ($modulecats as $modulecat) { $DB->set_field('question_categories', 'contextid', $newcontext->newitemid, array('id' => $modulecat->newitemid)); // And set new contextid also in question_category mapping (will be // used by {@link restore_create_question_files} later restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid, $modulecat->newitemid, $newcontext->newitemid); } } } } } /** * Execution step that will create all the question/answers/qtype-specific files for the restored * questions. It must be executed after {@link restore_move_module_questions_categories} * because only then each question is in its final category and only then the * contexts can be determined. */ class restore_create_question_files extends restore_execution_step { /** @var array Question-type specific component items cache. */ private $qtypecomponentscache = array(); /** * Preform the restore_create_question_files step. */ protected function define_execution() { global $DB; // Track progress, as this task can take a long time. $progress = $this->task->get_progress(); $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE); // Parentitemids of question_createds in backup_ids_temp are the category it is in. // MUST use a recordset, as there is no unique key in the first (or any) column. $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype FROM {backup_ids_temp} bi JOIN {question} q ON q.id = bi.newitemid WHERE bi.backupid = ? AND bi.itemname = 'question_created' ORDER BY categoryid ASC", array($this->get_restoreid())); $currentcatid = -1; foreach ($catqtypes as $categoryid => $row) { $qtype = $row->qtype; // Check if we are in a new category. if ($currentcatid !== $categoryid) { // Report progress for each category. $progress->progress(); if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_category', $categoryid)) { // Something went really wrong, cannot find the question_category for the question_created records. debugging('Error fetching target context for question', DEBUG_DEVELOPER); continue; } // Calculate source and target contexts. $oldctxid = $qcatmapping->info->contextid; $newctxid = $qcatmapping->parentitemid; $this->send_common_files($oldctxid, $newctxid, $progress); $currentcatid = $categoryid; } $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress); } $catqtypes->close(); $progress->end_progress(); } /** * Send the common question files to a new context. * * @param int $oldctxid Old context id. * @param int $newctxid New context id. * @param \core\progress $progress Progress object to use. */ private function send_common_files($oldctxid, $newctxid, $progress) { // Add common question files (question and question_answer ones). restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer', $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback', $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint', $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback', $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress); } /** * Send the question type specific files to a new context. * * @param text $qtype The qtype name to send. * @param int $oldctxid Old context id. * @param int $newctxid New context id. * @param \core\progress $progress Progress object to use. */ private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) { if (!isset($this->qtypecomponentscache[$qtype])) { $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype); } $components = $this->qtypecomponentscache[$qtype]; foreach ($components as $component => $fileareas) { foreach ($fileareas as $filearea => $mapping) { restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea, $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress); } } } } /** * Try to restore aliases and references to external files. * * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}. * We expect that all regular (non-alias) files have already been restored. Make sure * there is no restore step executed after this one that would call send_files_to_pool() again. * * You may notice we have hardcoded support for Server files, Legacy course files * and user Private files here at the moment. This could be eventually replaced with a set of * callbacks in the future if needed. * * @copyright 2012 David Mudrak <david@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class restore_process_file_aliases_queue extends restore_execution_step { /** @var array internal cache for {@link choose_repository()} */ private $cachereposbyid = array(); /** @var array internal cache for {@link choose_repository()} */ private $cachereposbytype = array(); /** * What to do when this step is executed. */ protected function define_execution() { global $DB; $this->log('processing file aliases queue', backup::LOG_DEBUG); $fs = get_file_storage(); // Load the queue. $rs = $DB->get_recordset('backup_ids_temp', array('backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'), '', 'info'); // Iterate over aliases in the queue. foreach ($rs as $record) { $info = backup_controller_dbops::decode_backup_temp_info($record->info); // Try to pick a repository instance that should serve the alias. $repository = $this->choose_repository($info); if (is_null($repository)) { $this->notify_failure($info, 'unable to find a matching repository instance'); continue; } if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') { // Aliases to Server files and Legacy course files may refer to a file // contained in the backup file or to some existing file (if we are on the // same site). try { $reference = file_storage::unpack_reference($info->oldfile->reference); } catch (Exception $e) { $this->notify_failure($info, 'invalid reference field format'); continue; } // Let's see if the referred source file was also included in the backup. $candidates = $DB->get_recordset('backup_files_temp', array( 'backupid' => $this->get_restoreid(), 'contextid' => $reference['contextid'], 'component' => $reference['component'], 'filearea' => $reference['filearea'], 'itemid' => $reference['itemid'], ), '', 'info, newcontextid, newitemid'); $source = null; foreach ($candidates as $candidate) { $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info); if ($candidateinfo->filename === $reference['filename'] and $candidateinfo->filepath === $reference['filepath'] and !is_null($candidate->newcontextid) and !is_null($candidate->newitemid) ) { $source = $candidateinfo; $source->contextid = $candidate->newcontextid; $source->itemid = $candidate->newitemid; break; } } $candidates->close(); if ($source) { // We have an alias that refers to another file also included in // the backup. Let us change the reference field so that it refers // to the restored copy of the original file. $reference = file_storage::pack_reference($source); // Send the new alias to the filepool. $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { // This is a reference to some moodle file that was not contained in the backup // file. If we are restoring to the same site, keep the reference untouched // and restore the alias as is if the referenced file exists. if ($this->task->is_samesite()) { if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) { $reference = file_storage::pack_reference($reference); $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { $this->notify_failure($info, 'referenced file not found'); continue; } // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'referenced file not included'); continue; } } } else if ($info->oldfile->repositorytype === 'user') { if ($this->task->is_samesite()) { // For aliases to user Private files at the same site, we have a chance to check // if the referenced file still exists. try { $reference = file_storage::unpack_reference($info->oldfile->reference); } catch (Exception $e) { $this->notify_failure($info, 'invalid reference field format'); continue; } if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'], $reference['itemid'], $reference['filepath'], $reference['filename'])) { $reference = file_storage::pack_reference($reference); $fs->create_file_from_reference($info->newfile, $repository->id, $reference); $this->notify_success($info); continue; } else { $this->notify_failure($info, 'referenced file not found'); continue; } // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'restoring at another site'); continue; } } else { // This is a reference to some external file such as in boxnet or dropbox. // If we are restoring to the same site, keep the reference untouched and // restore the alias as is. if ($this->task->is_samesite()) { $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference); $this->notify_success($info); continue; // If we are at other site, we can't restore this alias. } else { $this->notify_failure($info, 'restoring at another site'); continue; } } } $rs->close(); } /** * Choose the repository instance that should handle the alias. * * At the same site, we can rely on repository instance id and we just * check it still exists. On other site, try to find matching Server files or * Legacy course files repository instance. Return null if no matching * repository instance can be found. * * @param stdClass $info * @return repository|null */ private function choose_repository(stdClass $info) { global $DB, $CFG; require_once($CFG->dirroot.'/repository/lib.php'); if ($this->task->is_samesite()) { // We can rely on repository instance id. if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) { return $this->cachereposbyid[$info->oldfile->repositoryid]; } $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1); try { $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID); return $this->cachereposbyid[$info->oldfile->repositoryid]; } catch (Exception $e) { $this->cachereposbyid[$info->oldfile->repositoryid] = null; return null; } } else { // We can rely on repository type only. if (empty($info->oldfile->repositorytype)) { return null; } if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) { return $this->cachereposbytype[$info->oldfile->repositorytype]; } $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1); // Both Server files and Legacy course files repositories have a single // instance at the system context to use. Let us try to find it. if ($info->oldfile->repositorytype === 'local' or $info->oldfile->repositorytype === 'coursefiles') { $sql = "SELECT ri.id FROM {repository} r JOIN {repository_instances} ri ON ri.typeid = r.id WHERE r.type = ? AND ri.contextid = ?"; $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID)); if (empty($ris)) { return null; } $repoids = array_keys($ris); $repoid = reset($repoids); try { $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID); return $this->cachereposbytype[$info->oldfile->repositorytype]; } catch (Exception $e) { $this->cachereposbytype[$info->oldfile->repositorytype] = null; return null; } } $this->cachereposbytype[$info->oldfile->repositorytype] = null; return null; } } /** * Let the user know that the given alias was successfully restored * * @param stdClass $info */ private function notify_success(stdClass $info) { $filedesc = $this->describe_alias($info); $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1); } /** * Let the user know that the given alias can't be restored * * @param stdClass $info * @param string $reason detailed reason to be logged */ private function notify_failure(stdClass $info, $reason = '') { $filedesc = $this->describe_alias($info); if ($reason) { $reason = ' ('.$reason.')'; } $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1); $this->add_result_item('file_aliases_restore_failures', $filedesc); } /** * Return a human readable description of the alias file * * @param stdClass $info * @return string */ private function describe_alias(stdClass $info) { $filedesc = $this->expected_alias_location($info->newfile); if (!is_null($info->oldfile->source)) { $filedesc .= ' ('.$info->oldfile->source.')'; } return $filedesc; } /** * Return the expected location of a file * * Please note this may and may not work as a part of URL to pluginfile.php * (depends on how the given component/filearea deals with the itemid). * * @param stdClass $filerecord * @return string */ private function expected_alias_location($filerecord) { $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea; if (!is_null($filerecord->itemid)) { $filedesc .= '/'.$filerecord->itemid; } $filedesc .= $filerecord->filepath.$filerecord->filename; return $filedesc; } /** * Append a value to the given resultset * * @param string $name name of the result containing a list of values * @param mixed $value value to add as another item in that result */ private function add_result_item($name, $value) { $results = $this->task->get_results(); if (isset($results[$name])) { if (!is_array($results[$name])) { throw new coding_exception('Unable to append a result item into a non-array structure.'); } $current = $results[$name]; $current[] = $value; $this->task->add_result(array($name => $current)); } else { $this->task->add_result(array($name => array($value))); } } } /** * Abstract structure step, to be used by all the activities using core questions stuff * (like the quiz module), to support qtype plugins, states and sessions */ abstract class restore_questions_activity_structure_step extends restore_activity_structure_step { /** @var array question_attempt->id to qtype. */ protected $qtypes = array(); /** @var array question_attempt->id to questionid. */ protected $newquestionids = array(); /** * Attach below $element (usually attempts) the needed restore_path_elements * to restore question_usages and all they contain. * * If you use the $nameprefix parameter, then you will need to implement some * extra methods in your class, like * * protected function process_{nameprefix}question_attempt($data) { * $this->restore_question_usage_worker($data, '{nameprefix}'); * } * protected function process_{nameprefix}question_attempt($data) { * $this->restore_question_attempt_worker($data, '{nameprefix}'); * } * protected function process_{nameprefix}question_attempt_step($data) { * $this->restore_question_attempt_step_worker($data, '{nameprefix}'); * } * * @param restore_path_element $element the parent element that the usages are stored inside. * @param array $paths the paths array that is being built. * @param string $nameprefix should match the prefix passed to the corresponding * backup_questions_activity_structure_step::add_question_usages call. */ protected function add_question_usages($element, &$paths, $nameprefix = '') { // Check $element is restore_path_element if (! $element instanceof restore_path_element) { throw new restore_step_exception('element_must_be_restore_path_element', $element); } // Check $paths is one array if (!is_array($paths)) { throw new restore_step_exception('paths_must_be_array', $paths); } $paths[] = new restore_path_element($nameprefix . 'question_usage', $element->get_path() . "/{$nameprefix}question_usage"); $paths[] = new restore_path_element($nameprefix . 'question_attempt', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt"); $paths[] = new restore_path_element($nameprefix . 'question_attempt_step', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step", true); $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data', $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable"); } /** * Process question_usages */ protected function process_question_usage($data) { $this->restore_question_usage_worker($data, ''); } /** * Process question_attempts */ protected function process_question_attempt($data) { $this->restore_question_attempt_worker($data, ''); } /** * Process question_attempt_steps */ protected function process_question_attempt_step($data) { $this->restore_question_attempt_step_worker($data, ''); } /** * This method does the acutal work for process_question_usage or * process_{nameprefix}_question_usage. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_usage_worker($data, $nameprefix) { global $DB; // Clear our caches. $this->qtypes = array(); $this->newquestionids = array(); $data = (object)$data; $oldid = $data->id; $oldcontextid = $this->get_task()->get_old_contextid(); $data->contextid = $this->get_mappingid('context', $this->task->get_old_contextid()); // Everything ready, insert (no mapping needed) $newitemid = $DB->insert_record('question_usages', $data); $this->inform_new_usage_id($newitemid); $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false); } /** * When process_question_usage creates the new usage, it calls this method * to let the activity link to the new usage. For example, the quiz uses * this method to set quiz_attempts.uniqueid to the new usage id. * @param integer $newusageid */ abstract protected function inform_new_usage_id($newusageid); /** * This method does the acutal work for process_question_attempt or * process_{nameprefix}_question_attempt. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_attempt_worker($data, $nameprefix) { global $DB; $data = (object)$data; $oldid = $data->id; $question = $this->get_mapping('question', $data->questionid); $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage'); $data->questionid = $question->newitemid; if (!property_exists($data, 'variant')) { $data->variant = 1; } $data->timemodified = $this->apply_date_offset($data->timemodified); if (!property_exists($data, 'maxfraction')) { $data->maxfraction = 1; } $newitemid = $DB->insert_record('question_attempts', $data); $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid); $this->qtypes[$newitemid] = $question->info->qtype; $this->newquestionids[$newitemid] = $data->questionid; } /** * This method does the acutal work for process_question_attempt_step or * process_{nameprefix}_question_attempt_step. * @param array $data the data from the XML file. * @param string $nameprefix the element name prefix. */ protected function restore_question_attempt_step_worker($data, $nameprefix) { global $DB; $data = (object)$data; $oldid = $data->id; // Pull out the response data. $response = array(); if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) { foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) { $response[$variable['name']] = $variable['value']; } } unset($data->response); $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt'); $data->timecreated = $this->apply_date_offset($data->timecreated); $data->userid = $this->get_mappingid('user', $data->userid); // Everything ready, insert and create mapping (needed by question_sessions) $newitemid = $DB->insert_record('question_attempt_steps', $data); $this->set_mapping('question_attempt_step', $oldid, $newitemid, true); // Now process the response data. $response = $this->questions_recode_response_data( $this->qtypes[$data->questionattemptid], $this->newquestionids[$data->questionattemptid], $data->sequencenumber, $response); foreach ($response as $name => $value) { $row = new stdClass(); $row->attemptstepid = $newitemid; $row->name = $name; $row->value = $value; $DB->insert_record('question_attempt_step_data', $row, false); } } /** * Recode the respones data for a particular step of an attempt at at particular question. * @param string $qtype the question type. * @param int $newquestionid the question id. * @param int $sequencenumber the sequence number. * @param array $response the response data to recode. */ public function questions_recode_response_data( $qtype, $newquestionid, $sequencenumber, array $response) { $qtyperestorer = $this->get_qtype_restorer($qtype); if ($qtyperestorer) { $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response); } return $response; } /** * Given a list of question->ids, separated by commas, returns the * recoded list, with all the restore question mappings applied. * Note: Used by quiz->questions and quiz_attempts->layout * Note: 0 = page break (unconverted) */ protected function questions_recode_layout($layout) { // Extracts question id from sequence if ($questionids = explode(',', $layout)) { foreach ($questionids as $id => $questionid) { if ($questionid) { // If it is zero then this is a pagebreak, don't translate $newquestionid = $this->get_mappingid('question', $questionid); $questionids[$id] = $newquestionid; } } } return implode(',', $questionids); } /** * Get the restore_qtype_plugin subclass for a specific question type. * @param string $qtype e.g. multichoice. * @return restore_qtype_plugin instance. */ protected function get_qtype_restorer($qtype) { // Build one static cache to store {@link restore_qtype_plugin} // while we are needing them, just to save zillions of instantiations // or using static stuff that will break our nice API static $qtypeplugins = array(); if (!isset($qtypeplugins[$qtype])) { $classname = 'restore_qtype_' . $qtype . '_plugin'; if (class_exists($classname)) { $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this); } else { $qtypeplugins[$qtype] = null; } } return $qtypeplugins[$qtype]; } protected function after_execute() { parent::after_execute(); // Restore any files belonging to responses. foreach (question_engine::get_all_response_file_areas() as $filearea) { $this->add_related_files('question', $filearea, 'question_attempt_step'); } } /** * Attach below $element (usually attempts) the needed restore_path_elements * to restore question attempt data from Moodle 2.0. * * When using this method, the parent element ($element) must be defined with * $grouped = true. Then, in that elements process method, you must call * {@link process_legacy_attempt_data()} with the groupded data. See, for * example, the usage of this method in {@link restore_quiz_activity_structure_step}. * @param restore_path_element $element the parent element. (E.g. a quiz attempt.) * @param array $paths the paths array that is being built to describe the * structure. */ protected function add_legacy_question_attempt_data($element, &$paths) { global $CFG; require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php'); // Check $element is restore_path_element if (!($element instanceof restore_path_element)) { throw new restore_step_exception('element_must_be_restore_path_element', $element); } // Check $paths is one array if (!is_array($paths)) { throw new restore_step_exception('paths_must_be_array', $paths); } $paths[] = new restore_path_element('question_state', $element->get_path() . '/states/state'); $paths[] = new restore_path_element('question_session', $element->get_path() . '/sessions/session'); } protected function get_attempt_upgrader() { if (empty($this->attemptupgrader)) { $this->attemptupgrader = new question_engine_attempt_upgrader(); $this->attemptupgrader->prepare_to_restore(); } return $this->attemptupgrader; } /** * Process the attempt data defined by {@link add_legacy_question_attempt_data()}. * @param object $data contains all the grouped attempt data to process. * @param pbject $quiz data about the activity the attempts belong to. Required * fields are (basically this only works for the quiz module): * oldquestions => list of question ids in this activity - using old ids. * preferredbehaviour => the behaviour to use for questionattempts. */ protected function process_legacy_quiz_attempt_data($data, $quiz) { global $DB; $upgrader = $this->get_attempt_upgrader(); $data = (object)$data; $layout = explode(',', $data->layout); $newlayout = $layout; // Convert each old question_session into a question_attempt. $qas = array(); foreach (explode(',', $quiz->oldquestions) as $questionid) { if ($questionid == 0) { continue; } $newquestionid = $this->get_mappingid('question', $questionid); if (!$newquestionid) { throw new restore_step_exception('questionattemptreferstomissingquestion', $questionid, $questionid); } $question = $upgrader->load_question($newquestionid, $quiz->id); foreach ($layout as $key => $qid) { if ($qid == $questionid) { $newlayout[$key] = $newquestionid; } } list($qsession, $qstates) = $this->find_question_session_and_states( $data, $questionid); if (empty($qsession) || empty($qstates)) { throw new restore_step_exception('questionattemptdatamissing', $questionid, $questionid); } list($qsession, $qstates) = $this->recode_legacy_response_data( $question, $qsession, $qstates); $data->layout = implode(',', $newlayout); $qas[$newquestionid] = $upgrader->convert_question_attempt( $quiz, $data, $question, $qsession, $qstates); } // Now create a new question_usage. $usage = new stdClass(); $usage->component = 'mod_quiz'; $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid()); $usage->preferredbehaviour = $quiz->preferredbehaviour; $usage->id = $DB->insert_record('question_usages', $usage); $this->inform_new_usage_id($usage->id); $data->uniqueid = $usage->id; $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas, $this->questions_recode_layout($quiz->oldquestions)); } protected function find_question_session_and_states($data, $questionid) { $qsession = null; foreach ($data->sessions['session'] as $session) { if ($session['questionid'] == $questionid) { $qsession = (object) $session; break; } } $qstates = array(); foreach ($data->states['state'] as $state) { if ($state['question'] == $questionid) { // It would be natural to use $state['seq_number'] as the array-key // here, but it seems that buggy behaviour in 2.0 and early can // mean that that is not unique, so we use id, which is guaranteed // to be unique. $qstates[$state['id']] = (object) $state; } } ksort($qstates); $qstates = array_values($qstates); return array($qsession, $qstates); } /** * Recode any ids in the response data * @param object $question the question data * @param object $qsession the question sessions. * @param array $qstates the question states. */ protected function recode_legacy_response_data($question, $qsession, $qstates) { $qsession->questionid = $question->id; foreach ($qstates as &$state) { $state->question = $question->id; $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype); } return array($qsession, $qstates); } /** * Recode the legacy answer field. * @param object $state the state to recode the answer of. * @param string $qtype the question type. */ public function restore_recode_legacy_answer($state, $qtype) { $restorer = $this->get_qtype_restorer($qtype); if ($restorer) { return $restorer->recode_legacy_state_answer($state); } else { return $state->answer; } } }
Java
package CGRB::BLASTDB; # $Id: BLASTDB.pm,v 1.4 2004/11/16 21:38:43 givans Exp $ use warnings; use strict; use Carp; use CGRB::CGRBDB; use vars qw/ @ISA /; @ISA = qw/ CGRBDB /; 1; sub new { my $pkg = shift; my $user = shift; my $psswd = shift; $user = 'gcg' unless ($user); $psswd = 'sequences' unless ($psswd); # print "using user=$user, passwd=$psswd\n"; my $self = $pkg->generate('seq_databases',$user,$psswd); return $self; } sub availDB { my $self = shift; my $db = shift; my $avail = shift; $avail ? $self->_set_availDB($db,$avail) : $self->_get_availDB($db); } sub _set_availDB { my $self = shift; my $db = shift; my $avail = shift;# should be T or F my $dbh = $self->dbh(); my ($sth,$rslt); my $dbFile = $self->dbFile($db);# dbFile will be name of DB if ($avail ne 'T' && $avail ne 'F') { return "database available should be either 'T' or 'F'"; } $sth = $dbh->prepare("update DB set Avail = ? where db_file = ?"); $sth->bind_param(1,$avail); $sth->bind_param(2,$dbFile); $rslt = $self->_dbAction($dbh,$sth,3); if (ref $rslt eq 'ARRAY') { return $rslt->[0]->[0]; } else { return 0; } } sub _get_availDB { my $self = shift; my $db = shift; my $dbh = $self->dbh(); my ($sth,$rslt); my $dbFile = $self->dbFile($db); $sth = $dbh->prepare("select Avail from DB where db_file = ?"); $sth->bind_param(1,$dbFile); $rslt = $self->_dbAction($dbh,$sth,2); if (ref $rslt eq 'ARRAY') { return $rslt->[0]->[0]; } else { return 0; } } sub availDB_byType { my $self = shift; my $dbType = shift; my $avail = shift; $avail ? $self->_set_availDB_byType($dbType,$avail) : $self->_get_availDB_byType($dbType); } sub _set_availDB_byType { warn("setting DB availability by type no yet implemented"); } sub _get_availDB_byType { my $self = shift; my $dbType = shift; my $dbh = $self->dbh(); my ($sth,$rslt); $sth = $dbh->prepare("select db_name from DB where db_type = ? and Avail = 'F'"); $sth->bind_param(1, $dbType); $rslt = $self->_dbAction($dbh,$sth,2); if (ref $rslt eq 'ARRAY') { if ($rslt->[0]->[0]) { return 'F'; } else { return 'T'; } } else { return 0; } } sub dbFile { my $self = shift; my $db = shift; my $file = shift; $file ? $self->_set_dbFile($db,$file) : $self->_get_dbFile($db); } sub _set_dbFile { warn("setting db file not yet implemented"); } sub _get_dbFile { my $self = shift; my $db = shift; my $dbh = $self->dbh(); my ($sth,$rslt); $sth = $dbh->prepare("select db_file from DB where db_name = ?"); $sth->bind_param(1,$db); $rslt = $self->_dbAction($dbh,$sth,2); if (ref $rslt eq 'ARRAY') { return $rslt->[0]->[0]; } else { return 0; } } sub dbInfo { my $self = shift; my $dbh = $self->dbh(); my ($sth,$dates,%date); $sth = $dbh->prepare("select D.displayName, D.dwnld_date, D.description, T.type, D.displayOrder, D.db_name from DB D, DBType T where D.db_type = T.number AND D.displayOrder > 0"); $dates = $self->_dbAction($dbh,$sth,2); if (ref $dates eq 'ARRAY') { foreach my $ref (@$dates) { # print "Dababase: '$ref->[0]', Date: '$ref->[1]'<br>"; $date{$ref->[0]} = [$ref->[1], $ref->[2], $ref->[3], $ref->[4], $ref->[5]]; } return \%date; } else { return 0; } }
Java
<!DOCTYPE html > <html> <head> <title>BigDecimalStringConverter - ScalaFX API 8.0.0-R4 - scalafx.util.converter.BigDecimalStringConverter</title> <meta name="description" content="BigDecimalStringConverter - ScalaFX API 8.0.0 - R4 - scalafx.util.converter.BigDecimalStringConverter" /> <meta name="keywords" content="BigDecimalStringConverter ScalaFX API 8.0.0 R4 scalafx.util.converter.BigDecimalStringConverter" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'scalafx.util.converter.BigDecimalStringConverter'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="type"> <div id="definition"> <a href="BigDecimalStringConverter$.html" title="Go to companion"><img src="../../../lib/class_to_object_big.png" /></a> <p id="owner"><a href="../../package.html" class="extype" name="scalafx">scalafx</a>.<a href="../package.html" class="extype" name="scalafx.util">util</a>.<a href="package.html" class="extype" name="scalafx.util.converter">converter</a></p> <h1><a href="BigDecimalStringConverter$.html" title="Go to companion">BigDecimalStringConverter</a></h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">BigDecimalStringConverter</span><span class="result"> extends <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a>[<span class="extype" name="java.math.BigDecimal">BigDecimal</span>, <span class="extype" name="scala.BigDecimal">BigDecimal</span>, <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>]</span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a>[<span class="extype" name="java.math.BigDecimal">BigDecimal</span>, <span class="extype" name="scala.BigDecimal">BigDecimal</span>, <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>], <a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a>[<span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>], <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a>[<span class="extype" name="scala.BigDecimal">BigDecimal</span>], <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="scalafx.util.converter.BigDecimalStringConverter"><span>BigDecimalStringConverter</span></li><li class="in" name="scalafx.util.converter.StringConverterDelegate"><span>StringConverterDelegate</span></li><li class="in" name="scalafx.delegate.SFXDelegate"><span>SFXDelegate</span></li><li class="in" name="scalafx.util.StringConverter"><span>StringConverter</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="scalafx.util.converter.BigDecimalStringConverter#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(delegate:javafx.util.converter.BigDecimalStringConverter):scalafx.util.converter.BigDecimalStringConverter"></a> <a id="&lt;init&gt;:BigDecimalStringConverter"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">BigDecimalStringConverter</span><span class="params">(<span name="delegate">delegate: <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span> = <span class="symbol">new jfxuc.BigDecimalStringConverter</span></span>)</span> </span> </h4> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scalafx.util.converter.StringConverterDelegate#delegate" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="delegate:C"></a> <a id="delegate:javafx.util.converter.BigDecimalStringConverter"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">delegate</span><span class="result">: <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span></span> </span> </h4> <p class="shortcomment cmt">JavaFx StringConverter to be wrapped.</p><div class="fullcomment"><div class="comment cmt"><p>JavaFx StringConverter to be wrapped. </p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a> → <a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a></dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.delegate.SFXDelegate#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(ref:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="ref">ref: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <p class="shortcomment cmt">Verifies if a object is equals to this delegate.</p><div class="fullcomment"><div class="comment cmt"><p>Verifies if a object is equals to this delegate. </p></div><dl class="paramcmts block"><dt class="param">ref</dt><dd class="cmt"><p>Object to be compared.</p></dd><dt>returns</dt><dd class="cmt"><p>if the other object is equals to this delegate or not. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scalafx.util.converter.BigDecimalStringConverter#fromString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="fromString(s:String):BigDecimal"></a> <a id="fromString(String):BigDecimal"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">fromString</span><span class="params">(<span name="s">s: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <span class="extype" name="scala.BigDecimal">BigDecimal</span></span> </span> </h4> <p class="shortcomment cmt">Converts the string provided into an object defined by the specific converter.</p><div class="fullcomment"><div class="comment cmt"><p>Converts the string provided into an object defined by the specific converter. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>A new T instance generated from argument. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="scalafx.util.converter.BigDecimalStringConverter">BigDecimalStringConverter</a> → <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a> → <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a></dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scalafx.delegate.SFXDelegate#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>The delegate hashcode </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scalafx.util.converter.BigDecimalStringConverter#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString(b:BigDecimal):String"></a> <a id="toString(BigDecimal):String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">(<span name="b">b: <span class="extype" name="scala.BigDecimal">BigDecimal</span></span>)</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span> </span> </h4> <p class="shortcomment cmt">Converts the object provided into its string form.</p><div class="fullcomment"><div class="comment cmt"><p>Converts the object provided into its string form. </p></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>String version of argument. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="scalafx.util.converter.BigDecimalStringConverter">BigDecimalStringConverter</a> → <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a> → <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a></dd></dl></div> </li><li name="scalafx.delegate.SFXDelegate#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4> <p class="shortcomment cmt"></p><div class="fullcomment"><div class="comment cmt"></div><dl class="paramcmts block"><dt>returns</dt><dd class="cmt"><p>Returns the original delegate's <code>toString()</code> adding a <code>[SFX]</code> prefix. </p></dd></dl><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scalafx.util.converter.StringConverterDelegate"> <h3>Inherited from <a href="StringConverterDelegate.html" class="extype" name="scalafx.util.converter.StringConverterDelegate">StringConverterDelegate</a>[<span class="extype" name="java.math.BigDecimal">BigDecimal</span>, <span class="extype" name="scala.BigDecimal">BigDecimal</span>, <span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>]</h3> </div><div class="parent" name="scalafx.delegate.SFXDelegate"> <h3>Inherited from <a href="../../delegate/SFXDelegate.html" class="extype" name="scalafx.delegate.SFXDelegate">SFXDelegate</a>[<span class="extype" name="javafx.util.converter.BigDecimalStringConverter">javafx.util.converter.BigDecimalStringConverter</span>]</h3> </div><div class="parent" name="scalafx.util.StringConverter"> <h3>Inherited from <a href="../StringConverter.html" class="extype" name="scalafx.util.StringConverter">StringConverter</a>[<span class="extype" name="scala.BigDecimal">BigDecimal</span>]</h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package xmv.solutions.IT2JZ.Jira; /** * * @author David Koller XMV Solutions GmbH */ public class JiraTestcaseStep { /** * Name of Step (e.g. "Step 1") */ private String stepName; /** * Action to give in actual step (e.g. "Press red button") */ private String testData; /** * Expected result of action for current step (e.g. "Popup is shown saying 'Done!'") */ private String expectedResult; public String getStepName() { return stepName; } public void setStepName(String stepName) { this.stepName = stepName; } public String getTestData() { return testData; } public void setTestData(String testData) { this.testData = testData; } public String getExpectedResult() { return expectedResult; } public void setExpectedResult(String expectedResult) { this.expectedResult = expectedResult; } }
Java
/* package de.elxala.langutil (c) Copyright 2006 Alejandro Xalabarder Aulet This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* //(o) WelcomeGastona_source_javaj_layout EVALAYOUT ======================================================================================== ================ documentation for WelcomeGastona.gast ================================= ======================================================================================== #gastonaDoc# <docType> javaj_layout <name> EVALAYOUT <groupInfo> <javaClass> de.elxala.Eva.layout.EvaLayout <importance> 10 <desc> //A fexible grid layout <help> // // Eva layout is the most powerful layout used by Javaj. The components are laid out in a grid // and it is possible to define very accurately which cells of the grid occupy each one, which // size has to have and if they are expandable or not. // // Syntax: // // <layout of NAME> // EVALAYOUT, marginX, marginY, gapX, gapY // // --grid-- , header col1, ... , header colN // header row1, cell 1 1 , ... , cell 1 N // ... , ... , ... , ... // header rowM, cell M 1 , ... , cell M N // // The first row starts with "EVALAYOUT" or simply "EVA", then optionally the following values // in pixels for the whole grid // // marginX : horizontal margins for both left and right sides // marginY : vertical margins for both top and bottom areas // gapX : horizontal space between columns // gapY : vertical space between rows // // The rest of rows defines a grid with arbitrary N columns and M rows, the minimum for both M // and N is 1. To define a grid M x N we will need M+1 rows and a maximum of N+1 columns, this // is because the header types given in rows and columns. These header values may be one of: // // header // value meaning // ------- -------- // A Adapt (default). The row or column will adapt its size to the bigest default // size of all components that start in this row or column. // X Expand. The row or column is expandable, when the the frame is resized all // expandable row or columns will share the remaining space equally. // a number A fix size in pixels for the row or column // // Note that the very first header ("--grid--") acctually does not correspond with a row or a // column of the grid and therefore it is ignored by EvaLayout. // // Finally the cells are used to place and expand the components. If we want the component to // ocupy just one cell then we place it in that cell. If we want the component to ocupy more // cells then we place the component on the left-top cell of the rectangle of cells to be // ocupped, we fill the rest of top cells with "-" to the right and the rest of left cells with // the symbol "+" to the bottom, the rest of cells (neither top or left cells) might be left in // blank. // // Example: // // let's say we want to lay-out the following form // // ---------------------------------------------- // | label1 | field -------> | button1 | // ---------------------------------------------- // | label2 | text -------> | button2 | // ------------| | |---------- // | | | button3 | // | V |---------- // | | // ------------------------ // // representing this as grid of cells can be done at least in these two ways // // // Adapt Adapt Expand Adapt Adapt Expand Adapt // ------------------------------------- ----------------------------- // Adapt | label1 | field | - | button1 | Adapt | label1 | field | button1 | // |---------|-------|-------|---------| |---------|-------|---------| // Adapt | label2 | text | - | button2 | Adapt | label2 | text | button2 | // |---------|------ |-------|---------| |---------|------ |---------| // Adapt | | + | | button3 | Adapt | | + | button3 | // |---------|------ |-------|---------| |---------|------ |---------| // Expand | | + | | | Expand | | + | | // ------------------------------------- ----------------------------- // // the implementation of the second one as Evalayout would be // // <layout of myFirstLayout> // // EVALAYOUT // // grid, A , X , A // A, label1 , field , button1 // A, label2 , text , button2 // A, , + , button3 // X, , + , // // NOTE: While columns and rows of type expandable or fixed size might be empty of components, // this does not make sense for columns and rows of type adaptable (A), since in this // case there is nothing to adapt. These columns or rows has to be avoided because // might produce undefined results. // <...> // NOTE: EvaLayout is also available for C++ development with Windows Api and MFC, // see as reference the article http://www.codeproject.com/KB/dialog/EvaLayout.aspx // <examples> gastSample eva layout example1 eva layout example2 eva layout example3 eva layout complet eva layout centering eva layout percenting <eva layout example1> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example layout EVALAYOUT" // // <layout of F> // // EVALAYOUT, 10, 10, 5, 5 // // grid, , X , // , lLabel1 , eField1 , bButton1 // , lLabel2 , xText1 , bButton2 // , , + , bButton3 // X , , + , <eva layout example2> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example 2 layout EVALAYOUT" // // <layout of F> // // EVA, 10, 10, 5, 5 // // --- , 75 , X , A , // , bButton , xMemo , - , // , bBoton , + , , // , bKnopf , + , , // X , , + , , // , eCamp , - , bBotó maco , <eva layout example3> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example 2 bis layout EVALAYOUT" // // <layout of F> // EVALAYOUT, 15, 15, 5, 5 // // , , X , // 50, bBoton1 , - , - // , bBoton4 , eField , bBoton2 // X , + , xText , + // 50, bBoton3 , - , + <eva layout complet> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // F, "example complex layout" // // <layout of F> // EVALAYOUT, 15, 15, 5, 5 // // ---, 80 , X , 110 // , lLabel1 , eEdit1 , - // , lLabel2 , cCombo , lLabel3 // , lLabel4 , xMemo , iLista // , bBoton1 , + , + // , bBoton2 , + , + // X , , + , + // , layOwner , - , + // , , , bBoton4 // // <layout of layOwner> // PANEL, Y, Owner Info // // LayFields // // <layout of LayFields> // EVALAYOUT, 5, 5, 5, 5 // // ---, , X // , lName , eName // , lPhone , ePhone // <eva layout centering> //#gastona# // // <PAINT LAYOUT> // //#javaj# // // <frames> // Fmain, Centering with EvaLayout demo // // <layout of Fmain> // EVA // // , X, A , X // X , // A , , bCentered // X , <eva layout percenting> //#gastona# // // <!PAINT LAYOUT> // //#javaj# // // <frames> // Fmain, Percenting with EvaLayout demo, 300, 300 // // <layout of Fmain> // EVA, 10, 10, 7, 7 // // , X , X , X , X // X , b11 , b13 , - , - // X , b22 , - , b23 , - // X , + , , + , // X , b12 , - , + , // //#data# // // <b11> 25% x 25% // <b13> 75% horizontally 25% vertically // <b22> fifty-fifty // <b12> 50% x 25% y // <b23> half and 3/4 #**FIN_EVA# */ package de.elxala.Eva.layout; import java.util.Vector; import java.util.Hashtable; import java.util.Enumeration; // to traverse the HashTable ... import java.awt.*; import de.elxala.Eva.*; import de.elxala.langutil.*; import de.elxala.zServices.*; /** @author Alejandro Xalabarder @date 11.04.2006 22:32 Example: <pre> import java.awt.*; import javax.swing.*; import de.elxala.Eva.*; import de.elxala.Eva.layout.*; public class sampleEvaLayout { public static void main (String [] aa) { JFrame frame = new JFrame ("sampleEvaLayout"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = frame.getContentPane (); Eva lay = new Eva(); // set margins lay.addLine (new EvaLine ("EvaLayout, 15, 15, 5, 5")); // set grid lay.addLine (new EvaLine ("RxC, , 100 , X ,")); lay.addLine (new EvaLine (" , lname , eName , ,")); lay.addLine (new EvaLine (" , lobserv, xObs , - ,")); lay.addLine (new EvaLine (" X, , + , ,")); pane.setLayout (new EvaLayout(lay)); pane.add ("lname", new JLabel("Name")); pane.add ("lobserv", new JLabel("Notes")); pane.add ("eName", new JTextField()); pane.add ("xObs", new JTextPane()); frame.pack(); frame.setSize (new Dimension (300, 200)); frame.show(); } } </pre> */ public class EvaLayout implements LayoutManager2 { private static logger log = new logger (null, "de.elxala.Eva.EvaLayout", null); //19.10.2010 20:31 // Note : Limits introduced in change (bildID) 11088 on 2010-09-20 01:47:25 // named "FIX problema en layout (LOW LEVEL BUG 2!)" // But today the problem (without limits) cannot be reproduced! (?) // Limits set as aproximation, these can be reviewed and changed // private static int MAX_SIZE_DX = 10000; private static int MAX_SIZE_DY = 10000; protected static final int HEADER_EXPAND = 10; protected static final int HEADER_ORIGINAL = 11; protected static final int HEADER_NUMERIC = 12; protected static final String EXPAND_HORIZONTAL = "-"; protected static final String EXPAND_VERTICAL = "+"; // variables for pre-calculated layout // private boolean isPrecalculated = false; protected int Hmargin; protected int Vmargin; protected int Hgap; protected int Vgap; private int mnCols = -1; // note : this is a cached value and might be call before precalculation! private int mnRows = -1; // note : this is a cached value and might be call before precalculation! private int fijoH = 0; private int fijoV = 0; public int [] HdimMin = new int [0]; public int [] HdimPref = new int [0]; // for preferred instead of minimum public int [] Hpos = new int [0]; public int [] VdimMin = new int [0]; public int [] VdimPref = new int [0]; // for preferred instead of minimum public int [] Vpos = new int [0]; private Eva lay = null; private Hashtable componentHTable = new Hashtable(); protected class widgetInfo { public widgetInfo (String nam, Component com) { name = nam; comp = com; } public String name; // name of the component in the layout array public Component comp; // component info public boolean isLaidOut; // if the component has been found in the layout array // and therefore if indxPos is a valid calculated field // place in the layout array mesured in array indices public int posCol0; // first column that the widget occupies public int posRow0; // first row public int posCol1; // last column public int posRow1; // last row } Vector columnsReparto = new Vector (); Vector rowsReparto = new Vector (); public EvaLayout() { this(new Eva()); } public EvaLayout(Eva layarray) { log.dbg (2, "EvaLayout", "create EvaLayout " + layarray.getName ()); lay = layarray; } /** Switches to another layout : note that the components used in this new layout has to exists (added to the layout using add method) */ public void switchLayout(Eva layarray) { log.dbg (2, "switchLayout", "switch new layout info " + layarray.getName ()); lay = layarray; invalidatePreCalc (); } private int headType (String str) { if (str.length () == 0 || str.equalsIgnoreCase ("a")) return HEADER_ORIGINAL; if (str.equalsIgnoreCase ("x")) return HEADER_EXPAND; return HEADER_NUMERIC; // it should } private void precalculateAll () { if (isPrecalculated) return; log.dbg (2, "precalculateAll", "layout " + lay.getName () + " perform precalculation."); Hmargin = Math.max (0, stdlib.atoi (lay.getValue (0,1))); Vmargin = Math.max (0, stdlib.atoi (lay.getValue (0,2))); Hgap = Math.max (0, stdlib.atoi (lay.getValue (0,3))); Vgap = Math.max (0, stdlib.atoi (lay.getValue (0,4))); log.dbg (4, "precalculateAll", nColumns() + " columns x " + nRows() + " rows"); log.dbg (4, "precalculateAll", "margins xm=" + Hmargin + ", ym=" + Vmargin + ", yg=" + Hgap + ", yg=" + Vgap); mnCols = -1; // reset cached number of cols mnRows = -1; // reset cached number of rows HdimMin = new int [nColumns()]; HdimPref = new int [nColumns()]; Hpos = new int [nColumns()]; VdimMin = new int [nRows()]; VdimPref = new int [nRows()]; Vpos = new int [nRows()]; columnsReparto = new Vector (); rowsReparto = new Vector (); // for all components ... Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); ((widgetInfo) componentHTable.get(key)).isLaidOut = false; } // compute Vdim (Note: it might be precalculated if needed) fijoV = Vmargin; for (int rr = 0; rr < nRows(); rr ++) { String heaRow = rowHeader(rr); int typ = headType(heaRow); int gap = (rr == 0) ? 0: Vgap; if (typ == HEADER_ORIGINAL) { // maximum-minimum of the row VdimPref[rr] = minHeightOfRow(rr, true); VdimMin[rr] = minHeightOfRow(rr, false); log.dbg (2, "precalculateAll", "Adaption... VdimPref[rr] = " + VdimPref[rr]); } else if (typ == HEADER_EXPAND) { rowsReparto.add (new int [] { rr }); // compute later log.dbg (2, "precalculateAll", "Expand... VdimPref[rr] = " + VdimPref[rr]); } else { // indicated size VdimPref[rr] = VdimMin[rr] = stdlib.atoi(heaRow); log.dbg (2, "precalculateAll", "Explicit... VdimPref[rr] = " + VdimPref[rr]); } Vpos[rr] = fijoV + gap; fijoV += VdimPref[rr]; fijoV += gap; } fijoV += Vmargin; log.dbg (2, "precalculateAll", "fijoV = " + fijoV + " Vmargin = " + Vmargin + " Vgap = " + Vgap); //DEBUG .... if (log.isDebugging (2)) { String vertical = "Vertical array (posY/prefHeight/minHeight)"; for (int rr = 0; rr < Vpos.length; rr++) vertical += " " + rr + ") " + Vpos[rr] + "/" + VdimPref[rr] + "/" + VdimMin[rr]; log.dbg (2, "precalculateAll", vertical); } // compute Hdim (Note: it might be precalculated if needed) fijoH = Hmargin; for (int cc = 0; cc < nColumns(); cc ++) { String heaCol = columnHeader(cc); int typ = headType(heaCol); int gap = (cc == 0) ? 0: Hgap; if (typ == HEADER_ORIGINAL) { // maximum-minimum of the column HdimPref[cc] = minWidthOfColumn(cc, true); HdimMin[cc] = minWidthOfColumn(cc, false); } else if (typ == HEADER_EXPAND) columnsReparto.add (new int [] { cc }); // compute later else HdimPref[cc] = HdimMin[cc] = stdlib.atoi(heaCol); // indicated size Hpos[cc] = fijoH + gap; fijoH += HdimPref[cc]; fijoH += gap; } fijoH += Hmargin; log.dbg (2, "precalculateAll", "fijoH = " + fijoH); //DEBUG .... if (log.isDebugging (2)) { String horizontal = "Horizontal array (posX/prefWidth/minWidth)"; for (int cc = 0; cc < Hpos.length; cc++) horizontal += " " + cc + ") " + Hpos[cc] + "/" + HdimPref[cc] + "/" + HdimMin[cc]; log.dbg (2, "precalculateAll", horizontal); } // finding all components in the layout array for (int cc = 0; cc < nColumns(); cc ++) { for (int rr = 0; rr < nRows(); rr ++) { String name = widgetAt(rr, cc); widgetInfo wid = theComponent (name); if (wid == null) continue; // set position x,y wid.posCol0 = cc; wid.posRow0 = rr; // set position x2,y2 int ava = cc; while (ava+1 < nColumns() && widgetAt(rr, ava+1).equals (EXPAND_HORIZONTAL)) ava ++; wid.posCol1 = ava; ava = rr; while (ava+1 < nRows() && widgetAt(ava+1, cc).equals (EXPAND_VERTICAL)) ava ++; wid.posRow1 = ava; wid.isLaidOut = true; //DEBUG .... if (log.isDebugging (2)) { log.dbg (2, "precalculateAll", wid.name + " leftTop (" + wid.posCol0 + ", " + wid.posRow0 + ") rightBottom (" + wid.posCol1 + ", " + wid.posRow1 + ")"); } } } isPrecalculated = true; } protected int nColumns () { // OLD // return Math.max(0, lay.cols(1) - 1); if (mnCols != -1) return mnCols; // has to be calculated, // the maximum n of cols of header or rows // for (int ii = 1; ii < lay.rows (); ii ++) if (mnCols < Math.max(0, lay.cols(ii) - 1)) mnCols = Math.max(0, lay.cols(ii) - 1); mnCols = Math.max(0, mnCols); return mnCols; } protected int nRows () { // OLD // return Math.max(0, lay.rows() - 2); if (mnRows != -1) return mnRows; mnRows = Math.max(0, lay.rows() - 2); return mnRows; } public Eva getEva () { return lay; } public String [] getWidgets () { java.util.Vector vecWidg = new java.util.Vector (); for (int rr = 0; rr < nRows(); rr ++) for (int cc = 0; cc < nColumns(); cc ++) { String name = widgetAt (rr, cc); if (name.length() > 0 && !name.equals(EXPAND_HORIZONTAL) && !name.equals(EXPAND_VERTICAL)) vecWidg.add (name); } // pasarlo a array String [] arrWidg = new String [vecWidg.size ()]; for (int ii = 0; ii < arrWidg.length; ii ++) arrWidg[ii] = (String) vecWidg.get (ii); return arrWidg; } /** * Adds the specified component with the specified name */ public void addLayoutComponent(String name, Component comp) { log.dbg (2, "addLayoutComponent", name + " compName (" + comp.getName () + ")"); componentHTable.put(name, new widgetInfo (name, comp)); isPrecalculated = false; } /** * Removes the specified component from the layout. * @param comp the component to be removed */ public void removeLayoutComponent(Component comp) { // componentHTable.remove(comp); } /** * Calculates the preferred size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out */ public Dimension preferredLayoutSize(Container parent) { ///*EXPERIMENT!!!*/invalidatePreCalc (); Dimension di = getLayoutSize(parent, true); log.dbg (2, "preferredLayoutSize", lay.getName() + " preferredLayoutSize (" + di.width + ", " + di.height + ")"); //(o) TODO_javaj_layingOut Problem: preferredLayoutSize //19.04.2009 19:50 Problem: preferredLayoutSize is called when pack and after that no more // layouts data dependent like slider (don't know if horizontal or vertical) have problems // Note: this is not just a problem of EvaLayout but of all layout managers //log.severe ("SEVERINIO!"); return di; } /** * Calculates the minimum size dimensions for the specified * panel given the components in the specified parent container. * @param parent the component to be laid out */ public Dimension minimumLayoutSize(Container parent) { Dimension di = getLayoutSize(parent, false); log.dbg (2, "minimumLayoutSize", lay.getName() + " minimumLayoutSize (" + di.width + ", " + di.height + ")"); return di; } /** *calculating layout size (minimum or preferred). */ protected Dimension getLayoutSize(Container parent, boolean isPreferred) { log.dbg (2, "getLayoutSize", lay.getName()); precalculateAll (); // In precalculateAll the methods minWidthOfColumn and minHeightOfRow // does not evaluate expandable components since these might use other columns. // But in order to calculate the minimum or preferred total size we need this information. // In these cases we have to calculate following : if the sum of the sizes of the // columns that the component occupies is less that the minimum/preferred size of // the component then we add the difference to the total width // We evaluate this ONLY for those components that could be expanded! // for example // // NO COMPONENT HAS TO COMPONENTS comp1 and comp3 // BE RECALCULED HAS TO BE RECALCULED // --------------------- ------------------------ // grid, 160 , A grid, 160 , X // A , comp1 , - A , comp1 , - // A , comp2 , comp3 X , comp2 , comp3 // int [] extraCol = new int [nColumns ()]; int [] extraRow = new int [nRows ()]; int [] Hdim = isPreferred ? HdimPref: HdimMin; int [] Vdim = isPreferred ? VdimPref: VdimMin; //System.err.println ("PARLANT DE " + lay.getName () + " !!!"); // for all components ... Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { boolean someExpan = false; String key = (String) enu.nextElement(); widgetInfo wi = (widgetInfo) componentHTable.get(key); if (! wi.isLaidOut) continue; Dimension csiz = (isPreferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); log.dbg (2, "getLayoutSize", wi.name + " dim (" + csiz.width + ", " + csiz.height + ")"); // some column expandable ? // someExpan = false; for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) if (headType(columnHeader(cc)) == HEADER_EXPAND) { someExpan = true; break; } if (someExpan) { // sum of all columns that this component occupy int sum = 0; for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) sum += (Hdim[cc] + extraCol[cc]); // distribute it in all columns to be salomonic int resto = csiz.width - sum; if (resto > 0) { if (wi.posCol0 == wi.posCol1) { // System.err.println ("Resto X " + resto + " de " + wi.name + " en la " + wi.posCol0 + " veniendo de csiz.width " + csiz.width + " y sum " + sum + " que repahartimos en " + (1 + wi.posCol1 - wi.posCol0) + " parates tenahamos una estra de " + extraCol[wi.posCol0]); } for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++) extraCol[cc] = resto / (1 + wi.posCol1 - wi.posCol0); } } // some row expandable ? // someExpan = false; for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) if (headType(rowHeader(rr)) == HEADER_EXPAND) { someExpan = true; break; } if (someExpan) { // sum of all height (rows) that this component occupy int sum = 0; for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) sum += (Vdim[rr] + extraRow[rr]); // distribute it in all columns to be salomonic int resto = csiz.height - sum; if (resto > 0) { for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++) extraRow[rr] = resto / (1 + wi.posRow1 - wi.posRow0); } } } int tot_width = 0; for (int cc = 0; cc < nColumns(); cc ++) { tot_width += (Hdim[cc] + extraCol[cc]); } int tot_height = 0; for (int rr = 0; rr < nRows(); rr ++) { tot_height += Vdim[rr] + extraRow[rr]; } Insets insets = (parent != null) ? parent.getInsets(): new Insets(0,0,0,0); tot_width += Hgap * (nColumns() - 1) + insets.left + insets.right + 2 * Hmargin; tot_height += Vgap * (nRows() - 1) + insets.top + insets.bottom + 2 * Vmargin; log.dbg (2, "getLayoutSize", "returning tot_width " + tot_width + ", tot_height " + tot_height); // System.out.println ("getLayoutSize pref=" + isPreferred + " nos sale (" + tot_width + ", " + tot_height + ")"); return new Dimension (tot_width, tot_height); } private String columnHeader(int ncol) { return lay.getValue(1, ncol + 1).toUpperCase (); } private String rowHeader(int nrow) { return lay.getValue(2 + nrow, 0).toUpperCase (); } private String widgetAt(int nrow, int ncol) { return lay.getValue (nrow + 2, ncol + 1); } private widgetInfo theComponent(String cellName) { if (cellName.length() == 0 || cellName.equals(EXPAND_HORIZONTAL) || cellName.equals(EXPAND_VERTICAL)) return null; widgetInfo wi = (widgetInfo) componentHTable.get(cellName); if (wi == null) log.severe ("theComponent", "Component " + cellName + " not found in the container laying out " + lay.getName () + "!"); return wi; } private int minWidthOfColumn (int ncol, boolean preferred) { // el componente ma's ancho de la columna int maxwidth = 0; for (int rr = 0; rr < nRows(); rr ++) { String name = widgetAt (rr, ncol); widgetInfo wi = theComponent (name); if (wi != null) { if (widgetAt (rr, ncol+1).equals(EXPAND_HORIZONTAL)) continue; // widget occupies more columns so do not compute it Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); maxwidth = Math.max (maxwidth, csiz.width); } } //19.09.2010 Workaround //in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail! return maxwidth > MAX_SIZE_DX ? MAX_SIZE_DX : maxwidth; } private int minHeightOfRow (int nrow, boolean preferred) { // el componente ma's alto de la columna int maxheight = 0; for (int cc = 0; cc < nColumns(); cc ++) { String name = widgetAt (nrow, cc); widgetInfo wi = theComponent (name); if (wi != null) { if (widgetAt (nrow+1, cc).equals(EXPAND_VERTICAL)) continue; // widget occupies more rows so do not compute it Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize(); maxheight = Math.max (maxheight, csiz.height); } } //19.09.2010 Workaround //in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail! return maxheight > MAX_SIZE_DY ? MAX_SIZE_DY : maxheight; } /** * Lays out the container in the specified container. * @param parent the component which needs to be laid out */ public void layoutContainer(Container parent) { //isPrecalculated = false; if (log.isDebugging(4)) log.dbg (4, "layoutContainer", lay.getName ()); precalculateAll (); synchronized (parent.getTreeLock()) { Insets insets = parent.getInsets(); //if (log.isDebugging(4)) // log.dbg (4, "layoutContainer", "insets left right =" + insets.left + ", " + insets.right + " top bottom " + insets.top + ", " + insets.bottom); // Total parent dimensions Dimension size = parent.getSize(); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "parent size =" + size.width + ", " + size.height); int repartH = size.width - (insets.left + insets.right) - fijoH; int repartV = size.height - (insets.top + insets.bottom) - fijoV; int [] HextraPos = new int [HdimPref.length]; int [] VextraPos = new int [VdimPref.length]; if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "repartH=" + repartH + " repartV=" + repartV); // repartir H if (columnsReparto.size() > 0) { repartH /= columnsReparto.size(); for (int ii = 0; ii < columnsReparto.size(); ii ++) { int indx = ((int []) columnsReparto.get (ii))[0]; HdimPref[indx] = repartH; for (int res = indx+1; res < nColumns(); res ++) HextraPos[res] += repartH; } } // repartir V if (rowsReparto.size() > 0) { repartV /= rowsReparto.size(); for (int ii = 0; ii < rowsReparto.size(); ii ++) { int indx = ((int []) rowsReparto.get (ii))[0]; VdimPref[indx] = repartV; for (int res = indx+1; res < nRows(); res ++) VextraPos[res] += repartV; } } // // for all components ... for (int ii = 0; ii < componentArray.size(); ii ++) // java.util.Enumeration enu = componentHTable.keys(); while (enu.hasMoreElements()) { String key = (String) enu.nextElement(); widgetInfo wi = (widgetInfo) componentHTable.get(key); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "element [" + key + "]"); // System.out.println ("componente " + wi.name); if (! wi.isLaidOut) continue; // System.out.println (" indices " + wi.posCol0 + " (" + Hpos[wi.posCol0] + " extras " + HextraPos[wi.posCol0] + ")"); int x = Hpos[wi.posCol0] + HextraPos[wi.posCol0]; int y = Vpos[wi.posRow0] + VextraPos[wi.posRow0]; int dx = 0; int dy = 0; //if (log.isDebugging(4)) // log.dbg (4, "SIGUEY", "1) y = " + y + " Vpos[wi.posRow0] = " + Vpos[wi.posRow0] + " VextraPos[wi.posRow0] = " + VextraPos[wi.posRow0]); for (int mm = wi.posCol0; mm <= wi.posCol1; mm ++) { if (mm != wi.posCol0) dx += Hgap; dx += HdimPref[mm]; } for (int mm = wi.posRow0; mm <= wi.posRow1; mm ++) { if (mm != wi.posRow0) dy += Vgap; dy += VdimPref[mm]; } if (x < 0 || y < 0 || dx < 0 || dy < 0) { //Disable this warning because it happens very often when minimizing the window etc //log.warn ("layoutContainer", "component not laid out! [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")"); continue; } wi.comp.setBounds(x, y, dx, dy); if (log.isDebugging(4)) log.dbg (4, "layoutContainer", "vi.name [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")"); } } // end synchronized } // LayoutManager2 ///////////////////////////////////////////////////////// /** * This method make no sense in this layout, the constraints are not per component * but per column and rows. Since this method is called when adding components through * the method add(String, Component) we implement it as if constraints were the name */ public void addLayoutComponent(Component comp, Object constraints) { addLayoutComponent((String) constraints, comp); } /** * Returns the maximum size of this component. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Returns the alignment along the x axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentX(Container target) { return 0.5f; } /** * Returns the alignment along the y axis. This specifies how * the component would like to be aligned relative to other * components. The value should be a number between 0 and 1 * where 0 represents alignment along the origin, 1 is aligned * the furthest away from the origin, 0.5 is centered, etc. */ public float getLayoutAlignmentY(Container target) { return 0.5f; } /** * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. */ public void invalidateLayout(Container target) { invalidatePreCalc(); } public void invalidatePreCalc() { isPrecalculated = false; } }
Java
pizzasys ======== A system for pizzerias
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2013 by # Erwin Marsi and Tilburg University # This file is part of the Pycornetto package. # Pycornetto is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # Pycornetto is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """ # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi <e.marsi@gmail.com>' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """to prevent optparse from messing up the epilog text""" def format_epilog(self, epilog): return epilog or "" def format_description(self, description): return description.lstrip() epilog = """ Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask("pijp")' | cornetto-client.py $ cornetto-client.py <input >output """ try: parser = OptionParser(description=__doc__, version="%(prog)s version " + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version="%(prog)s version " + __version__) parser.add_option("-a", "--ask", action='store_true', help="assume all commands are input the 'ask' function, " "- so you can type 'query' instead of 'ask(\"query\") - '" "but online help is no longer accessible" ) parser.add_option("-H", "--host", default="localhost:5204", metavar="HOST[:PORT]", help="name or IP address of host (default is 'localhost') " "optionally followed by a port number " "(default is 5204)") parser.add_option('-n', '--no-pretty-print', dest="pretty_print", action='store_false', help="turn off pretty printing of output " "(default when standard input is a file)") parser.add_option("-p", "--port", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest="pretty_print", action='store_true', help="turn on pretty printing of output " "(default when standard input is a tty)") parser.add_option("-e", "--encoding", default="utf8", metavar="utf8,latin1,ascii,...", help="character encoding of output (default is utf8)") parser.add_option('-V', '--verbose', action='store_true', help="verbose output for debugging") (opts, args) = parser.parse_args() if opts.host.startswith("http://"): opts.host = opts.host[7:] try: host, port = opts.host.split(":")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = "http://" + (host or "localhost") try: port = int(port or 5204) except ValueError: exit("Error: %s is not a valid port number" % repr(port)) server = xmlrpclib.ServerProxy("%s:%s" % (host, port), encoding="utf-8", verbose=opts.verbose) try: eval('server.echo("test")') except SocketError, inst: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?" % ( inst, host, port), "See cornetto-server.py -h" exit(1) help_text = """ Type "?" to see his message. Type "help()" for help on available methods. Type "Ctrl-D" to exit. Restart with "cornetto-client.py -h" to see command line options. """ startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + "Copyright (c) Erwin Marsi\n" + help_text ) if stdin.isatty(): prompt = "$ " if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = "" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask("%s")' % c.strip()) else: process = lambda c: eval("server." + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers("fiets", "auto")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u"plafonni\xe8re"] encoder = lambda s: s.decode("unicode_escape").encode(opts.encoding, "backslashreplace") while True: try: command = raw_input(prompt) if command == "?": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print "\nSee you later alligator!" exit(0) except KeyboardInterrupt: print >>stderr, "\nInterrupted. Latest command may still run on the server though..." except SyntaxError: print >>stderr, "Error: invalid syntax" except NameError, inst: print >>stderr, "Error:", inst, "- use quotes?" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, "Error: %s\nCornetto server not running on %s:%s ?\n" % ( inst, host, port), "See cornetto-server.py -h"
Java
package tempconv // CToF converts a Celsius temperature to Fahrenheit func CToF(c Celsius) Fahrenheit { return Fahrenheit(c * 9 / 5 + 32) } // FToC converts s Fahrenheit temperature to Celsius func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
Java
const { nativeImage } = require('electron') const { resolve } = require('path') exports.size16 = nativeImage.createFromPath(resolve(__dirname, '../icon16.png')) exports.size16.setTemplateImage(true)
Java
package yio.tro.antiyoy.menu.customizable_list; import com.badlogic.gdx.graphics.g2d.BitmapFont; import yio.tro.antiyoy.gameplay.diplomacy.DiplomaticEntity; import yio.tro.antiyoy.menu.render.AbstractRenderCustomListItem; import yio.tro.antiyoy.menu.render.MenuRender; import yio.tro.antiyoy.menu.scenes.Scenes; import yio.tro.antiyoy.menu.scenes.gameplay.choose_entity.IDipEntityReceiver; import yio.tro.antiyoy.stuff.Fonts; import yio.tro.antiyoy.stuff.GraphicsYio; public class SimpleDipEntityItem extends AbstractSingleLineItem{ public DiplomaticEntity diplomaticEntity; public int backgroundColor; @Override protected BitmapFont getTitleFont() { return Fonts.smallerMenuFont; } @Override protected double getHeight() { return 0.07f * GraphicsYio.height; } @Override protected void onClicked() { Scenes.sceneChooseDiplomaticEntity.onDiplomaticEntityChosen(diplomaticEntity); } public void setDiplomaticEntity(DiplomaticEntity diplomaticEntity) { this.diplomaticEntity = diplomaticEntity; backgroundColor = getGameController().colorsManager.getColorByFraction(diplomaticEntity.fraction); setTitle("" + diplomaticEntity.capitalName); } @Override public AbstractRenderCustomListItem getRender() { return MenuRender.renderSimpleDipEntityItem; } }
Java
// ==++== // // Copyright (C) 2019 Matthias Fussenegger // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // ==--== namespace SimpleZIP_UI.Presentation.View.Model { /// <summary> /// Represents a list box item for the <see cref="MessageDigestPage"/>. /// </summary> public class MessageDigestModel { /// <summary> /// The name of the file whose hash value is to be displayed. /// </summary> public string FileName { get; } /// <summary> /// The physical location (full path) of the file. /// </summary> public string Location { get; } /// <summary> /// The calculated hash value of the file. /// </summary> public string HashValue { get; internal set; } /// <summary> /// Displays the location in the model if set to true. /// </summary> public BooleanModel IsDisplayLocation { get; set; } = false; /// <summary> /// Sets the color brush of the <see cref="FileName"/>. /// </summary> public SolidColorBrushModel FileNameColorBrush { get; set; } /// <summary> /// Constructs a new model for the ListBox in <see cref="MessageDigestPage"/>. /// </summary> /// <param name="fileName">The name of the file to be displayed.</param> /// <param name="location">The location of the file to be displayed.</param> /// <param name="hashValue">The hash value of the file to be displayed.</param> public MessageDigestModel(string fileName, string location, string hashValue) { FileName = fileName; Location = location; HashValue = hashValue; } } }
Java
#Region "Microsoft.VisualBasic::556146eee1abd2c1147f33071a728ef4, CLI_tools\eggHTS\CLI\Samples\LabelFree.vb" ' Author: ' ' asuka (amethyst.asuka@gcmodeller.org) ' xie (genetics@smrucc.org) ' xieguigang (xie.guigang@live.com) ' ' Copyright (c) 2018 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' ' This program is free software: you can redistribute it and/or modify ' it under the terms of the GNU General Public License as published by ' the Free Software Foundation, either version 3 of the License, or ' (at your option) any later version. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program. If not, see <http://www.gnu.org/licenses/>. ' /********************************************************************************/ ' Summaries: ' Module CLI ' ' Function: ExtractMatrix, LabelFreeMatrix, LabelFreeMatrixSplit, labelFreeTtest, MajorityProteinIDs ' matrixByInternal, matrixByUniprot, MatrixColRenames, MatrixNormalize, PerseusStatics ' PerseusTable ' ' ' /********************************************************************************/ #End Region Imports System.ComponentModel Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic.CommandLine Imports Microsoft.VisualBasic.CommandLine.Reflection Imports Microsoft.VisualBasic.Data.csv Imports Microsoft.VisualBasic.Data.csv.IO Imports Microsoft.VisualBasic.Language Imports Microsoft.VisualBasic.Linq Imports Microsoft.VisualBasic.Math.DataFrame.Impute Imports Microsoft.VisualBasic.MIME.Office.Excel Imports Microsoft.VisualBasic.Scripting.Runtime Imports Microsoft.VisualBasic.Text Imports SMRUCC.genomics.Analysis.HTS.Proteomics Imports SMRUCC.genomics.GCModeller.Workbench.ExperimentDesigner Imports csv = Microsoft.VisualBasic.Data.csv.IO.File Partial Module CLI ''' <summary> ''' 将perseus软件的输出转换为csv文档并且导出uniprot编号以方便进行注释 ''' </summary> ''' <param name="args"></param> ''' <returns></returns> <ExportAPI("/Perseus.Table")> <Usage("/Perseus.Table /in <proteinGroups.txt> [/out <out.csv>]")> <Group(CLIGroups.Samples_CLI)> Public Function PerseusTable(args As CommandLine) As Integer Dim [in] As String = args("/in") Dim out As String = args.GetValue("/out", [in].TrimSuffix & ".csv") Dim data As Perseus() = [in].LoadTsv(Of Perseus) Dim idlist As String() = data _ .Select(Function(prot) prot.ProteinIDs) _ .IteratesALL _ .Distinct _ .ToArray Dim uniprotIDs$() = idlist _ .Select(Function(s) s.Split("|"c, ":"c)(1)) _ .Distinct _ .ToArray Call idlist.SaveTo(out.TrimSuffix & ".proteinIDs.txt") Call uniprotIDs.SaveTo(out.TrimSuffix & ".uniprotIDs.txt") Return data.SaveTo(out).CLICode End Function <ExportAPI("/Perseus.Stat")> <Usage("/Perseus.Stat /in <proteinGroups.txt> [/out <out.csv>]")> <Group(CLIGroups.Samples_CLI)> Public Function PerseusStatics(args As CommandLine) As Integer Dim in$ = args("/in") Dim out As String = args.GetValue("/out", [in].TrimSuffix & ".perseus.Stat.csv") Dim data As Perseus() = [in].LoadTsv(Of Perseus) Dim csv As New csv Call csv.AppendLine({"MS/MS", CStr(Perseus.TotalMSDivideMS(data))}) Call csv.AppendLine({"Peptides", CStr(Perseus.TotalPeptides(data))}) Call csv.AppendLine({"ProteinGroups", CStr(data.Length)}) Return csv.Save(out, Encodings.ASCII).CLICode End Function <ExportAPI("/Perseus.MajorityProteinIDs")> <Usage("/Perseus.MajorityProteinIDs /in <table.csv> [/out <out.txt>]")> <Description("Export the uniprot ID list from ``Majority Protein IDs`` row and generates a text file for batch search of the uniprot database.")> Public Function MajorityProteinIDs(args As CommandLine) As Integer With args <= "/in" Dim out$ = (args <= "/out") Or (.TrimSuffix & "-uniprotID.txt").AsDefault Dim table As Perseus() = .LoadCsv(Of Perseus) Dim major$() = table _ .Select(Function(protein) Return protein.Majority_proteinIDs End Function) _ .IteratesALL _ .Distinct _ .ToArray Return major _ .FlushAllLines(out) _ .CLICode End With End Function <ExportAPI("/labelFree.matrix")> <Usage("/labelFree.matrix /in <*.csv/*.xlsx> [/sheet <default=proteinGroups> /intensity /uniprot <uniprot.Xml> /organism <scientificName> /out <out.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function LabelFreeMatrix(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim isIntensity As Boolean = args("/intensity") Dim uniprot$ = args("/uniprot") Dim organism$ = args("/organism") Dim out$ = args("/out") Or $"{[in].TrimSuffix}.{If(isIntensity, "intensity", "iBAQ")}.csv" Dim table As EntityObject() = EntityObject _ .LoadDataSet([in].ReadTableAuto(args("/sheet") Or "proteinGroups")) _ .ToArray If uniprot.FileExists Then Return table.matrixByUniprot(uniprot, organism, isIntensity) _ .SaveTo(out) _ .CLICode Else ' 没有额外的信息,则尝试使用内部的注释信息来完成 Return table.matrixByInternal(isIntensity) _ .SaveTo(out) _ .CLICode End If End Function <Extension> Private Function matrixByInternal(table As EntityObject(), isIntensity As Boolean) As DataSet() Dim getID As Func(Of EntityObject, String) If table(0).Properties.ContainsKey("Fasta headers") Then getID = Function(x) Dim headerID = x("Fasta headers").Split("|"c).ElementAtOrDefault(1) If headerID.StringEmpty Then Return x.ID.StringSplit("\s*;\s*")(0) Else Return headerID End If End Function Else getID = Function(x) x.ID.StringSplit("\s*;\s*")(0) End If Return table.ExtractMatrix(getID, isIntensity) End Function <Extension> Private Function ExtractMatrix(table As EntityObject(), getID As Func(Of EntityObject, String), isIntensity As Boolean) As DataSet() Dim keyPrefix$ = "iBAQ " Or "Intensity ".When(isIntensity) Dim projectDataSet = Function(x As EntityObject) As DataSet Dim id As String = getID(x) Dim data = x.Properties _ .Where(Function(c) Return InStr(c.Key, keyPrefix) > 0 End Function) _ .ToDictionary _ .AsNumeric Return New DataSet With { .ID = id, .Properties = data } End Function Return table.Select(projectDataSet).ToArray End Function <Extension> Private Function matrixByUniprot(table As EntityObject(), xml$, organism$, isIntensity As Boolean) As DataSet() Throw New NotImplementedException End Function ''' <summary> ''' 计算差异蛋白 ''' </summary> ''' <param name="args"></param> ''' <returns></returns> <ExportAPI("/labelFree.t.test")> <Usage("/labelFree.t.test /in <matrix.csv> /sampleInfo <sampleInfo.csv> /control <groupName> /treatment <groupName> [/significant <t.test/AB, default=t.test> /level <default=1.5> /p.value <default=0.05> /FDR <default=0.05> /out <out.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function labelFreeTtest(args As CommandLine) As Integer Dim data As DataSet() = DataSet.LoadDataSet(args <= "/in") _ .SimulateMissingValues(byRow:=False, infer:=InferMethods.Min) _ .TotalSumNormalize _ .ToArray Dim level# = args.GetValue("/level", 1.5) Dim pvalue# = args.GetValue("/p.value", 0.05) Dim FDR# = args.GetValue("/FDR", 0.05) Dim out$ = args.GetValue("/out", (args <= "/in").TrimSuffix & ".log2FC.t.test.csv") Dim sampleInfo As SampleInfo() = (args <= "/sampleInfo").LoadCsv(Of SampleInfo) Dim designer As New AnalysisDesigner With { .Controls = args <= "/control", .Treatment = args <= "/treatment" } Dim usingSignificantAB As Boolean = (args("/significant") Or "t.test") = "AB" Dim DEPs As DEP_iTraq() = data.logFCtest(designer, sampleInfo, level, pvalue, FDR, significantA:=usingSignificantAB) Return DEPs _ .ToArray _ .SaveDataSet(out) _ .CLICode End Function <ExportAPI("/labelFree.matrix.split")> <Usage("/labelFree.matrix.split /in <matrix.csv> /sampleInfo <sampleInfo.csv> /designer <analysis_designer.csv> [/out <directory>]")> <Group(CLIGroups.LabelFreeTool)> Public Function LabelFreeMatrixSplit(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim out$ = args("/out") Or $"{[in].TrimSuffix}.matrix/" Dim matrix As DataSet() = DataSet.LoadDataSet([in]).ToArray Dim sampleInfo As SampleInfo() = (args <= "/sampleInfo").LoadCsv(Of SampleInfo) Dim designer As AnalysisDesigner() = (args <= "/designer").LoadCsv(Of AnalysisDesigner) For Each analysis As AnalysisDesigner In designer Dim controls = sampleInfo.SampleIDs(analysis.Controls) Dim treatments = sampleInfo.SampleIDs(analysis.Treatment) Dim subMatrix As DataSet() = Iterator Function(projection As String()) As IEnumerable(Of DataSet) For Each protein In matrix Yield protein.SubSet(projection) Next End Function(controls + treatments).ToArray Dim controlGroup = sampleInfo.TakeGroup(analysis.Controls).AsList Dim treatmentGroup As SampleInfo() = sampleInfo.TakeGroup(analysis.Treatment) Names(subMatrix) = controlGroup + treatmentGroup Call subMatrix.SaveTo($"{out}/{analysis.Title}.csv") Next Return 0 End Function <ExportAPI("/names")> <Usage("/names /in <matrix.csv> /sampleInfo <sampleInfo.csv> [/out <out.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function MatrixColRenames(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim out$ = args("/out") Or $"{[in].TrimSuffix}.sample_name.csv" Dim matrix As DataSet() = DataSet.LoadDataSet([in]).ToArray Dim sampleInfo As SampleInfo() = (args <= "/sampleInfo").LoadCsv(Of SampleInfo) Names(matrix) = sampleInfo Return matrix.SaveTo(out).CLICode End Function <ExportAPI("/Matrix.Normalization")> <Usage("/Matrix.Normalization /in <matrix.csv> /infer <min/avg, default=min> [/out <normalized.csv>]")> <Group(CLIGroups.LabelFreeTool)> Public Function MatrixNormalize(args As CommandLine) As Integer Dim in$ = args <= "/in" Dim infer$ = args("/infer") Or "min" Dim out$ = args("/out") Or $"{[in].TrimSuffix}.normalized.csv" Dim matrix As DataSet() = DataSet.LoadDataSet([in]).ToArray Dim method As InferMethods If infer.TextEquals("min") Then method = InferMethods.Min Else method = InferMethods.Average End If matrix = matrix _ .SimulateMissingValues(byRow:=False, infer:=method) _ .TotalSumNormalize _ .ToArray Return matrix.SaveTo(out).CLICode End Function End Module
Java
#!/usr/bin/env bash INTERFACE="${INTERFACE:-wlo1}" systemctl enable netctl-auto@$INTERFACE systemctl --user enable maintenance.timer systemctl --user enable battery.timer
Java
package standalone_tools; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Set; import framework.DataQuery; import framework.DiffComplexDetector; import framework.DiffComplexDetector.SPEnrichment; import framework.DiffSeedCombDetector; import framework.QuantDACOResultSet; import framework.Utilities; /** * CompleXChange cmd-tool * @author Thorsten Will */ public class CompleXChange { static String version_string = "CompleXChange 1.01"; private static String path_group1 = "[GROUP1-FOLDER]"; private static String path_group2 = "[GROUP2-FOLDER]"; private static Map<String, QuantDACOResultSet> group1; private static Map<String, QuantDACOResultSet> group2; private static String path_seed = "no seed file defined"; private static Set<String> seed = null; private static String output_folder; private static double FDR = 0.05; private static boolean parametric = false; private static boolean paired = false; private static boolean incorporate_supersets = false; private static double min_variant_fraction = 0.75; private static boolean human_readable = false; private static boolean also_seedcomb_calcs = false; private static boolean also_seed_enrich = false; private static boolean filter_allosome = false; private static int no_threads = Math.max(Runtime.getRuntime().availableProcessors() / 2, 1); // assuming HT/SMT systems /** * Reads all matching output pairs of JDACO results/major transcripts from a certain folder: * [folder]/[sample-string]_complexes.txt(.gz) and [folder]/[sample-string]_major-transcripts.txt(.gz) * @param folder * @return */ public static Map<String, QuantDACOResultSet> readQuantDACOComplexes(String folder) { Map<String, QuantDACOResultSet> data = new HashMap<>(); for (File f:Utilities.getAllSuffixMatchingFilesInSubfolders(folder, "_major-transcripts.txt")) { String gz = ""; if (f.getName().endsWith(".gz")) gz = ".gz"; String pre = f.getAbsolutePath().split("_major-transcripts")[0]; String sample = f.getName().split("_major-transcripts")[0]; QuantDACOResultSet qdr = new QuantDACOResultSet(pre + "_complexes.txt" + gz, seed, pre + "_major-transcripts.txt" + gz); data.put(sample, qdr); } return data; } /** * Prints the help message */ public static void printHelp() { System.out.println("usage: java -jar CompleXChange.jar ([OPTIONS]) [GROUP1-FOLDER] [GROUP2-FOLDER] [OUTPUT-FOLDER]"); System.out.println(); System.out.println("[OPTIONS] (optional) :"); System.out.println(" -fdr=[FDR] : false discovery rate (default: 0.05)"); System.out.println(" -mf=[MIN_VAR_FRACTION] : fraction of either group a complex must be part of to be considered in the analysis (default: 0.75)"); System.out.println(" -s=[SEED-FILE] : file listing proteins around which the complexes are centered, e.g. seed file used for JDACO complex predictions (default: none)"); System.out.println(" -t=[#threads] : number of threads to be used (default: #cores/2)"); System.out.println(" -nd : assume normal distribution when testing (default: no assumption, non-parametric tests applied)"); System.out.println(" -p : assume paired/dependent data (default: unpaired/independent tests applied)"); System.out.println(" -ss : also associate supersets in the analyses (default: no supersets)"); System.out.println(" -enr : determine seed proteins enriched in up/down-regulated complexes (as in GSEA)"); System.out.println(" -sc : additional analysis based on seed combinations rather than sole complexes (as in GSEA)"); System.out.println(" -hr : additionally output human readable files with gene names and rounded numbers (default: no output)"); System.out.println(" -f : filter complexes with allosome proteins (default: no filtering)"); System.out.println(); System.out.println("[GROUPx-FOLDER] :"); System.out.println(" Standard PPIXpress/JDACO-output is read from those folders. JDACO results and major transcripts are needed."); System.out.println(); System.out.println("[OUTPUT-FOLDER]"); System.out.println(" The outcome is written to this folder. If it does not exist, it is created."); System.out.println(); System.exit(0); } /** * Prints the version of the program */ public static void printVersion() { System.out.println(version_string); System.exit(0); } /** * Parse arguments * @param args */ public static void parseInput(String[] args) { for (String arg:args) { // help needed? if (arg.equals("-h") || arg.equals("-help")) printHelp(); // output version else if (arg.equals("-version")) printVersion(); // parse FDR else if (arg.startsWith("-fdr=")) FDR = Double.parseDouble(arg.split("=")[1]); // parse min_variant_fraction else if (arg.startsWith("-mf=")) min_variant_fraction = Double.parseDouble(arg.split("=")[1]); // add seed file else if (arg.startsWith("-s=")) { path_seed = arg.split("=")[1]; seed = Utilities.readEntryFile(path_seed); if (seed == null) System.exit(1); // error will be thrown by the utility-function if (seed.isEmpty()) { System.err.println("Seed file " + path_seed + " is empty."); System.exit(1); } } // parse #threads else if (arg.startsWith("-t=")) no_threads = Math.max(Integer.parseInt(arg.split("=")[1]), 1); // parametric? else if (arg.equals("-nd")) parametric = true; // paired? else if (arg.equals("-p")) paired = true; // supersets? else if (arg.equals("-ss")) incorporate_supersets = true; // seed combinations? else if (arg.equals("-sc")) also_seedcomb_calcs = true; // seed enrichment? else if (arg.equals("-enr")) also_seed_enrich = true; // output human readable files? else if (arg.equals("-hr")) human_readable = true; // filter allosome proteins? else if (arg.equals("-f")) filter_allosome = true; // read groupwise input else if (group1 == null) { path_group1 = arg; if (!path_group1.endsWith("/")) path_group1 += "/"; group1 = readQuantDACOComplexes(path_group1); } else if (group2 == null) { path_group2 = arg; if (!path_group2.endsWith("/")) path_group2 += "/"; group2 = readQuantDACOComplexes(path_group2); } // set output-folder else if (output_folder == null) { output_folder = arg; if (!output_folder.endsWith("/")) output_folder += "/"; } } // some final checks if (group1 == null || group1.isEmpty() || group2 == null || group2.isEmpty()) { if (group1 == null || group1.isEmpty()) System.err.println(path_group1 + " does not exist or contains no useable data."); if (group2 == null || group2.isEmpty()) System.err.println(path_group2 + " does not exist or contains no useable data."); System.exit(1); } if (group1.size() < 2 || group2.size() < 2) { if (group1.size() < 2) System.err.println(path_group1 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation."); if (group2.size() < 2) System.err.println(path_group2 + " does not contain enough data. At least two samples per group are needed for a statistical evaluation."); System.exit(1); } if (output_folder == null) { System.err.println("Please add an output folder."); System.exit(1); } // check for invalid usage of seedcomb mode if (also_seedcomb_calcs && seed == null) { also_seedcomb_calcs = false; System.out.println("Analysis of seed combination variants in complexes requires a seed file, this additional analysis is skipped."); } if (also_seed_enrich && seed == null) { also_seed_enrich = false; System.out.println("Analysis of seed protein enrichment in complexes requires a seed file, this additional analysis is skipped."); } } public static void main(String[] args) { if (args.length == 1 && args[0].equals("-version")) printVersion(); if (args.length < 3) { printHelp(); } // parse cmd-line and set all parameters try { parseInput(args); } catch (Exception e) { System.out.println("Something went wrong while reading the command-line, please check your input!"); System.out.println(); printHelp(); } // preface if (group1.size() < 5 || group2.size() < 5) { System.out.println("Computations will run as intended, but be aware that at least five samples per group are recommended to gather meaningful results."); } System.out.println("Seed: " + path_seed); System.out.println("FDR: " + FDR); String test = "Wilcoxon rank sum test (unpaired, non-parametric)"; if (paired && parametric) test = "paired t-test (paired, parametric)"; else if (paired) test = "Wilcoxon signed-rank test (paired, non-parametric)"; else if (parametric) test = "Welch's unequal variances t-test (unpaired, parametric)"; System.out.println("Statistical test: " + test); System.out.println("Min. fraction: " + min_variant_fraction); System.out.println("Incorporate supersets: " + (incorporate_supersets ? "yes" : "no")); if (filter_allosome) { System.out.print("Filtering of complexes with allosome proteins enabled. Downloading data ... "); String db = DataQuery.getEnsemblOrganismDatabaseFromProteins(group1.values().iterator().next().getAbundantSeedProteins()); DataQuery.getAllosomeProteins(db); System.out.println("done."); } System.out.println(); // computations boolean output_to_write = false; System.out.println("Processing " + path_group1 + " (" + group1.keySet().size() + ") vs " + path_group2 + " (" + group2.keySet().size() + ") ..."); System.out.flush(); DiffComplexDetector dcd = new DiffComplexDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome); if (seed != null) System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() +" (" + dcd.getSignSortedVariants(false, false).size() + " seed combination variants) significant."); else System.out.println(dcd.getRawPValues().size() + " complexes tested, " + dcd.getSignificanceSortedComplexes().size() + " significant."); System.out.flush(); output_to_write = !dcd.getSignificanceSortedComplexes().isEmpty(); DiffSeedCombDetector dscd = null; if (also_seedcomb_calcs) { dscd = new DiffSeedCombDetector(group1, group2, FDR, parametric, paired, incorporate_supersets, min_variant_fraction, no_threads, filter_allosome); System.out.println(dscd.getVariantsRawPValues().size() + " seed combinations tested, " + dscd.getSignificanceSortedVariants().size() + " significant."); if (!dscd.getSignificanceSortedVariants().isEmpty()) output_to_write = true; System.out.flush(); } SPEnrichment spe = null; if (seed == null && also_seed_enrich) { System.out.println("Please specify a seed protein file if seed protein enrichment should be determined."); System.out.flush(); } else if (seed != null && also_seed_enrich) { System.out.println("Calculating seed protein enrichment with 10000 permutations to approximate null distribution and only considering seed proteins participating in at least 10 complexes."); System.out.flush(); spe = dcd.calculateSPEnrichment(FDR, 10000, 10); if (!spe.getSignificanceSortedSeedProteins().isEmpty()) output_to_write = true; } /* * write file-output */ if (!output_to_write) { System.out.println("Since there is nothing to report, no output is written."); System.exit(0); } // check if output-folder exists, otherwise create it File f = new File(output_folder); if (!f.exists()) f.mkdir(); // write output files System.out.println("Writing results ..."); dcd.writeSignSortedComplexes(output_folder + "diff_complexes.txt", false); if (seed != null) { dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes.txt", false); if (also_seedcomb_calcs) dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations.txt", false); if (also_seed_enrich) spe.writeSignificantSeedProteins(output_folder + "enriched_seed_proteins.txt"); } if (human_readable) { System.out.println("Retrieving data on gene names ..."); System.out.flush(); System.out.println("Output human readable results ..."); dcd.writeSignSortedComplexes(output_folder + "diff_complexes_hr.txt", true); if (seed != null) { dcd.writeSignSortedVariants(output_folder + "diff_seedcomb_in_complexes_hr.txt", true); if (also_seedcomb_calcs) dscd.writeSignSortedVariants(output_folder + "diff_seed_combinations_hr.txt", true); } } } }
Java
// black-box testing package router_test import ( "testing" "github.com/kataras/iris" "github.com/kataras/iris/context" "github.com/kataras/iris/core/router" "github.com/kataras/iris/httptest" ) type testController struct { router.Controller } var writeMethod = func(c router.Controller) { c.Ctx.Writef(c.Ctx.Method()) } func (c *testController) Get() { writeMethod(c.Controller) } func (c *testController) Post() { writeMethod(c.Controller) } func (c *testController) Put() { writeMethod(c.Controller) } func (c *testController) Delete() { writeMethod(c.Controller) } func (c *testController) Connect() { writeMethod(c.Controller) } func (c *testController) Head() { writeMethod(c.Controller) } func (c *testController) Patch() { writeMethod(c.Controller) } func (c *testController) Options() { writeMethod(c.Controller) } func (c *testController) Trace() { writeMethod(c.Controller) } type ( testControllerAll struct{ router.Controller } testControllerAny struct{ router.Controller } // exactly same as All ) func (c *testControllerAll) All() { writeMethod(c.Controller) } func (c *testControllerAny) All() { writeMethod(c.Controller) } func TestControllerMethodFuncs(t *testing.T) { app := iris.New() app.Controller("/", new(testController)) app.Controller("/all", new(testControllerAll)) app.Controller("/any", new(testControllerAny)) e := httptest.New(t, app) for _, method := range router.AllMethods { e.Request(method, "/").Expect().Status(httptest.StatusOK). Body().Equal(method) e.Request(method, "/all").Expect().Status(httptest.StatusOK). Body().Equal(method) e.Request(method, "/any").Expect().Status(httptest.StatusOK). Body().Equal(method) } } type testControllerPersistence struct { router.Controller Data string `iris:"persistence"` } func (t *testControllerPersistence) Get() { t.Ctx.WriteString(t.Data) } func TestControllerPersistenceFields(t *testing.T) { data := "this remains the same for all requests" app := iris.New() app.Controller("/", &testControllerPersistence{Data: data}) e := httptest.New(t, app) e.GET("/").Expect().Status(httptest.StatusOK). Body().Equal(data) } type testControllerBeginAndEndRequestFunc struct { router.Controller Username string } // called before of every method (Get() or Post()). // // useful when more than one methods using the // same request values or context's function calls. func (t *testControllerBeginAndEndRequestFunc) BeginRequest(ctx context.Context) { t.Username = ctx.Params().Get("username") // or t.Params.Get("username") because the // t.Ctx == ctx and is being initialized before this "BeginRequest" } // called after every method (Get() or Post()). func (t *testControllerBeginAndEndRequestFunc) EndRequest(ctx context.Context) { ctx.Writef("done") // append "done" to the response } func (t *testControllerBeginAndEndRequestFunc) Get() { t.Ctx.Writef(t.Username) } func (t *testControllerBeginAndEndRequestFunc) Post() { t.Ctx.Writef(t.Username) } func TestControllerBeginAndEndRequestFunc(t *testing.T) { app := iris.New() app.Controller("/profile/{username}", new(testControllerBeginAndEndRequestFunc)) e := httptest.New(t, app) usernames := []string{ "kataras", "makis", "efi", "rg", "bill", "whoisyourdaddy", } doneResponse := "done" for _, username := range usernames { e.GET("/profile/" + username).Expect().Status(httptest.StatusOK). Body().Equal(username + doneResponse) e.POST("/profile/" + username).Expect().Status(httptest.StatusOK). Body().Equal(username + doneResponse) } }
Java
/* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2016 HydroloGIS (www.hydrologis.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package eu.geopaparazzi.library.profiles.objects; import android.os.Parcel; import android.os.Parcelable; import eu.geopaparazzi.library.network.download.IDownloadable; /** * Created by hydrologis on 19/03/18. */ public class ProfileOtherfiles extends ARelativePathResource implements Parcelable, IDownloadable { public String url = ""; public String modifiedDate = ""; public long size = -1; private String destinationPath = ""; public ProfileOtherfiles() { } protected ProfileOtherfiles(Parcel in) { url = in.readString(); modifiedDate = in.readString(); size = in.readLong(); destinationPath = in.readString(); } public static final Creator<ProfileOtherfiles> CREATOR = new Creator<ProfileOtherfiles>() { @Override public ProfileOtherfiles createFromParcel(Parcel in) { return new ProfileOtherfiles(in); } @Override public ProfileOtherfiles[] newArray(int size) { return new ProfileOtherfiles[size]; } }; @Override public long getSize() { return size; } @Override public String getUrl() { return url; } @Override public String getDestinationPath() { return destinationPath; } @Override public void setDestinationPath(String path) { destinationPath = path; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(url); dest.writeString(modifiedDate); dest.writeLong(size); dest.writeString(destinationPath); } }
Java
#from moderation import moderation #from .models import SuccessCase #moderation.register(SuccessCase)
Java
document.addEventListener("DOMContentLoaded", function(event) { if (/android|blackberry|iPhone|iPad|iPod|webOS/i.test(navigator.userAgent) === false) { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { el.parentNode.addEventListener('mouseenter', animateTypeText); el.parentNode.addEventListener('mouseleave', destroyTypeText); }); } else { var linkDescrs = document.querySelectorAll('.link-descr'); Array.prototype.forEach.call(linkDescrs, function(el, i) { removeClass(el, 'link-descr'); }); } }); var addClass = function(elem, add_class) { elem.setAttribute("class", elem.getAttribute("class") + ' ' + add_class); }; var removeClass = function(elem, rem_class) { var origClass = elem.getAttribute("class"); var remClassRegex = new Regexp("(\\s*)"+rem_class+"(\\s*)"); var classMatch = origClass.match(remClassRegex); var replaceString = ''; if (classMatch[1].length > 0 || classMatch[2].length > 0) { replaceString = ' '; } var newClass = origClass.replace(remClassRegex, replaceString); elem.setAttribute("class", newClass); }; var animateTypeText = function() { var elem = this; var typeArea = document.createElement("span"); typeArea.setAttribute("class", "link-subtext"); elem.insertBefore(typeArea, elem.querySelector("span:last-of-type")); setTimeout(addLetter(elem), 40); }; var addLetter = function(elem) { // if (elem.parentElement.querySelector(":hover") === elem) { var subtextSpan = elem.querySelector(".link-subtext"); var descrText = elem.querySelector(".link-descr").textContent; if (subtextSpan === null) { return; } var currentText = subtextSpan.textContent.slice(0,-1); var currentPos = currentText.length; subtextSpan.textContent = currentText + descrText.slice(currentPos, currentPos+1) + "\u258B"; if (currentText.length < descrText.length) { setTimeout(function(){addLetter(elem)}, 40); } // } }; var destroyTypeText = function() { var elem = this; elem.removeChild(elem.querySelector('.link-subtext')); };
Java
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- template designed by Marco Von Ballmoos --> <title>File Source for THead.php</title> <link rel="stylesheet" href="../media/stylesheet.css" /> </head> <body> <h1>Source for file THead.php</h1> <p>Documentation is available at <a href="../Elements/_Elements---Table---THead.php.html">THead.php</a></p> <div class="src-code"> <div class="src-code"><ol><li><div class="src-line"><a name="a1"></a><span class="src-php">&lt;?php</span></div></li> <li><div class="src-line"><a name="a2"></a><span class="src-doc">/**</span></div></li> <li><div class="src-line"><a name="a3"></a><span class="src-doc">&nbsp;*&nbsp;The&nbsp;&lt;thead&gt;&nbsp;tag&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;header&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.</span></div></li> <li><div class="src-line"><a name="a4"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a5"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;thead&nbsp;element&nbsp;should&nbsp;be&nbsp;used&nbsp;in&nbsp;conjunction&nbsp;with&nbsp;the&nbsp;tbody&nbsp;and&nbsp;tfoot&nbsp;elements.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a6"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;tbody&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;body&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table&nbsp;and&nbsp;the&nbsp;tfoot</span></div></li> <li><div class="src-line"><a name="a7"></a><span class="src-doc">&nbsp;*&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;footer&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a8"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt;&nbsp;&lt;tfoot&gt;&nbsp;must&nbsp;appear&nbsp;before&nbsp;&lt;tbody&gt;&nbsp;within&nbsp;a&nbsp;table,&nbsp;so&nbsp;that&nbsp;a&nbsp;browser</span></div></li> <li><div class="src-line"><a name="a9"></a><span class="src-doc">&nbsp;*&nbsp;can&nbsp;render&nbsp;the&nbsp;foot&nbsp;before&nbsp;receiving&nbsp;all&nbsp;the&nbsp;rows&nbsp;of&nbsp;data.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a10"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;Notice&nbsp;that&nbsp;these&nbsp;elements&nbsp;will&nbsp;not&nbsp;affect&nbsp;the&nbsp;layout&nbsp;of&nbsp;the&nbsp;table&nbsp;by&nbsp;default.</span></div></li> <li><div class="src-line"><a name="a11"></a><span class="src-doc">&nbsp;*&nbsp;However,&nbsp;you&nbsp;can&nbsp;use&nbsp;CSS&nbsp;to&nbsp;let&nbsp;these&nbsp;elements&nbsp;affect&nbsp;the&nbsp;table's&nbsp;layout.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a12"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-inlinetag">{@link&nbsp;http://www.w3schools.com/tags/tag_thead.asp&nbsp;}</span></div></li> <li><div class="src-line"><a name="a13"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a14"></a><span class="src-doc">&nbsp;*&nbsp;PHP&nbsp;version&nbsp;5</span></div></li> <li><div class="src-line"><a name="a15"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a16"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@example</span><span class="src-doc">&nbsp;&nbsp;&nbsp;simple.php&nbsp;How&nbsp;to&nbsp;use</span></div></li> <li><div class="src-line"><a name="a17"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@filesource</span></div></li> <li><div class="src-line"><a name="a18"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@category</span><span class="src-doc">&nbsp;&nbsp;Element</span></div></li> <li><div class="src-line"><a name="a19"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@package</span><span class="src-doc">&nbsp;&nbsp;&nbsp;Elements</span></div></li> <li><div class="src-line"><a name="a20"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@author</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;Jens&nbsp;Peters&nbsp;&lt;jens@history-archive.net&gt;</span></div></li> <li><div class="src-line"><a name="a21"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@copyright</span><span class="src-doc">&nbsp;2011&nbsp;Jens&nbsp;Peters</span></div></li> <li><div class="src-line"><a name="a22"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@license</span><span class="src-doc">&nbsp;&nbsp;&nbsp;http://www.gnu.org/licenses/lgpl.html&nbsp;GNU&nbsp;LGPL&nbsp;v3</span></div></li> <li><div class="src-line"><a name="a23"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@version</span><span class="src-doc">&nbsp;&nbsp;&nbsp;1.1</span></div></li> <li><div class="src-line"><a name="a24"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@link</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://launchpad.net/htmlbuilder</span></div></li> <li><div class="src-line"><a name="a25"></a><span class="src-doc">&nbsp;*/</span></div></li> <li><div class="src-line"><a name="a26"></a>namespace&nbsp;<span class="src-id">HTMLBuilder</span>\<span class="src-id">Elements</span>\<span class="src-id"><a href="../Elements/General/Table.html">Table</a></span><span class="src-sym">;</span></div></li> <li><div class="src-line"><a name="a27"></a>use&nbsp;<span class="src-id">HTMLBuilder</span>\<span class="src-id">Elements</span>\<span class="src-id"><a href="../Elements/Base/Root.html">Root</a></span><span class="src-sym">;</span></div></li> <li><div class="src-line"><a name="a28"></a>&nbsp;</div></li> <li><div class="src-line"><a name="a29"></a><span class="src-doc">/**</span></div></li> <li><div class="src-line"><a name="a30"></a><span class="src-doc">&nbsp;*&nbsp;The&nbsp;&lt;thead&gt;&nbsp;tag&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;header&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.</span></div></li> <li><div class="src-line"><a name="a31"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a32"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;thead&nbsp;element&nbsp;should&nbsp;be&nbsp;used&nbsp;in&nbsp;conjunction&nbsp;with&nbsp;the&nbsp;tbody&nbsp;and&nbsp;tfoot&nbsp;elements.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a33"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;The&nbsp;tbody&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;body&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table&nbsp;and&nbsp;the&nbsp;tfoot</span></div></li> <li><div class="src-line"><a name="a34"></a><span class="src-doc">&nbsp;*&nbsp;element&nbsp;is&nbsp;used&nbsp;to&nbsp;group&nbsp;the&nbsp;footer&nbsp;content&nbsp;in&nbsp;an&nbsp;HTML&nbsp;table.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a35"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt;&nbsp;&lt;tfoot&gt;&nbsp;must&nbsp;appear&nbsp;before&nbsp;&lt;tbody&gt;&nbsp;within&nbsp;a&nbsp;table,&nbsp;so&nbsp;that&nbsp;a&nbsp;browser</span></div></li> <li><div class="src-line"><a name="a36"></a><span class="src-doc">&nbsp;*&nbsp;can&nbsp;render&nbsp;the&nbsp;foot&nbsp;before&nbsp;receiving&nbsp;all&nbsp;the&nbsp;rows&nbsp;of&nbsp;data.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a37"></a><span class="src-doc">&nbsp;*&nbsp;&lt;p&gt;Notice&nbsp;that&nbsp;these&nbsp;elements&nbsp;will&nbsp;not&nbsp;affect&nbsp;the&nbsp;layout&nbsp;of&nbsp;the&nbsp;table&nbsp;by&nbsp;default.</span></div></li> <li><div class="src-line"><a name="a38"></a><span class="src-doc">&nbsp;*&nbsp;However,&nbsp;you&nbsp;can&nbsp;use&nbsp;CSS&nbsp;to&nbsp;let&nbsp;these&nbsp;elements&nbsp;affect&nbsp;the&nbsp;table's&nbsp;layout.&lt;/p&gt;</span></div></li> <li><div class="src-line"><a name="a39"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-inlinetag">{@link&nbsp;http://www.w3schools.com/tags/tag_thead.asp&nbsp;}</span></div></li> <li><div class="src-line"><a name="a40"></a><span class="src-doc">&nbsp;*&nbsp;</span></div></li> <li><div class="src-line"><a name="a41"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@category</span><span class="src-doc">&nbsp;&nbsp;&nbsp;Element</span></div></li> <li><div class="src-line"><a name="a42"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@example</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;simple.php&nbsp;see&nbsp;HOW&nbsp;TO&nbsp;USE</span></div></li> <li><div class="src-line"><a name="a43"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@example</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;debug.php&nbsp;see&nbsp;HOW&nbsp;TO&nbsp;DEBUG</span></div></li> <li><div class="src-line"><a name="a44"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@package</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;Elements</span></div></li> <li><div class="src-line"><a name="a45"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@subpackage</span><span class="src-doc">&nbsp;General</span></div></li> <li><div class="src-line"><a name="a46"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@author</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Jens&nbsp;Peters&nbsp;&lt;jens@history-archiv.net&gt;</span></div></li> <li><div class="src-line"><a name="a47"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@license</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;http://www.gnu.org/licenses/lgpl.html&nbsp;GNU&nbsp;LGPL&nbsp;v3</span></div></li> <li><div class="src-line"><a name="a48"></a><span class="src-doc">&nbsp;*&nbsp;</span><span class="src-doc-coretag">@link</span><span class="src-doc">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;http://launchpad.net/htmlbuilder</span></div></li> <li><div class="src-line"><a name="a49"></a><span class="src-doc">&nbsp;*/</span></div></li> <li><div class="src-line"><a name="a50"></a><span class="src-key">class&nbsp;</span><a href="../Elements/General/THead.html">THead</a>&nbsp;<span class="src-key">extends&nbsp;</span><a href="../Elements/General/RootRow.html">RootRow</a>&nbsp;<span class="src-sym">{</span></div></li> <li><div class="src-line"><a name="a51"></a>&nbsp;</div></li> <li><div class="src-line"><a name="a52"></a>&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-key">public&nbsp;</span><span class="src-key">function&nbsp;</span><a href="../Elements/General/THead.html#methodinitElement">initElement</a><span class="src-sym">(</span><span class="src-sym">)&nbsp;</span><span class="src-sym">{</span></div></li> <li><div class="src-line"><a name="a53"></a>&nbsp;</div></li> <li><div class="src-line"><a name="a54"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-var">$this</span><span class="src-sym">-&gt;</span><a href="../Elements/Base/Root.html#var$_allowedChildren">_allowedChildren</a>&nbsp;=&nbsp;<span class="src-key">array&nbsp;</span><span class="src-sym">(</span></div></li> <li><div class="src-line"><a name="a55"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-str">&quot;tr&quot;</span></div></li> <li><div class="src-line"><a name="a56"></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-sym">)</span><span class="src-sym">;</span></div></li> <li><div class="src-line"><a name="a57"></a>&nbsp;&nbsp;&nbsp;&nbsp;<span class="src-sym">}</span></div></li> <li><div class="src-line"><a name="a58"></a><span class="src-sym">}</span></div></li> </ol></div> </div> <p class="notes" id="credit"> Documentation generated on Sat, 22 Dec 2012 00:28:46 +0100 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.4</a> </p> </body> </html>
Java
package de.turnierverwaltung.control.settingsdialog; import java.awt.Dialog; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.sql.SQLException; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import de.turnierverwaltung.control.ExceptionHandler; import de.turnierverwaltung.control.MainControl; import de.turnierverwaltung.control.Messages; import de.turnierverwaltung.control.PropertiesControl; import de.turnierverwaltung.control.ratingdialog.DWZListToSQLITEControl; import de.turnierverwaltung.control.ratingdialog.ELOListToSQLITEControl; import de.turnierverwaltung.control.sqlite.SaveTournamentControl; import de.turnierverwaltung.model.TournamentConstants; import de.turnierverwaltung.view.settingsdialog.SettingsView; import say.swing.JFontChooser; public class ActionListenerSettingsControl { private final MainControl mainControl; private final SettingsControl esControl; private JDialog dialog; public ActionListenerSettingsControl(final MainControl mainControl, final SettingsControl esControl) { super(); this.mainControl = mainControl; this.esControl = esControl; addPropertiesActionListener(); } public void addActionListeners() { esControl.getEigenschaftenView().getFontChooserButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final JFontChooser fontChooser = esControl.getEigenschaftenView().getFontChooser(); fontChooser.setSelectedFont(mainControl.getPropertiesControl().getFont()); final int result = fontChooser.showDialog(esControl.getEigenschaftenView()); if (result == JFontChooser.OK_OPTION) { final Font selectedFont = fontChooser.getSelectedFont(); MainControl.setUIFont(selectedFont); mainControl.getPropertiesControl().setFont(selectedFont); mainControl.getPropertiesControl().writeProperties(); } } }); esControl.getEigenschaftenView().getOkButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { mainControl.getPropertiesControl().writeSettingsDialogProperties(dialog.getBounds().x, dialog.getBounds().y, dialog.getBounds().width, dialog.getBounds().height); dialog.dispose(); final PropertiesControl ppC = mainControl.getPropertiesControl(); final SettingsView settingsView = esControl.getEigenschaftenView(); ppC.setTableComumnBlack(settingsView.getBlackTextField().getText()); ppC.setTableComumnWhite(settingsView.getWhiteTextField().getText()); ppC.setTableComumnMeeting(settingsView.getMeetingTextField().getText()); ppC.setTableComumnNewDWZ(settingsView.getNewDWZTextField().getText()); ppC.setTableComumnOldDWZ(settingsView.getOldDWZTextField().getText()); ppC.setTableComumnNewELO(settingsView.getNewELOTextField().getText()); ppC.setTableComumnOldELO(settingsView.getOldELOTextField().getText()); ppC.setTableComumnPlayer(settingsView.getPlayerTextField().getText()); ppC.setTableComumnPoints(settingsView.getPointsTextField().getText()); ppC.setTableComumnRanking(settingsView.getRankingTextField().getText()); ppC.setTableComumnResult(settingsView.getResultTextField().getText()); ppC.setTableComumnSonnebornBerger(settingsView.getSbbTextField().getText()); ppC.setTableComumnRound(settingsView.getRoundTextField().getText()); ppC.setSpielfrei(settingsView.getSpielfreiTextField().getText()); if (mainControl.getPlayerListControl() != null) { mainControl.getPlayerListControl().testPlayerListForDoubles(); } ppC.setCutForename(settingsView.getForenameLengthBox().getValue()); ppC.setCutSurname(settingsView.getSurnameLengthBox().getValue()); ppC.setWebserverPath(settingsView.getWebserverPathTextField().getText()); ppC.checkCrossTableColumnForDoubles(); ppC.checkMeetingTableColumnForDoubles(); ppC.setCSSTable(settingsView.getTableCSSTextField().getText()); ppC.writeProperties(); esControl.setTableColumns(); } }); esControl.getEigenschaftenView().getOpenVereineCSVButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // vereine.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("CSV file", "csv", "CSV"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToVereineCVS(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS()); } } }); esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final DWZListToSQLITEControl dwzL = new DWZListToSQLITEControl(mainControl); dwzL.convertDWZListToSQLITE(); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } }); esControl.getEigenschaftenView().getOpenPlayersCSVButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // spieler.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("CSV or SQLite file", "csv", "CSV", "sqlite", "SQLite"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToPlayersCSV(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); final String filename = file.getName(); final int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true); } } } } }); esControl.getEigenschaftenView().getConvertELOToSQLITEButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final ELOListToSQLITEControl eloL = new ELOListToSQLITEControl(mainControl); eloL.convertELOListToSQLITE(); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } }); esControl.getEigenschaftenView().getOpenPlayersELOButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // spieler.csv final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); final FileFilter filter = new FileNameExtensionFilter("TXT or SQLite file", "txt", "TXT", "sqlite", "SQLite"); fc.setFileFilter(filter); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setPathToPlayersELO(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); final String filename = file.getName(); final int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true); } } } } }); esControl.getEigenschaftenView().getOpenDefaultPathButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final File path = new File(mainControl.getPropertiesControl().getDefaultPath()); final JFileChooser fc = new JFileChooser(path); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setMultiSelectionEnabled(false); final int returnVal = fc.showOpenDialog(esControl.getEigenschaftenView()); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fc.getSelectedFile(); // This is where a real application would open the // file. mainControl.getPropertiesControl().setDefaultPath(file.getAbsolutePath()); mainControl.getPropertiesControl().writeProperties(); esControl.getEigenschaftenView() .setOpenDefaultPathLabel(mainControl.getPropertiesControl().getDefaultPath()); } } }); esControl.getEigenschaftenView() .setOpenVereineCSVLabel(mainControl.getPropertiesControl().getPathToVereineCVS()); esControl.getEigenschaftenView() .setOpenPlayersCSVLabel(mainControl.getPropertiesControl().getPathToPlayersCSV()); esControl.getEigenschaftenView() .setOpenPlayersELOLabel(mainControl.getPropertiesControl().getPathToPlayersELO()); esControl.getEigenschaftenView().getGermanLanguageCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mainControl.getLanguagePropertiesControl().setLanguageToGerman(); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getEnglishLanguageCheckBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { mainControl.getLanguagePropertiesControl().setLanguageToEnglish(); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getSpielerListeAuswahlBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int anzahlProTab = esControl.getEigenschaftenView().getSpielerListeAuswahlBox() .getSelectedIndex(); mainControl.getPropertiesControl().setSpielerProTab(anzahlProTab); mainControl.getPropertiesControl().writeProperties(); } }); esControl.getEigenschaftenView().getTurnierListeAuswahlBox().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { final int anzahlProTab = esControl.getEigenschaftenView().getTurnierListeAuswahlBox() .getSelectedIndex(); mainControl.getPropertiesControl().setTurniereProTab(anzahlProTab); mainControl.getPropertiesControl().writeProperties(); } }); String filename = mainControl.getPropertiesControl().getPathToPlayersELO(); int positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(true); } } else { esControl.getEigenschaftenView().getConvertELOToSQLITEButton().setEnabled(false); } filename = mainControl.getPropertiesControl().getPathToPlayersCSV(); positionEXT = filename.lastIndexOf('.'); if (positionEXT > 0) { final String newFile = filename.substring(positionEXT); if (newFile.equals(".sqlite")) { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(true); } } else { esControl.getEigenschaftenView().getConvertDWZToSQLITEButton().setEnabled(false); } esControl.getEigenschaftenView().getResetPropertiesButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int abfrage = beendenHinweis(); if (abfrage > 0) { if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) { if (mainControl.getChangedGames().isEmpty() == false) { final SaveTournamentControl saveTournament = new SaveTournamentControl(mainControl); try { saveTournament.saveChangedPartien(); } catch (final SQLException e1) { final ExceptionHandler eh = new ExceptionHandler(mainControl); eh.fileSQLError(e1.getMessage()); } } } } mainControl.getPropertiesControl().resetProperties(); mainControl.getPropertiesControl().writeProperties(); JOptionPane.showMessageDialog(null, Messages.getString("EigenschaftenControl.29"), Messages.getString("EigenschaftenControl.28"), JOptionPane.INFORMATION_MESSAGE); System.exit(0); } }); } private void addPropertiesActionListener() { mainControl.getNaviView().getPropertiesButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { mainControl.getSettingsControl().setEigenschaftenView(new SettingsView()); final SettingsView eigenschaftenView = mainControl.getSettingsControl().getEigenschaftenView(); mainControl.getSettingsControl().setItemListenerControl( new ItemListenerSettingsControl(mainControl, mainControl.getSettingsControl())); mainControl.getSettingsControl().getItemListenerControl().addItemListeners(); if (dialog == null) { dialog = new JDialog(); } else { dialog.dispose(); dialog = new JDialog(); } // dialog.setAlwaysOnTop(true); dialog.getContentPane().add(eigenschaftenView); dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setBounds(mainControl.getPropertiesControl().getSettingsDialogX(), mainControl.getPropertiesControl().getSettingsDialogY(), mainControl.getPropertiesControl().getSettingsDialogWidth(), mainControl.getPropertiesControl().getSettingsDialogHeight()); dialog.setEnabled(true); if (mainControl.getPropertiesControl() == null) { mainControl.setPropertiesControl(new PropertiesControl(mainControl)); } final PropertiesControl ppC = mainControl.getPropertiesControl(); ppC.readProperties(); eigenschaftenView.getCheckBoxHeaderFooter().setSelected(ppC.getOnlyTables()); eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ()); eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(ppC.getNoFolgeDWZ()); eigenschaftenView.getCheckBoxohneELO().setSelected(ppC.getNoELO()); eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(ppC.getNoFolgeELO()); eigenschaftenView.getSpielerListeAuswahlBox().setSelectedIndex(ppC.getSpielerProTab()); eigenschaftenView.getTurnierListeAuswahlBox().setSelectedIndex(ppC.getTurniereProTab()); eigenschaftenView.getForenameLengthBox().setValue(ppC.getCutForename()); eigenschaftenView.getSurnameLengthBox().setValue(ppC.getCutSurname()); eigenschaftenView.getWebserverPathTextField().setText(ppC.getWebserverPath()); // eigenschaftenView.getCheckBoxohneDWZ().setSelected(ppC.getNoDWZ()); eigenschaftenView.getCheckBoxhtmlToClipboard().setSelected(ppC.gethtmlToClipboard()); if (eigenschaftenView.getCheckBoxohneDWZ().isSelected() == true) { eigenschaftenView.getCheckBoxohneFolgeDWZ().setSelected(true); eigenschaftenView.getCheckBoxohneFolgeDWZ().setEnabled(false); ppC.setNoFolgeDWZ(true); } if (eigenschaftenView.getCheckBoxohneELO().isSelected() == true) { eigenschaftenView.getCheckBoxohneFolgeELO().setSelected(true); eigenschaftenView.getCheckBoxohneFolgeELO().setEnabled(false); ppC.setNoFolgeELO(true); } eigenschaftenView.getCheckBoxPDFLinks().setSelected(ppC.getPDFLinks()); eigenschaftenView.getWebserverPathTextField().setEnabled(ppC.getPDFLinks()); if (mainControl.getPropertiesControl().getLanguage().equals("german")) { //$NON-NLS-1$ eigenschaftenView.getGermanLanguageCheckBox().setSelected(true); eigenschaftenView.getEnglishLanguageCheckBox().setSelected(false); mainControl.getLanguagePropertiesControl().setLanguageToGerman(); } else if (mainControl.getPropertiesControl().getLanguage().equals("english")) { //$NON-NLS-1$ eigenschaftenView.getGermanLanguageCheckBox().setSelected(false); eigenschaftenView.getEnglishLanguageCheckBox().setSelected(true); mainControl.getLanguagePropertiesControl().setLanguageToEnglish(); } eigenschaftenView.setOpenDefaultPathLabel(ppC.getDefaultPath()); eigenschaftenView.getTableCSSTextField().setText(ppC.getCSSTable()); esControl.setTableColumns(); addActionListeners(); esControl.getItemListenerControl().addItemListeners(); dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); dialog.setVisible(true); } }); } private int beendenHinweis() { int abfrage = 0; if (mainControl.getHauptPanel().getTabCount() == TournamentConstants.TAB_ACTIVE_TOURNAMENT + 1) { if (mainControl.getChangedGames().isEmpty() == false) { final String hinweisText = Messages.getString("NaviController.21") //$NON-NLS-1$ + Messages.getString("NaviController.22") //$NON-NLS-1$ + Messages.getString("NaviController.33"); //$NON-NLS-1$ abfrage = 1; // Custom button text final Object[] options = { Messages.getString("NaviController.24"), //$NON-NLS-1$ Messages.getString("NaviController.25") }; //$NON-NLS-1$ abfrage = JOptionPane.showOptionDialog(mainControl, hinweisText, Messages.getString("NaviController.26"), //$NON-NLS-1$ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); } } return abfrage; } }
Java
namespace Ribbonizer.Ribbon { using System.Collections.Generic; using System.Linq; using Ribbonizer.Ribbon.DefinitionValidation; using Ribbonizer.Ribbon.Tabs; internal class RibbonInitializer : IRibbonInitializer { private readonly IEnumerable<IRibbonDefinitionValidator> definitionValidators; private readonly IRibbonTabViewCacheInitializer tabViewCacheInitializer; public RibbonInitializer(IEnumerable<IRibbonDefinitionValidator> definitionValidators, IRibbonTabViewCacheInitializer tabViewCacheInitializer) { this.definitionValidators = definitionValidators; this.tabViewCacheInitializer = tabViewCacheInitializer; } public void InitializeRibbonViewTree() { IEnumerable<IRibbonDefinitionViolation> violations = this.definitionValidators .SelectMany(x => x.Validate()) .ToList(); if (violations.Any()) { throw new RibbonDefinitionViolationException(violations); } this.tabViewCacheInitializer.InitializeCache(); } } }
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2015 Satpy developers # # This file is part of satpy. # # satpy is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # satpy is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # satpy. If not, see <http://www.gnu.org/licenses/>. """Fetch avhrr calibration coefficients.""" import datetime as dt import os.path import sys import h5py import urllib2 BASE_URL = "http://www.star.nesdis.noaa.gov/smcd/spb/fwu/homepage/" + \ "AVHRR/Op_Cal_AVHRR/" URLS = { "Metop-B": {"ch1": BASE_URL + "Metop1_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "Metop1_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "Metop1_AVHRR_Libya_ch3a.txt"}, "Metop-A": {"ch1": BASE_URL + "Metop2_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "Metop2_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "Metop2_AVHRR_Libya_ch3a.txt"}, "NOAA-16": {"ch1": BASE_URL + "N16_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N16_AVHRR_Libya_ch2.txt"}, "NOAA-17": {"ch1": BASE_URL + "N17_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N17_AVHRR_Libya_ch2.txt", "ch3a": BASE_URL + "N17_AVHRR_Libya_ch3a.txt"}, "NOAA-18": {"ch1": BASE_URL + "N18_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N18_AVHRR_Libya_ch2.txt"}, "NOAA-19": {"ch1": BASE_URL + "N19_AVHRR_Libya_ch1.txt", "ch2": BASE_URL + "N19_AVHRR_Libya_ch2.txt"} } def get_page(url): """Retrieve the given page.""" return urllib2.urlopen(url).read() def get_coeffs(page): """Parse coefficients from the page.""" coeffs = {} coeffs['datetime'] = [] coeffs['slope1'] = [] coeffs['intercept1'] = [] coeffs['slope2'] = [] coeffs['intercept2'] = [] slope1_idx, intercept1_idx, slope2_idx, intercept2_idx = \ None, None, None, None date_idx = 0 for row in page.lower().split('\n'): row = row.split() if len(row) == 0: continue if row[0] == 'update': # Get the column indices from the header line slope1_idx = row.index('slope_lo') intercept1_idx = row.index('int_lo') slope2_idx = row.index('slope_hi') intercept2_idx = row.index('int_hi') continue if slope1_idx is None: continue # In some cases the fields are connected, skip those rows if max([slope1_idx, intercept1_idx, slope2_idx, intercept2_idx]) >= len(row): continue try: dat = dt.datetime.strptime(row[date_idx], "%m/%d/%Y") except ValueError: continue coeffs['datetime'].append([dat.year, dat.month, dat.day]) coeffs['slope1'].append(float(row[slope1_idx])) coeffs['intercept1'].append(float(row[intercept1_idx])) coeffs['slope2'].append(float(row[slope2_idx])) coeffs['intercept2'].append(float(row[intercept2_idx])) return coeffs def get_all_coeffs(): """Get all available calibration coefficients for the satellites.""" coeffs = {} for platform in URLS: if platform not in coeffs: coeffs[platform] = {} for chan in URLS[platform].keys(): url = URLS[platform][chan] print(url) page = get_page(url) coeffs[platform][chan] = get_coeffs(page) return coeffs def save_coeffs(coeffs, out_dir=''): """Save calibration coefficients to HDF5 files.""" for platform in coeffs.keys(): fname = os.path.join(out_dir, "%s_calibration_data.h5" % platform) fid = h5py.File(fname, 'w') for chan in coeffs[platform].keys(): fid.create_group(chan) fid[chan]['datetime'] = coeffs[platform][chan]['datetime'] fid[chan]['slope1'] = coeffs[platform][chan]['slope1'] fid[chan]['intercept1'] = coeffs[platform][chan]['intercept1'] fid[chan]['slope2'] = coeffs[platform][chan]['slope2'] fid[chan]['intercept2'] = coeffs[platform][chan]['intercept2'] fid.close() print("Calibration coefficients saved for %s" % platform) def main(): """Create calibration coefficient files for AVHRR.""" out_dir = sys.argv[1] coeffs = get_all_coeffs() save_coeffs(coeffs, out_dir=out_dir) if __name__ == "__main__": main()
Java
<?php /** * Belgian Scouting Web Platform * Copyright (C) 2014 Julien Dupuis * * This code is licensed under the GNU General Public License. * * This is free software, and you are welcome to redistribute it * under under the terms of the GNU General Public License. * * It is distributed without any warranty; without even the * implied warranty of merchantability or fitness for a particular * purpose. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ /** * This Eloquent class represents a privilege of a leader * * Columns: * - operation: A string representing which operation this privilege allows * - scope: 'S' if the privilege is limited to the leader's section, 'U' for unit if they can use this privilege on any section * - member_id: The leader affected by this privilege * * Note : predefined privileges are privileges that can be automatically applied to classes * of members : * A: Simple leader * R: Leader in charge / Section webmaster * S: Unit co-leader * U: Unit main leader */ class Privilege extends Eloquent { var $guarded = array('id', 'created_at', 'updated_at'); // Following are all the privileges with // - id: the string representing the privilege // - text: a textual description of the privilege // - section: true if this privilege can be applied to only a section, false if it is a global privilige // - predefined: in which predefined classes it will be applied public static $UPDATE_OWN_LISTING_ENTRY = array( 'id' => 'Update own listing entry', 'text' => 'Modifier ses données personnelles dans le listing', 'section' => false, 'predefined' => "ARSU" ); public static $EDIT_PAGES = array( 'id' => 'Edit pages', 'text' => 'Modifier les pages #delasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_SECTION_EMAIL_AND_SUBGROUP = array( 'id' => "Edit section e-mail address and subgroup name", 'text' => "Changer l'adresse e-mail #delasection", 'section' => true, 'predefined' => "RSU" ); public static $EDIT_CALENDAR = array( 'id' => "Edit calendar", 'text' => 'Modifier les entrées du calendrier #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_ATTENDANCE = array( 'id' => "Manage attendance", 'text' => 'Cocher les présences aux activités #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_EVENT_PAYMENTS = array( 'id' => "Manage event payments", 'text' => 'Cocher le paiement des membres pour les activités #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $EDIT_NEWS = array( 'id' => "Edit news", 'text' => 'Poster des nouvelles (actualités) pour #lasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_DOCUMENTS = array( 'id' => "Edit documents", 'text' => 'Modifier les documents #delasection', 'section' => true, 'predefined' => "RSU" ); public static $SEND_EMAILS = array( 'id' => "Send e-mails", 'text' => 'Envoyer des e-mails aux membres #delasection', 'section' => true, 'predefined' => "RSU" ); public static $POST_PHOTOS = array( 'id' => "Post photos", 'text' => 'Ajouter/supprimer des photos pour #lasection', 'section' => true, 'predefined' => "ARSU" ); public static $MANAGE_ACCOUNTING = array( 'id' => "Manage accounting", 'text' => 'Gérer les comptes #delasection', 'section' => true, 'predefined' => "RSU" ); public static $SECTION_TRANSFER = array( 'id' => "Section transfer", 'text' => "Changer les scouts de section", 'section' => false, 'predefined' => "SU", ); public static $EDIT_LISTING_LIMITED = array( 'id' => "Edit listing limited", 'text' => 'Modifier les données non sensibles du listing #delasection', 'section' => true, 'predefined' => "RSU" ); public static $EDIT_LISTING_ALL = array( 'id' => "Edit listing all", 'text' => 'Modifier les données sensibles du listing #delasection', 'section' => true, 'predefined' => "U" ); public static $VIEW_HEALTH_CARDS = array( 'id' => "View health cards", 'text' => 'Consulter les fiches santé #delasection', 'section' => true, 'predefined' => "ARSU" ); public static $EDIT_LEADER_PRIVILEGES = array( 'id' => "Edit leader privileges", 'text' => 'Changer les privilèges des animateurs #delasection', 'section' => true, 'predefined' => "RSU" ); public static $UPDATE_PAYMENT_STATUS = array( 'id' => "Update payment status", 'text' => 'Modifier le statut de paiement', 'section' => false, 'predefined' => "SU" ); public static $MANAGE_ANNUAL_FEAST_REGISTRATION = array( 'id' => "Manage annual feast registration", 'text' => "Valider les inscriptions pour la fête d'unité", 'section' => false, 'predefined' => "SU" ); public static $MANAGE_SUGGESIONS = array( 'id' => "Manage suggestions", 'text' => "Répondre aux suggestions et les supprimer", 'section' => false, 'predefined' => "SU" ); public static $EDIT_GLOBAL_PARAMETERS = array( 'id' => "Edit global parameters", 'text' => "Changer les paramètres du site", 'section' => false, 'predefined' => "U" ); public static $EDIT_STYLE = array( 'id' => "Edit style", 'text' => "Modifier le style du site", 'section' => false, 'predefined' => "U" ); public static $MANAGE_SECTIONS = array( 'id' => "Manage sections", 'text' => "Créer, modifier et supprimer les sections", 'section' => false, 'predefined' => "U" ); public static $DELETE_USERS = array( 'id' => "Delete users", 'text' => "Supprimer des comptes d'utilisateurs", 'section' => false, 'predefined' => "U" ); public static $DELETE_GUEST_BOOK_ENTRIES = array( 'id' => "Delete guest book entries", 'text' => "Supprimer des entrées du livre d'or", 'section' => false, 'predefined' => "U" ); /** * Returns the list of privileges */ public static function getPrivilegeList() { return array( self::$UPDATE_OWN_LISTING_ENTRY, self::$EDIT_CALENDAR, self::$MANAGE_ATTENDANCE, self::$MANAGE_EVENT_PAYMENTS, self::$POST_PHOTOS, self::$VIEW_HEALTH_CARDS, self::$EDIT_PAGES, self::$EDIT_DOCUMENTS, self::$EDIT_NEWS, self::$SEND_EMAILS, self::$EDIT_SECTION_EMAIL_AND_SUBGROUP, self::$MANAGE_ACCOUNTING, self::$SECTION_TRANSFER, self::$EDIT_LISTING_LIMITED, self::$EDIT_LEADER_PRIVILEGES, self::$MANAGE_ANNUAL_FEAST_REGISTRATION, self::$MANAGE_SUGGESIONS, self::$UPDATE_PAYMENT_STATUS, self::$EDIT_LISTING_ALL, self::$EDIT_GLOBAL_PARAMETERS, self::$EDIT_STYLE, self::$MANAGE_SECTIONS, self::$DELETE_GUEST_BOOK_ENTRIES, self::$DELETE_USERS, ); } /** * Returns the list of privileges sorted in 4 categories * * @param boolean $forSection Whether this is for a section leader or a unit leader */ public static function getPrivilegeArrayByCategory($forSection = false) { // The four categories $basicPrivileges = array(); $leaderInChargePrivileges = array(); $unitTeamPrivileges = array(); $unitLeaderPrivileges = array(); // Sort privileges into categories foreach (self::getPrivilegeList() as $privilege) { if (strpos($privilege['predefined'], "A") !== false) { if ($forSection) { if ($privilege['section']) { $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'S'); $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } else { $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } else { if ($privilege['section']) $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); else $basicPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } elseif (strpos($privilege['predefined'], "R") !== false) { if ($forSection) { if ($privilege['section']) { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'S'); $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } else { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } else { $leaderInChargePrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } elseif (strpos($privilege['predefined'], "S") !== false) { $unitTeamPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } elseif (strpos($privilege['predefined'], "U") !== false) { $unitLeaderPrivileges[] = array('privilege' => $privilege, 'scope' => 'U'); } } // Return list of categories return array( "Gestion de base" => $basicPrivileges, "Gestion avancée" => $leaderInChargePrivileges, "Gestion de l'unité" => $unitTeamPrivileges, "Gestion avancée de l'unité" => $unitLeaderPrivileges, ); } /** * Sets and saves all the privileges from the base category to the given leader */ public static function addBasePrivilegesForLeader($leader) { foreach (self::getPrivilegeList() as $privilege) { if (strpos($privilege['predefined'], "A") !== false) { try { Privilege::create(array( 'operation' => $privilege['id'], 'scope' => $privilege['section'] ? 'S' : 'U', 'member_id' => $leader->id, )); } catch (Exception $e) { Log::error($e); } } } } /** * Sets ($state = true) or unsets ($state = false) and saves a privilege for a leader in a given scope */ public static function set($operation, $scope, $leaderId, $state) { // Find existing privilege $privilege = Privilege::where('operation', '=', $operation) ->where('scope', '=', $scope) ->where('member_id', '=', $leaderId) ->first(); if ($privilege && !$state) { // Privilege exists and should be removed $privilege->delete(); } elseif (!$privilege && $state) { // Privilege does not exist and should be created Privilege::create(array( 'operation' => $operation, 'scope' => $scope, 'member_id' => $leaderId, )); } } }
Java
<?php /** * WES WebExploitScan Web GPLv4 http://github.com/libre/webexploitscan * * The PHP page that serves all page requests on WebExploitScan installation. * * The routines here dispatch control to the appropriate handler, which then * prints the appropriate page. * * All WebExploitScan code is released under the GNU General Public License. * See COPYRIGHT.txt and LICENSE.txt. */ $NAME='Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2155'; $TAGCLEAR='A<?php[^}]{1,600}}}define([\'"]startTime[\'"],getTime());if(!function_exists([\'"]shellexec[\'"])){functions+shellexec($cmd){'; $TAGBASE64='QTw/cGhwW159XXsxLDYwMH19fWRlZmluZShbXCciXXN0YXJ0VGltZVtcJyJdLGdldFRpbWUoKSk7aWYoIWZ1bmN0aW9uX2V4aXN0cyhbXCciXXNoZWxsZXhlY1tcJyJdKSl7ZnVuY3Rpb25zK3NoZWxsZXhlYygkY21kKXs='; $TAGHEX='413c3f7068705b5e7d5d7b312c3630307d7d7d646566696e65285b5c27225d737461727454696d655b5c27225d2c67657454696d652829293b6966282166756e6374696f6e5f657869737473285b5c27225d7368656c6c657865635b5c27225d29297b66756e6374696f6e732b7368656c6c657865632824636d64297b'; $TAGHEXPHP=''; $TAGURI='A%3C%3Fphp%5B%5E%7D%5D%7B1%2C600%7D%7D%7Ddefine%28%5B%5C%27%22%5DstartTime%5B%5C%27%22%5D%2CgetTime%28%29%29%3Bif%28%21function_exists%28%5B%5C%27%22%5Dshellexec%5B%5C%27%22%5D%29%29%7Bfunctions%2Bshellexec%28%24cmd%29%7B'; $TAGCLEAR2=''; $TAGBASE642=''; $TAGHEX2=''; $TAGHEXPHP2=''; $TAGURI2=''; $DATEADD='10/09/2019'; $LINK='Webexploitscan.org ;Php-MS-PHP-Antimalware-Scanner malware_signature- ID 2155 '; $ACTIVED='1'; $VSTATR='malware_signature';
Java
#define TYPEDEPARGS 0, 1, 2, 3 #define SINGLEARGS #define REALARGS #define OCTFILENAME comp_ufilterbankheapint // change to filename #define OCTFILEHELP "This function calls the C-library\n\ phase=comp_ufilterbankheapint(s,tgrad,fgrad,cfreq,a,do_real,tol,phasetype)\n Yeah." #include "ltfat_oct_template_helper.h" static inline void fwd_ufilterbankheapint( const double s[], const double tgrad[], const double fgrad[], const double cfreq[], ltfat_int a, ltfat_int M, ltfat_int L, ltfat_int W, int do_real, double tol, int phasetype, double phase[]) { if (phasetype == 1) ltfat_ufilterbankheapint_d( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); else ltfat_ufilterbankheapint_relgrad_d( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); } static inline void fwd_ufilterbankheapint( const float s[], const float tgrad[], const float fgrad[], const float cfreq[], ltfat_int a, ltfat_int M, ltfat_int L, ltfat_int W, int do_real, float tol, int phasetype, float phase[]) { if (phasetype == 1) ltfat_ufilterbankheapint_s( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); else ltfat_ufilterbankheapint_relgrad_s( s, tgrad, fgrad, cfreq, a, M, L, W, do_real, tol, phase); } template <class LTFAT_TYPE, class LTFAT_REAL, class LTFAT_COMPLEX> octave_value_list octFunction(const octave_value_list& args, int nargout) { // Input data MArray<LTFAT_REAL> s = ltfatOctArray<LTFAT_REAL>(args(0)); MArray<LTFAT_REAL> tgrad = ltfatOctArray<LTFAT_REAL>(args(1)); MArray<LTFAT_REAL> fgrad = ltfatOctArray<LTFAT_REAL>(args(2)); MArray<LTFAT_REAL> cfreq = ltfatOctArray<LTFAT_REAL>(args(3)); octave_idx_type a = args(4).int_value(); octave_idx_type do_real = args(5).int_value(); double tol = args(6).double_value(); octave_idx_type phasetype = args(7).int_value(); octave_idx_type M = s.columns(); octave_idx_type N = s.rows(); octave_idx_type W = 1; octave_idx_type L = (octave_idx_type)( N * a); // phasetype--; MArray<LTFAT_REAL> phase(dim_vector(N, M, W)); fwd_ufilterbankheapint( s.data(), tgrad.data(), fgrad.data(), cfreq.data(), a, M, L, W, do_real, tol, phasetype, phase.fortran_vec()); return octave_value(phase); }
Java
/** * This file is part of RagEmu. * http://ragemu.org - https://github.com/RagEmu/Renewal * * Copyright (C) 2016 RagEmu Dev Team * Copyright (C) 2012-2015 Hercules Dev Team * Copyright (C) Athena Dev Teams * * RagEmu is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COMMON_MD5CALC_H #define COMMON_MD5CALC_H #include "common/ragemu.h" /** @file * md5 calculation algorithm. * * The source code referred to the following URL. * http://www.geocities.co.jp/SiliconValley-Oakland/8878/lab17/lab17.html */ /// The md5 interface struct md5_interface { /** * Hashes a string, returning the hash in string format. * * @param[in] string The source string (NUL terminated). * @param[out] output Output buffer (at least 33 bytes available). */ void (*string) (const char *string, char *output); /** * Hashes a string, returning the buffer in binary format. * * @param[in] string The source string. * @param[out] output Output buffer (at least 16 bytes available). */ void (*binary) (const uint8 *buf, const int buf_size, uint8 *output); /** * Generates a random salt. * * @param[in] len The desired salt length. * @param[out] output The output buffer (at least len bytes available). */ void (*salt) (int len, char *output); }; #ifdef RAGEMU_CORE void md5_defaults(void); #endif // RAGEMU_CORE HPShared struct md5_interface *md5; ///< Pointer to the md5 interface. #endif /* COMMON_MD5CALC_H */
Java
// OpenCppCoverage is an open source code coverage for C++. // Copyright (C) 2014 OpenCppCoverage // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.Shell.Interop; using System; namespace OpenCppCoverage.VSPackage { class OutputWindowWriter { //--------------------------------------------------------------------- public OutputWindowWriter(DTE2 dte, IVsOutputWindow outputWindow) { // These lines show the output windows Window output = dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput); output.Activate(); if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(OpenCppCoverageOutputPaneGuid, out outputWindowPane_))) { if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.CreatePane(OpenCppCoverageOutputPaneGuid, "OpenCppCoverage", 1, 1))) throw new Exception("Cannot create new pane."); if (Microsoft.VisualStudio.ErrorHandler.Failed(outputWindow.GetPane(OpenCppCoverageOutputPaneGuid, out outputWindowPane_))) throw new Exception("Cannot get the pane."); } outputWindowPane_.Clear(); ActivatePane(); } //--------------------------------------------------------------------- public void ActivatePane() { outputWindowPane_.Activate(); } //--------------------------------------------------------------------- public bool WriteLine(string message) { return Microsoft.VisualStudio.ErrorHandler.Succeeded(outputWindowPane_.OutputString(message + "\n")); } readonly IVsOutputWindowPane outputWindowPane_; public readonly static Guid OpenCppCoverageOutputPaneGuid = new Guid("CB47C727-5E45-467B-A4CD-4A025986A8A0"); } }
Java
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: git author: - "Ansible Core Team" - "Michael DeHaan" version_added: "0.0.1" short_description: Deploy software (or files) from git checkouts description: - Manage I(git) checkouts of repositories to deploy files or software. options: repo: description: - git, SSH, or HTTP(S) protocol address of the git repository. type: str required: true aliases: [ name ] dest: description: - The path of where the repository should be checked out. This is equivalent to C(git clone [repo_url] [directory]). The repository named in I(repo) is not appended to this path and the destination directory must be empty. This parameter is required, unless I(clone) is set to C(no). type: path required: true version: description: - What version of the repository to check out. This can be the literal string C(HEAD), a branch name, a tag name. It can also be a I(SHA-1) hash, in which case I(refspec) needs to be specified if the given revision is not already available. type: str default: "HEAD" accept_hostkey: description: - If C(yes), ensure that "-o StrictHostKeyChecking=no" is present as an ssh option. type: bool default: 'no' version_added: "1.5" accept_newhostkey: description: - As of OpenSSH 7.5, "-o StrictHostKeyChecking=accept-new" can be used which is safer and will only accepts host keys which are not present or are the same. if C(yes), ensure that "-o StrictHostKeyChecking=accept-new" is present as an ssh option. type: bool default: 'no' version_added: "2.12" ssh_opts: description: - Creates a wrapper script and exports the path as GIT_SSH which git then automatically uses to override ssh arguments. An example value could be "-o StrictHostKeyChecking=no" (although this particular option is better set by I(accept_hostkey)). type: str version_added: "1.5" key_file: description: - Specify an optional private key file path, on the target host, to use for the checkout. type: path version_added: "1.5" reference: description: - Reference repository (see "git clone --reference ..."). version_added: "1.4" remote: description: - Name of the remote. type: str default: "origin" refspec: description: - Add an additional refspec to be fetched. If version is set to a I(SHA-1) not reachable from any branch or tag, this option may be necessary to specify the ref containing the I(SHA-1). Uses the same syntax as the C(git fetch) command. An example value could be "refs/meta/config". type: str version_added: "1.9" force: description: - If C(yes), any modified files in the working repository will be discarded. Prior to 0.7, this was always 'yes' and could not be disabled. Prior to 1.9, the default was `yes`. type: bool default: 'no' version_added: "0.7" depth: description: - Create a shallow clone with a history truncated to the specified number or revisions. The minimum possible value is C(1), otherwise ignored. Needs I(git>=1.9.1) to work correctly. type: int version_added: "1.2" clone: description: - If C(no), do not clone the repository even if it does not exist locally. type: bool default: 'yes' version_added: "1.9" update: description: - If C(no), do not retrieve new revisions from the origin repository. - Operations like archive will work on the existing (old) repository and might not respond to changes to the options version or remote. type: bool default: 'yes' version_added: "1.2" executable: description: - Path to git executable to use. If not supplied, the normal mechanism for resolving binary paths will be used. type: path version_added: "1.4" bare: description: - If C(yes), repository will be created as a bare repo, otherwise it will be a standard repo with a workspace. type: bool default: 'no' version_added: "1.4" umask: description: - The umask to set before doing any checkouts, or any other repository maintenance. type: raw version_added: "2.2" recursive: description: - If C(no), repository will be cloned without the --recursive option, skipping sub-modules. type: bool default: 'yes' version_added: "1.6" single_branch: description: - Clone only the history leading to the tip of the specified I(branch). type: bool default: 'no' version_added: '2.11' track_submodules: description: - If C(yes), submodules will track the latest commit on their master branch (or other branch specified in .gitmodules). If C(no), submodules will be kept at the revision specified by the main project. This is equivalent to specifying the --remote flag to git submodule update. type: bool default: 'no' version_added: "1.8" verify_commit: description: - If C(yes), when cloning or checking out a I(version) verify the signature of a GPG signed commit. This requires git version>=2.1.0 to be installed. The commit MUST be signed and the public key MUST be present in the GPG keyring. type: bool default: 'no' version_added: "2.0" archive: description: - Specify archive file path with extension. If specified, creates an archive file of the specified format containing the tree structure for the source tree. Allowed archive formats ["zip", "tar.gz", "tar", "tgz"]. - This will clone and perform git archive from local directory as not all git servers support git archive. type: path version_added: "2.4" archive_prefix: description: - Specify a prefix to add to each file path in archive. Requires I(archive) to be specified. version_added: "2.10" type: str separate_git_dir: description: - The path to place the cloned repository. If specified, Git repository can be separated from working tree. type: path version_added: "2.7" gpg_whitelist: description: - A list of trusted GPG fingerprints to compare to the fingerprint of the GPG-signed commit. - Only used when I(verify_commit=yes). - Use of this feature requires Git 2.6+ due to its reliance on git's C(--raw) flag to C(verify-commit) and C(verify-tag). type: list elements: str default: [] version_added: "2.9" requirements: - git>=1.7.1 (the command line tool) notes: - "If the task seems to be hanging, first verify remote host is in C(known_hosts). SSH will prompt user to authorize the first contact with a remote host. To avoid this prompt, one solution is to use the option accept_hostkey. Another solution is to add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling the git module, with the following command: ssh-keyscan -H remote_host.com >> /etc/ssh/ssh_known_hosts." - Supports C(check_mode). ''' EXAMPLES = ''' - name: Git checkout ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout version: release-0.22 - name: Read-write git checkout from github ansible.builtin.git: repo: git@github.com:mylogin/hello.git dest: /home/mylogin/hello - name: Just ensuring the repo checkout exists ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout update: no - name: Just get information about the repository whether or not it has already been cloned locally ansible.builtin.git: repo: 'https://foosball.example.org/path/to/repo.git' dest: /srv/checkout clone: no update: no - name: Checkout a github repo and use refspec to fetch all pull requests ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples refspec: '+refs/pull/*:refs/heads/*' - name: Create git archive from repo ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples archive: /tmp/ansible-examples.zip - name: Clone a repo with separate git directory ansible.builtin.git: repo: https://github.com/ansible/ansible-examples.git dest: /src/ansible-examples separate_git_dir: /src/ansible-examples.git - name: Example clone of a single branch ansible.builtin.git: single_branch: yes branch: master - name: Avoid hanging when http(s) password is missing ansible.builtin.git: repo: https://github.com/ansible/could-be-a-private-repo dest: /src/from-private-repo environment: GIT_TERMINAL_PROMPT: 0 # reports "terminal prompts disabled" on missing password # or GIT_ASKPASS: /bin/true # for git before version 2.3.0, reports "Authentication failed" on missing password ''' RETURN = ''' after: description: Last commit revision of the repository retrieved during the update. returned: success type: str sample: 4c020102a9cd6fe908c9a4a326a38f972f63a903 before: description: Commit revision before the repository was updated, "null" for new repository. returned: success type: str sample: 67c04ebe40a003bda0efb34eacfb93b0cafdf628 remote_url_changed: description: Contains True or False whether or not the remote URL was changed. returned: success type: bool sample: True warnings: description: List of warnings if requested features were not available due to a too old git version. returned: error type: str sample: git version is too old to fully support the depth argument. Falling back to full checkouts. git_dir_now: description: Contains the new path of .git directory if it is changed. returned: success type: str sample: /path/to/new/git/dir git_dir_before: description: Contains the original path of .git directory if it is changed. returned: success type: str sample: /path/to/old/git/dir ''' import filecmp import os import re import shlex import stat import sys import shutil import tempfile from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import b, string_types from ansible.module_utils._text import to_native, to_text from ansible.module_utils.common.process import get_bin_path def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir): if os.path.exists(repo_dir): module.fail_json(msg='Separate-git-dir path %s already exists.' % repo_dir) if worktree_dir: dot_git_file_path = os.path.join(worktree_dir, '.git') try: shutil.move(old_repo_dir, repo_dir) with open(dot_git_file_path, 'w') as dot_git_file: dot_git_file.write('gitdir: %s' % repo_dir) result['git_dir_before'] = old_repo_dir result['git_dir_now'] = repo_dir except (IOError, OSError) as err: # if we already moved the .git dir, roll it back if os.path.exists(repo_dir): shutil.move(repo_dir, old_repo_dir) module.fail_json(msg=u'Unable to move git dir. %s' % to_text(err)) def head_splitter(headfile, remote, module=None, fail_on_error=False): '''Extract the head reference''' # https://github.com/ansible/ansible-modules-core/pull/907 res = None if os.path.exists(headfile): rawdata = None try: f = open(headfile, 'r') rawdata = f.readline() f.close() except Exception: if fail_on_error and module: module.fail_json(msg="Unable to read %s" % headfile) if rawdata: try: rawdata = rawdata.replace('refs/remotes/%s' % remote, '', 1) refparts = rawdata.split(' ') newref = refparts[-1] nrefparts = newref.split('/', 2) res = nrefparts[-1].rstrip('\n') except Exception: if fail_on_error and module: module.fail_json(msg="Unable to split head from '%s'" % rawdata) return res def unfrackgitpath(path): if path is None: return None # copied from ansible.utils.path return os.path.normpath(os.path.realpath(os.path.expanduser(os.path.expandvars(path)))) def get_submodule_update_params(module, git_path, cwd): # or: git submodule [--quiet] update [--init] [-N|--no-fetch] # [-f|--force] [--rebase] [--reference <repository>] [--merge] # [--recursive] [--] [<path>...] params = [] # run a bad submodule command to get valid params cmd = "%s submodule update --help" % (git_path) rc, stdout, stderr = module.run_command(cmd, cwd=cwd) lines = stderr.split('\n') update_line = None for line in lines: if 'git submodule [--quiet] update ' in line: update_line = line if update_line: update_line = update_line.replace('[', '') update_line = update_line.replace(']', '') update_line = update_line.replace('|', ' ') parts = shlex.split(update_line) for part in parts: if part.startswith('--'): part = part.replace('--', '') params.append(part) return params def write_ssh_wrapper(module_tmpdir): try: # make sure we have full permission to the module_dir, which # may not be the case if we're sudo'ing to a non-root user if os.access(module_tmpdir, os.W_OK | os.R_OK | os.X_OK): fd, wrapper_path = tempfile.mkstemp(prefix=module_tmpdir + '/') else: raise OSError except (IOError, OSError): fd, wrapper_path = tempfile.mkstemp() fh = os.fdopen(fd, 'w+b') template = b("""#!/bin/sh if [ -z "$GIT_SSH_OPTS" ]; then BASEOPTS="" else BASEOPTS=$GIT_SSH_OPTS fi # Let ssh fail rather than prompt BASEOPTS="$BASEOPTS -o BatchMode=yes" if [ -z "$GIT_KEY" ]; then ssh $BASEOPTS "$@" else ssh -i "$GIT_KEY" -o IdentitiesOnly=yes $BASEOPTS "$@" fi """) fh.write(template) fh.close() st = os.stat(wrapper_path) os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC) return wrapper_path def set_git_ssh(ssh_wrapper, key_file, ssh_opts): if os.environ.get("GIT_SSH"): del os.environ["GIT_SSH"] os.environ["GIT_SSH"] = ssh_wrapper if os.environ.get("GIT_KEY"): del os.environ["GIT_KEY"] if key_file: os.environ["GIT_KEY"] = key_file if os.environ.get("GIT_SSH_OPTS"): del os.environ["GIT_SSH_OPTS"] if ssh_opts: os.environ["GIT_SSH_OPTS"] = ssh_opts def get_version(module, git_path, dest, ref="HEAD"): ''' samples the version of the git repo ''' cmd = "%s rev-parse %s" % (git_path, ref) rc, stdout, stderr = module.run_command(cmd, cwd=dest) sha = to_native(stdout).rstrip('\n') return sha def ssh_supports_acceptnewhostkey(module): try: ssh_path = get_bin_path('ssh') except ValueError as err: module.fail_json( msg='Remote host is missing ssh command, so you cannot ' 'use acceptnewhostkey option.', details=to_text(err)) supports_acceptnewhostkey = True cmd = [ssh_path, '-o', 'StrictHostKeyChecking=accept-new', '-V'] rc, stdout, stderr = module.run_command(cmd) if rc != 0: supports_acceptnewhostkey = False return supports_acceptnewhostkey def get_submodule_versions(git_path, module, dest, version='HEAD'): cmd = [git_path, 'submodule', 'foreach', git_path, 'rev-parse', version] (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json( msg='Unable to determine hashes of submodules', stdout=out, stderr=err, rc=rc) submodules = {} subm_name = None for line in out.splitlines(): if line.startswith("Entering '"): subm_name = line[10:-1] elif len(line.strip()) == 40: if subm_name is None: module.fail_json() submodules[subm_name] = line.strip() subm_name = None else: module.fail_json(msg='Unable to parse submodule hash line: %s' % line.strip()) if subm_name is not None: module.fail_json(msg='Unable to find hash for submodule: %s' % subm_name) return submodules def clone(git_path, module, repo, dest, remote, depth, version, bare, reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_whitelist, single_branch): ''' makes a new git repo if it does not already exist ''' dest_dirname = os.path.dirname(dest) try: os.makedirs(dest_dirname) except Exception: pass cmd = [git_path, 'clone'] if bare: cmd.append('--bare') else: cmd.extend(['--origin', remote]) is_branch_or_tag = is_remote_branch(git_path, module, dest, repo, version) or is_remote_tag(git_path, module, dest, repo, version) if depth: if version == 'HEAD' or refspec: cmd.extend(['--depth', str(depth)]) elif is_branch_or_tag: cmd.extend(['--depth', str(depth)]) cmd.extend(['--branch', version]) else: # only use depth if the remote object is branch or tag (i.e. fetchable) module.warn("Ignoring depth argument. " "Shallow clones are only available for " "HEAD, branches, tags or in combination with refspec.") if reference: cmd.extend(['--reference', str(reference)]) if single_branch: if git_version_used is None: module.fail_json(msg='Cannot find git executable at %s' % git_path) if git_version_used < LooseVersion('1.7.10'): module.warn("git version '%s' is too old to use 'single-branch'. Ignoring." % git_version_used) else: cmd.append("--single-branch") if is_branch_or_tag: cmd.extend(['--branch', version]) needs_separate_git_dir_fallback = False if separate_git_dir: if git_version_used is None: module.fail_json(msg='Cannot find git executable at %s' % git_path) if git_version_used < LooseVersion('1.7.5'): # git before 1.7.5 doesn't have separate-git-dir argument, do fallback needs_separate_git_dir_fallback = True else: cmd.append('--separate-git-dir=%s' % separate_git_dir) cmd.extend([repo, dest]) module.run_command(cmd, check_rc=True, cwd=dest_dirname) if needs_separate_git_dir_fallback: relocate_repo(module, result, separate_git_dir, os.path.join(dest, ".git"), dest) if bare and remote != 'origin': module.run_command([git_path, 'remote', 'add', remote, repo], check_rc=True, cwd=dest) if refspec: cmd = [git_path, 'fetch'] if depth: cmd.extend(['--depth', str(depth)]) cmd.extend([remote, refspec]) module.run_command(cmd, check_rc=True, cwd=dest) if verify_commit: verify_commit_sign(git_path, module, dest, version, gpg_whitelist) def has_local_mods(module, git_path, dest, bare): if bare: return False cmd = "%s status --porcelain" % (git_path) rc, stdout, stderr = module.run_command(cmd, cwd=dest) lines = stdout.splitlines() lines = list(filter(lambda c: not re.search('^\\?\\?.*$', c), lines)) return len(lines) > 0 def reset(git_path, module, dest): ''' Resets the index and working tree to HEAD. Discards any changes to tracked files in working tree since that commit. ''' cmd = "%s reset --hard HEAD" % (git_path,) return module.run_command(cmd, check_rc=True, cwd=dest) def get_diff(module, git_path, dest, repo, remote, depth, bare, before, after): ''' Return the difference between 2 versions ''' if before is None: return {'prepared': '>> Newly checked out %s' % after} elif before != after: # Ensure we have the object we are referring to during git diff ! git_version_used = git_version(git_path, module) fetch(git_path, module, repo, dest, after, remote, depth, bare, '', git_version_used) cmd = '%s diff %s %s' % (git_path, before, after) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc == 0 and out: return {'prepared': out} elif rc == 0: return {'prepared': '>> No visual differences between %s and %s' % (before, after)} elif err: return {'prepared': '>> Failed to get proper diff between %s and %s:\n>> %s' % (before, after, err)} else: return {'prepared': '>> Failed to get proper diff between %s and %s' % (before, after)} return {} def get_remote_head(git_path, module, dest, version, remote, bare): cloning = False cwd = None tag = False if remote == module.params['repo']: cloning = True elif remote == 'file://' + os.path.expanduser(module.params['repo']): cloning = True else: cwd = dest if version == 'HEAD': if cloning: # cloning the repo, just get the remote's HEAD version cmd = '%s ls-remote %s -h HEAD' % (git_path, remote) else: head_branch = get_head_branch(git_path, module, dest, remote, bare) cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, head_branch) elif is_remote_branch(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) elif is_remote_tag(git_path, module, dest, remote, version): tag = True cmd = '%s ls-remote %s -t refs/tags/%s*' % (git_path, remote, version) else: # appears to be a sha1. return as-is since it appears # cannot check for a specific sha1 on remote return version (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=cwd) if len(out) < 1: module.fail_json(msg="Could not determine remote revision for %s" % version, stdout=out, stderr=err, rc=rc) out = to_native(out) if tag: # Find the dereferenced tag if this is an annotated tag. for tag in out.split('\n'): if tag.endswith(version + '^{}'): out = tag break elif tag.endswith(version): out = tag rev = out.split()[0] return rev def is_remote_tag(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -t refs/tags/%s' % (git_path, remote, version) (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if to_native(version, errors='surrogate_or_strict') in out: return True else: return False def get_branches(git_path, module, dest): branches = [] cmd = '%s branch --no-color -a' % (git_path,) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Could not determine branch data - received %s" % out, stdout=out, stderr=err) for line in out.split('\n'): if line.strip(): branches.append(line.strip()) return branches def get_annotated_tags(git_path, module, dest): tags = [] cmd = [git_path, 'for-each-ref', 'refs/tags/', '--format', '%(objecttype):%(refname:short)'] (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Could not determine tag data - received %s" % out, stdout=out, stderr=err) for line in to_native(out).split('\n'): if line.strip(): tagtype, tagname = line.strip().split(':') if tagtype == 'tag': tags.append(tagname) return tags def is_remote_branch(git_path, module, dest, remote, version): cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if to_native(version, errors='surrogate_or_strict') in out: return True else: return False def is_local_branch(git_path, module, dest, branch): branches = get_branches(git_path, module, dest) lbranch = '%s' % branch if lbranch in branches: return True elif '* %s' % branch in branches: return True else: return False def is_not_a_branch(git_path, module, dest): branches = get_branches(git_path, module, dest) for branch in branches: if branch.startswith('* ') and ('no branch' in branch or 'detached from' in branch or 'detached at' in branch): return True return False def get_repo_path(dest, bare): if bare: repo_path = dest else: repo_path = os.path.join(dest, '.git') # Check if the .git is a file. If it is a file, it means that the repository is in external directory respective to the working copy (e.g. we are in a # submodule structure). if os.path.isfile(repo_path): with open(repo_path, 'r') as gitfile: data = gitfile.read() ref_prefix, gitdir = data.rstrip().split('gitdir: ', 1) if ref_prefix: raise ValueError('.git file has invalid git dir reference format') # There is a possibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path.split('.git')[0], gitdir) if not os.path.isdir(repo_path): raise ValueError('%s is not a directory' % repo_path) return repo_path def get_head_branch(git_path, module, dest, remote, bare=False): ''' Determine what branch HEAD is associated with. This is partly taken from lib/ansible/utils/__init__.py. It finds the correct path to .git/HEAD and reads from that file the branch that HEAD is associated with. In the case of a detached HEAD, this will look up the branch in .git/refs/remotes/<remote>/HEAD. ''' try: repo_path = get_repo_path(dest, bare) except (IOError, ValueError) as err: # No repo path found """``.git`` file does not have a valid format for detached Git dir.""" module.fail_json( msg='Current repo does not have a valid reference to a ' 'separate Git dir or it refers to the invalid path', details=to_text(err), ) # Read .git/HEAD for the name of the branch. # If we're in a detached HEAD state, look up the branch associated with # the remote HEAD in .git/refs/remotes/<remote>/HEAD headfile = os.path.join(repo_path, "HEAD") if is_not_a_branch(git_path, module, dest): headfile = os.path.join(repo_path, 'refs', 'remotes', remote, 'HEAD') branch = head_splitter(headfile, remote, module=module, fail_on_error=True) return branch def get_remote_url(git_path, module, dest, remote): '''Return URL of remote source for repo.''' command = [git_path, 'ls-remote', '--get-url', remote] (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: # There was an issue getting remote URL, most likely # command is not available in this version of Git. return None return to_native(out).rstrip('\n') def set_remote_url(git_path, module, repo, dest, remote): ''' updates repo from remote sources ''' # Return if remote URL isn't changing. remote_url = get_remote_url(git_path, module, dest, remote) if remote_url == repo or unfrackgitpath(remote_url) == unfrackgitpath(repo): return False command = [git_path, 'remote', 'set-url', remote, repo] (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: label = "set a new url %s for %s" % (repo, remote) module.fail_json(msg="Failed to %s: %s %s" % (label, out, err)) # Return False if remote_url is None to maintain previous behavior # for Git versions prior to 1.7.5 that lack required functionality. return remote_url is not None def fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=False): ''' updates repo from remote sources ''' set_remote_url(git_path, module, repo, dest, remote) commands = [] fetch_str = 'download remote objects and refs' fetch_cmd = [git_path, 'fetch'] refspecs = [] if depth: # try to find the minimal set of refs we need to fetch to get a # successful checkout currenthead = get_head_branch(git_path, module, dest, remote) if refspec: refspecs.append(refspec) elif version == 'HEAD': refspecs.append(currenthead) elif is_remote_branch(git_path, module, dest, repo, version): if currenthead != version: # this workaround is only needed for older git versions # 1.8.3 is broken, 1.9.x works # ensure that remote branch is available as both local and remote ref refspecs.append('+refs/heads/%s:refs/heads/%s' % (version, version)) refspecs.append('+refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version)) elif is_remote_tag(git_path, module, dest, repo, version): refspecs.append('+refs/tags/' + version + ':refs/tags/' + version) if refspecs: # if refspecs is empty, i.e. version is neither heads nor tags # assume it is a version hash # fall back to a full clone, otherwise we might not be able to checkout # version fetch_cmd.extend(['--depth', str(depth)]) if not depth or not refspecs: # don't try to be minimalistic but do a full clone # also do this if depth is given, but version is something that can't be fetched directly if bare: refspecs = ['+refs/heads/*:refs/heads/*', '+refs/tags/*:refs/tags/*'] else: # ensure all tags are fetched if git_version_used >= LooseVersion('1.9'): fetch_cmd.append('--tags') else: # old git versions have a bug in --tags that prevents updating existing tags commands.append((fetch_str, fetch_cmd + [remote])) refspecs = ['+refs/tags/*:refs/tags/*'] if refspec: refspecs.append(refspec) if force: fetch_cmd.append('--force') fetch_cmd.extend([remote]) commands.append((fetch_str, fetch_cmd + refspecs)) for (label, command) in commands: (rc, out, err) = module.run_command(command, cwd=dest) if rc != 0: module.fail_json(msg="Failed to %s: %s %s" % (label, out, err), cmd=command) def submodules_fetch(git_path, module, remote, track_submodules, dest): changed = False if not os.path.exists(os.path.join(dest, '.gitmodules')): # no submodules return changed gitmodules_file = open(os.path.join(dest, '.gitmodules'), 'r') for line in gitmodules_file: # Check for new submodules if not changed and line.strip().startswith('path'): path = line.split('=', 1)[1].strip() # Check that dest/path/.git exists if not os.path.exists(os.path.join(dest, path, '.git')): changed = True # Check for updates to existing modules if not changed: # Fetch updates begin = get_submodule_versions(git_path, module, dest) cmd = [git_path, 'submodule', 'foreach', git_path, 'fetch'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if rc != 0: module.fail_json(msg="Failed to fetch submodules: %s" % out + err) if track_submodules: # Compare against submodule HEAD # FIXME: determine this from .gitmodules version = 'master' after = get_submodule_versions(git_path, module, dest, '%s/%s' % (remote, version)) if begin != after: changed = True else: # Compare against the superproject's expectation cmd = [git_path, 'submodule', 'status'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if rc != 0: module.fail_json(msg='Failed to retrieve submodule status: %s' % out + err) for line in out.splitlines(): if line[0] != ' ': changed = True break return changed def submodule_update(git_path, module, dest, track_submodules, force=False): ''' init and update any submodules ''' # get the valid submodule params params = get_submodule_update_params(module, git_path, dest) # skip submodule commands if .gitmodules is not present if not os.path.exists(os.path.join(dest, '.gitmodules')): return (0, '', '') cmd = [git_path, 'submodule', 'sync'] (rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) if 'remote' in params and track_submodules: cmd = [git_path, 'submodule', 'update', '--init', '--recursive', '--remote'] else: cmd = [git_path, 'submodule', 'update', '--init', '--recursive'] if force: cmd.append('--force') (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to init/update submodules: %s" % out + err) return (rc, out, err) def set_remote_branch(git_path, module, dest, remote, version, depth): """set refs for the remote branch version This assumes the branch does not yet exist locally and is therefore also not checked out. Can't use git remote set-branches, as it is not available in git 1.7.1 (centos6) """ branchref = "+refs/heads/%s:refs/heads/%s" % (version, version) branchref += ' +refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version) cmd = "%s fetch --depth=%s %s %s" % (git_path, depth, remote, branchref) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to fetch branch from remote: %s" % version, stdout=out, stderr=err, rc=rc) def switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_whitelist): cmd = '' if version == 'HEAD': branch = get_head_branch(git_path, module, dest, remote) (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, branch), cwd=dest) if rc != 0: module.fail_json(msg="Failed to checkout branch %s" % branch, stdout=out, stderr=err, rc=rc) cmd = "%s reset --hard %s/%s --" % (git_path, remote, branch) else: # FIXME check for local_branch first, should have been fetched already if is_remote_branch(git_path, module, dest, remote, version): if depth and not is_local_branch(git_path, module, dest, version): # git clone --depth implies --single-branch, which makes # the checkout fail if the version changes # fetch the remote branch, to be able to check it out next set_remote_branch(git_path, module, dest, remote, version, depth) if not is_local_branch(git_path, module, dest, version): cmd = "%s checkout --track -b %s %s/%s" % (git_path, version, remote, version) else: (rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, version), cwd=dest) if rc != 0: module.fail_json(msg="Failed to checkout branch %s" % version, stdout=out, stderr=err, rc=rc) cmd = "%s reset --hard %s/%s" % (git_path, remote, version) else: cmd = "%s checkout --force %s" % (git_path, version) (rc, out1, err1) = module.run_command(cmd, cwd=dest) if rc != 0: if version != 'HEAD': module.fail_json(msg="Failed to checkout %s" % (version), stdout=out1, stderr=err1, rc=rc, cmd=cmd) else: module.fail_json(msg="Failed to checkout branch %s" % (branch), stdout=out1, stderr=err1, rc=rc, cmd=cmd) if verify_commit: verify_commit_sign(git_path, module, dest, version, gpg_whitelist) return (rc, out1, err1) def verify_commit_sign(git_path, module, dest, version, gpg_whitelist): if version in get_annotated_tags(git_path, module, dest): git_sub = "verify-tag" else: git_sub = "verify-commit" cmd = "%s %s %s" % (git_path, git_sub, version) if gpg_whitelist: cmd += " --raw" (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg='Failed to verify GPG signature of commit/tag "%s"' % version, stdout=out, stderr=err, rc=rc) if gpg_whitelist: fingerprint = get_gpg_fingerprint(err) if fingerprint not in gpg_whitelist: module.fail_json(msg='The gpg_whitelist does not include the public key "%s" for this commit' % fingerprint, stdout=out, stderr=err, rc=rc) return (rc, out, err) def get_gpg_fingerprint(output): """Return a fingerprint of the primary key. Ref: https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;hb=HEAD#l482 """ for line in output.splitlines(): data = line.split() if data[1] != 'VALIDSIG': continue # if signed with a subkey, this contains the primary key fingerprint data_id = 11 if len(data) == 11 else 2 return data[data_id] def git_version(git_path, module): """return the installed version of git""" cmd = "%s --version" % git_path (rc, out, err) = module.run_command(cmd) if rc != 0: # one could fail_json here, but the version info is not that important, # so let's try to fail only on actual git commands return None rematch = re.search('git version (.*)$', to_native(out)) if not rematch: return None return LooseVersion(rematch.groups()[0]) def git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version): """ Create git archive in given source directory """ cmd = [git_path, 'archive', '--format', archive_fmt, '--output', archive, version] if archive_prefix is not None: cmd.insert(-1, '--prefix') cmd.insert(-1, archive_prefix) (rc, out, err) = module.run_command(cmd, cwd=dest) if rc != 0: module.fail_json(msg="Failed to perform archive operation", details="Git archive command failed to create " "archive %s using %s directory." "Error: %s" % (archive, dest, err)) return rc, out, err def create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result): """ Helper function for creating archive using git_archive """ all_archive_fmt = {'.zip': 'zip', '.gz': 'tar.gz', '.tar': 'tar', '.tgz': 'tgz'} _, archive_ext = os.path.splitext(archive) archive_fmt = all_archive_fmt.get(archive_ext, None) if archive_fmt is None: module.fail_json(msg="Unable to get file extension from " "archive file name : %s" % archive, details="Please specify archive as filename with " "extension. File extension can be one " "of ['tar', 'tar.gz', 'zip', 'tgz']") repo_name = repo.split("/")[-1].replace(".git", "") if os.path.exists(archive): # If git archive file exists, then compare it with new git archive file. # if match, do nothing # if does not match, then replace existing with temp archive file. tempdir = tempfile.mkdtemp() new_archive_dest = os.path.join(tempdir, repo_name) new_archive = new_archive_dest + '.' + archive_fmt git_archive(git_path, module, dest, new_archive, archive_fmt, archive_prefix, version) # filecmp is supposed to be efficient than md5sum checksum if filecmp.cmp(new_archive, archive): result.update(changed=False) # Cleanup before exiting try: shutil.rmtree(tempdir) except OSError: pass else: try: shutil.move(new_archive, archive) shutil.rmtree(tempdir) result.update(changed=True) except OSError as e: module.fail_json(msg="Failed to move %s to %s" % (new_archive, archive), details=u"Error occurred while moving : %s" % to_text(e)) else: # Perform archive from local directory git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version) result.update(changed=True) # =========================================== def main(): module = AnsibleModule( argument_spec=dict( dest=dict(type='path'), repo=dict(required=True, aliases=['name']), version=dict(default='HEAD'), remote=dict(default='origin'), refspec=dict(default=None), reference=dict(default=None), force=dict(default='no', type='bool'), depth=dict(default=None, type='int'), clone=dict(default='yes', type='bool'), update=dict(default='yes', type='bool'), verify_commit=dict(default='no', type='bool'), gpg_whitelist=dict(default=[], type='list', elements='str'), accept_hostkey=dict(default='no', type='bool'), accept_newhostkey=dict(default='no', type='bool'), key_file=dict(default=None, type='path', required=False), ssh_opts=dict(default=None, required=False), executable=dict(default=None, type='path'), bare=dict(default='no', type='bool'), recursive=dict(default='yes', type='bool'), single_branch=dict(default=False, type='bool'), track_submodules=dict(default='no', type='bool'), umask=dict(default=None, type='raw'), archive=dict(type='path'), archive_prefix=dict(), separate_git_dir=dict(type='path'), ), mutually_exclusive=[('separate_git_dir', 'bare'), ('accept_hostkey', 'accept_newhostkey')], required_by={'archive_prefix': ['archive']}, supports_check_mode=True ) dest = module.params['dest'] repo = module.params['repo'] version = module.params['version'] remote = module.params['remote'] refspec = module.params['refspec'] force = module.params['force'] depth = module.params['depth'] update = module.params['update'] allow_clone = module.params['clone'] bare = module.params['bare'] verify_commit = module.params['verify_commit'] gpg_whitelist = module.params['gpg_whitelist'] reference = module.params['reference'] single_branch = module.params['single_branch'] git_path = module.params['executable'] or module.get_bin_path('git', True) key_file = module.params['key_file'] ssh_opts = module.params['ssh_opts'] umask = module.params['umask'] archive = module.params['archive'] archive_prefix = module.params['archive_prefix'] separate_git_dir = module.params['separate_git_dir'] result = dict(changed=False, warnings=list()) if module.params['accept_hostkey']: if ssh_opts is not None: if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): ssh_opts += " -o StrictHostKeyChecking=no" else: ssh_opts = "-o StrictHostKeyChecking=no" if module.params['accept_newhostkey']: if not ssh_supports_acceptnewhostkey(module): module.warn("Your ssh client does not support accept_newhostkey option, therefore it cannot be used.") else: if ssh_opts is not None: if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): ssh_opts += " -o StrictHostKeyChecking=accept-new" else: ssh_opts = "-o StrictHostKeyChecking=accept-new" # evaluate and set the umask before doing anything else if umask is not None: if not isinstance(umask, string_types): module.fail_json(msg="umask must be defined as a quoted octal integer") try: umask = int(umask, 8) except Exception: module.fail_json(msg="umask must be an octal integer", details=str(sys.exc_info()[1])) os.umask(umask) # Certain features such as depth require a file:/// protocol for path based urls # so force a protocol here ... if os.path.expanduser(repo).startswith('/'): repo = 'file://' + os.path.expanduser(repo) # We screenscrape a huge amount of git commands so use C locale anytime we # call run_command() module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C') if separate_git_dir: separate_git_dir = os.path.realpath(separate_git_dir) gitconfig = None if not dest and allow_clone: module.fail_json(msg="the destination directory must be specified unless clone=no") elif dest: dest = os.path.abspath(dest) try: repo_path = get_repo_path(dest, bare) if separate_git_dir and os.path.exists(repo_path) and separate_git_dir != repo_path: result['changed'] = True if not module.check_mode: relocate_repo(module, result, separate_git_dir, repo_path, dest) repo_path = separate_git_dir except (IOError, ValueError) as err: # No repo path found """``.git`` file does not have a valid format for detached Git dir.""" module.fail_json( msg='Current repo does not have a valid reference to a ' 'separate Git dir or it refers to the invalid path', details=to_text(err), ) gitconfig = os.path.join(repo_path, 'config') # create a wrapper script and export # GIT_SSH=<path> as an environment variable # for git to use the wrapper script ssh_wrapper = write_ssh_wrapper(module.tmpdir) set_git_ssh(ssh_wrapper, key_file, ssh_opts) module.add_cleanup_file(path=ssh_wrapper) git_version_used = git_version(git_path, module) if depth is not None and git_version_used < LooseVersion('1.9.1'): module.warn("git version is too old to fully support the depth argument. Falling back to full checkouts.") depth = None recursive = module.params['recursive'] track_submodules = module.params['track_submodules'] result.update(before=None) local_mods = False if (dest and not os.path.exists(gitconfig)) or (not dest and not allow_clone): # if there is no git configuration, do a clone operation unless: # * the user requested no clone (they just want info) # * we're doing a check mode test # In those cases we do an ls-remote if module.check_mode or not allow_clone: remote_head = get_remote_head(git_path, module, dest, version, repo, bare) result.update(changed=True, after=remote_head) if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff module.exit_json(**result) # there's no git config, so clone clone(git_path, module, repo, dest, remote, depth, version, bare, reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_whitelist, single_branch) elif not update: # Just return having found a repo already in the dest path # this does no checking that the repo is the actual repo # requested. result['before'] = get_version(module, git_path, dest) result.update(after=result['before']) if archive: # Git archive is not supported by all git servers, so # we will first clone and perform git archive from local directory if module.check_mode: result.update(changed=True) module.exit_json(**result) create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) module.exit_json(**result) else: # else do a pull local_mods = has_local_mods(module, git_path, dest, bare) result['before'] = get_version(module, git_path, dest) if local_mods: # failure should happen regardless of check mode if not force: module.fail_json(msg="Local modifications exist in repository (force=no).", **result) # if force and in non-check mode, do a reset if not module.check_mode: reset(git_path, module, dest) result.update(changed=True, msg='Local modifications exist.') # exit if already at desired sha version if module.check_mode: remote_url = get_remote_url(git_path, module, dest, remote) remote_url_changed = remote_url and remote_url != repo and unfrackgitpath(remote_url) != unfrackgitpath(repo) else: remote_url_changed = set_remote_url(git_path, module, repo, dest, remote) result.update(remote_url_changed=remote_url_changed) if module.check_mode: remote_head = get_remote_head(git_path, module, dest, version, remote, bare) result.update(changed=(result['before'] != remote_head or remote_url_changed), after=remote_head) # FIXME: This diff should fail since the new remote_head is not fetched yet?! if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff module.exit_json(**result) else: fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=force) result['after'] = get_version(module, git_path, dest) # switch to version specified regardless of whether # we got new revisions from the repository if not bare: switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_whitelist) # Deal with submodules submodules_updated = False if recursive and not bare: submodules_updated = submodules_fetch(git_path, module, remote, track_submodules, dest) if submodules_updated: result.update(submodules_changed=submodules_updated) if module.check_mode: result.update(changed=True, after=remote_head) module.exit_json(**result) # Switch to version specified submodule_update(git_path, module, dest, track_submodules, force=force) # determine if we changed anything result['after'] = get_version(module, git_path, dest) if result['before'] != result['after'] or local_mods or submodules_updated or remote_url_changed: result.update(changed=True) if module._diff: diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after']) if diff: result['diff'] = diff if archive: # Git archive is not supported by all git servers, so # we will first clone and perform git archive from local directory if module.check_mode: result.update(changed=True) module.exit_json(**result) create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) module.exit_json(**result) if __name__ == '__main__': main()
Java
<?php /**************************************************************************/ /* PHP-NUKE: Advanced Content Management System */ /* ============================================ */ /* */ /* This is the language module with all the system messages */ /* */ /* If you made a translation, please go to the site and send to me */ /* the translated file. Please keep the original text order by modules, */ /* and just one message per line, also double check your translation! */ /* */ /* You need to change the second quoted phrase, not the capital one! */ /* */ /* If you need to use double quotes (') remember to add a backslash (\), */ /* so your entry will look like: This is \'double quoted\' text. */ /* And, if you use HTML code, please double check it. */ /* If you create the correct translation for this file please post it */ /* in the forums at www.ravenphpscripts.com */ /* */ /**************************************************************************/ define('_MA_ARTICLE','Articles'); define('_MA_ARTICLEID','Article #'); define('_MA_ARTICLE_AUTHOR_UPDATE','has been tied to '); define('_MA_ARTICLE_UPDATE_WARNING','You must enter an Article ID <strong>and</strong> an author username to move an article.'); define('_MA_READS_TO_MAKE_TOP10','Reads to make top 10: '); define('_MA_NO_AUTHORS','No User Authors'); define('_TOPWELCOME','Welcome to the Articles and Authors page for '); define('_WELCOME','Welcome'); define('_SUBMITCONTENT','Submit Content'); define('_SUBMITARTICLE','Submit Article'); define('_WRITEREVIEW','Write Review'); define('_SUBMITWEBLINK','Submit Web Link'); define('_STATISTICS','Statistics'); define('_QUICKSTATOVERVIEW','Quick Stat Overview'); define('_TOPRECENTSTORIES','Top Stories in the last 30 days'); define('_TOPALLSTORIES','Top Stories of all time'); define('_TOPAUTHORS','Top Authors'); define('_MONTHLYARTICLEOVERVIEW','Monthly Article Overview'); define('_ARTICLECOUNTBYTOPIC','Article Count By Topic'); define('_ARTICLECOUNTBYCATEGORY','Article Count By Category'); define('_STORYREADS','Reads'); define('_STORIES','Stories'); define('_STORYAVGREADS','Avg Reads'); define('_OVERALL','Overall'); define('_RECENT','Recent'); define('_STORYTITLE','Title'); define('_STORYDATE','Date'); define('_AUTHORNAME','Author'); define('_READSPERDAY','Reads Per Day'); define('_READSTORIES','most read stories'); define('_TOP','Top'); define('_AUTHORS','Authors'); define('_NUMSTORIES','# Stories'); define('_TOTALRATINGS','Total Ratings'); define('_AVGRATINGS','Avg Rating'); define('_MONTH','Month'); define('_CATEGORY','Category'); define('_LVOTES','votes'); define('_HITS','Hits'); define('_LINKSDATESTRING','%d. %m. %Y'); ?>
Java
/* This file is part of SpatGRIS. Developers: Samuel Béland, Olivier Bélanger, Nicolas Masson SpatGRIS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SpatGRIS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SpatGRIS. If not, see <http://www.gnu.org/licenses/>. */ #include "sg_AbstractSliceComponent.hpp" //============================================================================== AbstractSliceComponent::AbstractSliceComponent(GrisLookAndFeel & lookAndFeel, SmallGrisLookAndFeel & smallLookAndFeel) : mLayout(LayoutComponent::Orientation::vertical, false, false, lookAndFeel) , mVuMeter(smallLookAndFeel) , mMuteSoloComponent(*this, lookAndFeel, smallLookAndFeel) { JUCE_ASSERT_MESSAGE_THREAD; addAndMakeVisible(mLayout); } //============================================================================== void AbstractSliceComponent::setState(PortState const state, bool const soloMode) { JUCE_ASSERT_MESSAGE_THREAD; mMuteSoloComponent.setPortState(state); mVuMeter.setMuted(soloMode ? state != PortState::solo : state == PortState::muted); repaint(); }
Java
#include "main/SimpleCardProtocol.hh" #include "bridge/BridgeConstants.hh" #include "bridge/CardShuffle.hh" #include "bridge/CardType.hh" #include "bridge/Position.hh" #include "engine/SimpleCardManager.hh" #include "main/Commands.hh" #include "main/PeerCommandSender.hh" #include "messaging/CardTypeJsonSerializer.hh" #include "messaging/FunctionMessageHandler.hh" #include "messaging/JsonSerializer.hh" #include "messaging/JsonSerializerUtility.hh" #include "messaging/UuidJsonSerializer.hh" #include "Logging.hh" #include <algorithm> #include <optional> #include <string> #include <tuple> #include <utility> namespace Bridge { namespace Main { using CardVector = std::vector<CardType>; using Engine::CardManager; using Messaging::failure; using Messaging::Identity; using Messaging::JsonSerializer; using Messaging::Reply; using Messaging::success; class SimpleCardProtocol::Impl : public Bridge::Observer<CardManager::ShufflingState> { public: Impl( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender); bool acceptPeer( const Identity& identity, const PositionVector& positions); Reply<> deal(const Identity& identity, const CardVector& cards); const Uuid gameUuid; const std::shared_ptr<Engine::SimpleCardManager> cardManager { std::make_shared<Engine::SimpleCardManager>()}; private: void handleNotify(const CardManager::ShufflingState& state) override; bool expectingCards {false}; std::optional<Identity> leaderIdentity; const std::shared_ptr<PeerCommandSender> peerCommandSender; }; SimpleCardProtocol::Impl::Impl( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender) : gameUuid {gameUuid}, peerCommandSender {std::move(peerCommandSender)} { } void SimpleCardProtocol::Impl::handleNotify( const CardManager::ShufflingState& state) { if (state == CardManager::ShufflingState::REQUESTED) { if (!leaderIdentity) { log(LogLevel::DEBUG, "Simple card protocol: Generating deck"); auto cards = generateShuffledDeck(); assert(cardManager); cardManager->shuffle(cards.begin(), cards.end()); dereference(peerCommandSender).sendCommand( JsonSerializer {}, DEAL_COMMAND, std::pair {GAME_COMMAND, gameUuid}, std::pair {CARDS_COMMAND, std::move(cards)}); } else { log(LogLevel::DEBUG, "Simple card protocol: Expecting deck"); expectingCards = true; } } } bool SimpleCardProtocol::Impl::acceptPeer( const Identity& identity, const PositionVector& positions) { if (std::find(positions.begin(), positions.end(), Positions::NORTH) != positions.end()) { leaderIdentity = identity; } return true; } Reply<> SimpleCardProtocol::Impl::deal( const Identity& identity, const CardVector& cards) { log(LogLevel::DEBUG, "Deal command from %s", identity); if (expectingCards && leaderIdentity == identity) { cardManager->shuffle(cards.begin(), cards.end()); expectingCards = false; return success(); } return failure(); } SimpleCardProtocol::SimpleCardProtocol( const Uuid& gameUuid, std::shared_ptr<PeerCommandSender> peerCommandSender) : impl { std::make_shared<Impl>(gameUuid, std::move(peerCommandSender))} { assert(impl->cardManager); impl->cardManager->subscribe(impl); } bool SimpleCardProtocol::handleAcceptPeer( const Identity& identity, const PositionVector& positions, const OptionalArgs&) { assert(impl); return impl->acceptPeer(identity, positions); } void SimpleCardProtocol::handleInitialize() { } std::shared_ptr<Messaging::MessageHandler> SimpleCardProtocol::handleGetDealMessageHandler() { return Messaging::makeMessageHandler( *impl, &Impl::deal, JsonSerializer {}, std::tuple {CARDS_COMMAND}); } SimpleCardProtocol::SocketVector SimpleCardProtocol::handleGetSockets() { return {}; } std::shared_ptr<CardManager> SimpleCardProtocol::handleGetCardManager() { assert(impl); return impl->cardManager; } } }
Java
#define BOOST_TEST_MODULE sugar_integration_tests #include <boost/test/included/unit_test.hpp>
Java
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include "MantidDataHandling/RemoveLogs.h" #include "MantidAPI/FileProperty.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/Glob.h" #include "MantidKernel/PropertyWithValue.h" #include "MantidKernel/Strings.h" #include "MantidKernel/TimeSeriesProperty.h" #include <Poco/DateTimeFormat.h> #include <Poco/DateTimeParser.h> #include <Poco/DirectoryIterator.h> #include <Poco/File.h> #include <Poco/Path.h> #include <boost/algorithm/string.hpp> #include <algorithm> #include <fstream> // used to get ifstream #include <sstream> namespace Mantid { namespace DataHandling { // Register the algorithm into the algorithm factory DECLARE_ALGORITHM(RemoveLogs) using namespace Kernel; using namespace API; using DataObjects::Workspace2D_sptr; /// Empty default constructor RemoveLogs::RemoveLogs() {} /// Initialisation method. void RemoveLogs::init() { // When used as a Child Algorithm the workspace name is not used - hence the // "Anonymous" to satisfy the validator declareProperty( make_unique<WorkspaceProperty<MatrixWorkspace>>("Workspace", "Anonymous", Direction::InOut), "The name of the workspace to which the log data will be removed"); declareProperty( make_unique<ArrayProperty<std::string>>("KeepLogs", Direction::Input), "List(comma separated) of logs to be kept"); } /** Executes the algorithm. Reading in log file(s) * * @throw Mantid::Kernel::Exception::FileError Thrown if file is not *recognised to be a raw datafile or log file * @throw std::runtime_error Thrown with Workspace problems */ void RemoveLogs::exec() { // Get the input workspace and retrieve run from workspace. // the log file(s) will be loaded into the run object of the workspace const MatrixWorkspace_sptr localWorkspace = getProperty("Workspace"); const std::vector<Mantid::Kernel::Property *> &logData = localWorkspace->run().getLogData(); std::vector<std::string> keepLogs = getProperty("KeepLogs"); std::vector<std::string> logNames; logNames.reserve(logData.size()); for (const auto property : logData) { logNames.push_back(property->name()); } for (const auto &name : logNames) { auto location = std::find(keepLogs.cbegin(), keepLogs.cend(), name); if (location == keepLogs.cend()) { localWorkspace->mutableRun().removeLogData(name); } } // operation was a success and ended normally return; } } // namespace DataHandling } // namespace Mantid
Java
/** * file mirror/doc/factory_generator.hpp * Documentation only header * * @author Matus Chochlik * * Copyright 2008-2010 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef MIRROR_DOC_FACTORY_GENERATOR_1011291729_HPP #define MIRROR_DOC_FACTORY_GENERATOR_1011291729_HPP #ifdef MIRROR_DOCUMENTATION_ONLY #include <mirror/config.hpp> MIRROR_NAMESPACE_BEGIN /** @page mirror_factory_generator_utility Factory generator utility * * @section mirror_factory_generator_intro Introduction * * The factory generator utility allows to easily create implementations * of object factories at compile-time by using the meta-data provided * by Mirror. * By object factories we mean here classes, which can create * instances of various types (@c Products), but do not require that the caller * supplies the parameters for the construction directly. * Factories pick or let the application user pick the @c Product 's most * appropriate constructor, they gather the necessary parameters in * a generic, application-specific way and use the selected constructor * to create an instance of the @c Product. * * Obviously the most interesting feature of these factories is, that * they separate the caller (who just needs to get an instance of the * specified type) from the actual method of creation which involves * choosing of right constructor and supplying the * required parameters, which in turn can also be constructed or supplied * in some other way (for example from a pool of existing objects). * * This is useful when we need to create instances of (possibly different) * types having multiple constructors from a single point in code and we want * the method of construction to be determined by parameters available only * at run-time. * * Here follows a brief list of examples: * - Creation of objects based on user input from a GUI: The factory object * creates a GUI component (a dialog for example) having the necessary * controls for selecting one of the constructors of the constructed type * and for the input of the values of all parameters for the selected * constructor. * - Creation of objects from a database dataset: The factory can go through * the list of constructors and find the one whose parameters are matching * to the columns in a database dataset. Then it calls this constructor * and passes the values of the matching columns as the parameters, doing * the appropriate type conversions where necessary. By doing this repeatedly * we can create multiple objects, each representing a different row in * the dataset. * - Creation of objects from other external representations: Similar to * the option above one can create instances from other file or stream-based * data representations like (XML, JSON, XDR, etc.) * * The factories generated by this utility can then be used for example * for the implementation of the Abstract factory design pattern, where * even the exact type of the created object is not known. * * Because the factory classes are created by a generic meta-program * at compile-time a good optimizing compiler can generate source * code, which is as efficient as if the factories were hand-coded. * This however depends on the implementation of the application-specific * parts that are supplied to the factory generator. * * @section mirror_factory_generator_principles Principles * * As we mentioned in the introduction, the factory must handle two important * tasks during the construction of an instance: * - Choose the constructor (default, copy, custom). * - Supply the parameters to the constructor if necessary. * * The implementation of these tasks is also the most distinctive thing * about a particular factory. The rest of the process is the same regardless * of the @c Product type. This is why the factory generator utility provides * all the common boilerplate code and the application only specifies how * a constuctor is selected and how the arguments are supplied to it. * * Furthermore there are two basic ways how to supply a parameter value: * - Create one from scratch by using the same factory with a different * @c Product type recursivelly. * - Use an existing instance which can be acquired from a pool of instances, * or be a result of a functor call. * * In order to create a factory, the application needs to supply the factory * generator with two template classes with the following signature: * * @code * template <class Product, class SourceTraits> * class constructor_parameter_source; * @endcode * * The first one is referred to as a @c Manufacturer and is responsible * for the creation of new parameter values. The second template is * referred to as @c Suppliers and is responsible for returning of an existing * value. * * One of the specializations of the @c Manufacturer template, namely the one * having the @c void type as @c Product is referred to as @c Manager. * This @c Manager is responsible for the selecting of the constructor that * to be used. * * Both of these templates have the following parameters: * - @c Product is the type produced by the source. A @c Manufacturer creates * a new instance of @c Product and @c Suppliers return an * existing instance of @c Product (one of possibly multiple candidates) * - @c SourceTraits is an optional type parameter used by some factory * implementations for the configuration and fine tuning of the factory's * behavior and appearance. * * Whether these sources (@c Manufacturer or @c Suppliers) are going to be used * for the supplying of a constructor parameter and if so, which of them, * depends on the selected constructor: * - If the @c Product 's default constructor is selected, then no parameters * are required and neither the @c Manufacturer nor the @c Suppliers are used. * - If the copy constructor is selected then the @c Suppliers template * (which returns existing instances of the same type) is used. * - If another constructor was picked, then the @c Manufacturer template is used * to create the individual parameters. * * @subsection mirror_factory_generator_manufacturer The Manufacturer * * The application-defined @c Manufacturer template should have several * distinct specializations, which serve for different purposes. * * As mentioned before, a @c Manufacturer with the @c void type as @c Product * serves as a manager which is responsible for choosing the constructor * that is ultimately to be used for the construction of an instance * of the @c Product. This means that besides the regular @c Manufacturer * which in fact creates the instances, there is one instance of the @c Manager * for every @c Product in the generated factory. The @c Manager has also * a different interface then the other @c Manufacturers. * * Other specializations of the @c Manufacturer should handle the creation of * values of some special types (like the native C++ types; boolean, integers, * floating points, strings, etc), considered atomic (i.e. not eleborated) * by the factory. Values of such types can be input directly by the user * into some kind of UI, they can be converted from some external representation * like the value of row/column in a database dataset, or a value of an XML * attribute, etc. * * The default implementation of the @c Manufacturer is for elaborated types and it * uses a generated factory to recursively create instances of the constructor * parameters. * * @subsection mirror_factory_generator_suppliers The Suppliers * * The @c Suppliers template is responsible for returning existing instances * of the type passed as the @c Product parameter. Depending on the specific * factory and the @c Product, the suppliers may or may not have means * to get instances of that particular @c Product type and should be implemented * accordingly. If there are multiple possible sources of values of a type * then the specialization of @c Suppliers must provide some means how to * select which of the external sources is to be used. * * @subsection mirror_factory_generator_source_traits The parameter source traits * * For additional flexibility both the @c Manufacturer and the @c Suppliers * template have (besides the @c Product type they create) an aditional template * type parameter called @c SourceTraits. This type is usually defined together * with the @c Manufacturer and @c Suppliers and is passed to the instantiations * of these templates by the factory generator when a new factory is created. * The factory generator treats this type as opaque. * If a concrete implementation of the parameter sources (@c Manufacturer and * @c Suppliers) has no use for this additional parameter, the void type * can be passed to the factory generator. * * @subsection mirror_factory_generator_factory_maker Factory and Factory Maker * * The @c Manufacturers, the @c Suppliers, the @c SourceTraits and * the boilerplate code common to all factories is tied together by * the @c mirror::factory template, with the following definition: * * @code * template < * template <class, class> class Manufacturer, * template <class, class> class Suppliers, * class SourceTraits, * typename Product * > class factory * { * public: * Product operator()(void); * Product* new_(void); * }; * @endcode * * Perhaps a more convenient way how to create factories, especially when * one wants to create multiple factories of the same kind (with the same * @c Manufacturers, @c Suppliers and @c SourceTraits) for constructing * different @c Product types is to use the @c mirror::factory_maker template * class defined as follows: * * @code * template < * template <class, class> class Manufacturer, * template <class, class> class Suppliers, * class SourceTraits * > struct factory_maker * { * template <typename Product> * struct factory * { * typedef factory<Manufacturer, Suppliers, SourceTraits, Product> type; * }; * }; * @endcode * * @section mirror_factory_generator_usage Usage * * The basic usage of the factory generator utility should be obvious from the above; * It is necessary to implement the @c Manufacturer and the @c Suppliers * templates (and possibly also the @c SourceTraits) and then use either the * @c mirror::factory template directly or the @c mirror::factory_maker 's factory * nested template to create an instantiation of a factory constructing instances * of a @c Product type: * * @code * // use the factory directly ... * mirror::factory<my_manuf, my_suppl, my_traits, my_product_1> f1; * my_product_1 x1(f1()); * my_product_1* px1(f1.new_()); * * // ... * // or use the factory_maker * typedef mirror::factory_maker<my_manuf, my_suppl, my_traits> my_fact_maker; * my_fact_maker::factory<my_product_1>::type f1; * my_fact_maker::factory<my_product_2>::type f2; * my_fact_maker::factory<my_product_3>::type f2; * // * my_product_1 x1(f1()); * my_product_1* px1(f1.new_()); * my_product_2 x2(f2()); * my_product_3* px3(f3.new_()); * @endcode * * @subsection mirror_factory_generator_tutorials Tutorials and other resources * * Here follows a list of references to other pages dealing with the factory * generator utility in depth and also tutorials showing how to write * the plugins (the Managers, Manufacturers and Suppliers) for the factory * generator: * * - @subpage mirror_fact_gen_in_depth * - @subpage mirror_sql_fact_gen_tutorial * * @section mirror_factory_generator_existing_templates Existing Manufacturers and Suppliers * * The Mirror library provides several working sample implementations * of the @c Manufacturer and @c Suppliers templates. * The following example shows the usage of the @c wx_gui_factory template * with the factory generator utility in a simple wxWidgets-based application. * The generated factory creates a wxDialog containing all necessary widgets * for the selection of the constructor to be used and for the input of all * parameters required by the selected constructor. Screenshots of dialogs * generated by this implementation can be found * @link mirror_wx_gui_fact_examples here@endlink. */ MIRROR_NAMESPACE_END #endif // DOCUMENTATION_ONLY #endif //include guard
Java
#sidebar { display: none; } #sidebar * { border-radius: 0 !important; } #sidebar > nav { background-color: #222222; } @media (min-width: 768px) { #sidebar { position: fixed; top: 0; bottom: 0; left: 0; z-index: 1000; display: block; padding: 0; overflow-x: hidden; overflow-y: auto; background-color: #222222; border-right: 1px solid #111111; } } li.brand {background-color: #000;} .brand a.brand { padding: 0; width: 100%; height: 50px; margin: 0; display: block; background-image: url(../img/logo-light.png); background-position: center; background-size: 90%; background-repeat: no-repeat; } #sidebar .nav.nav-sidebar { border-bottom: 1px solid #ccc; } #sidebar .nav.nav-sidebar:last-child { border-bottom: 0; } #sidebar ul, #sidebar li, #sidebar li a { display: block; width: 100%; } #sidebar a.gradient > i { width: 24px; font-size: 16px; text-align: left; } #sidebar a.gradient { border-right: 5px solid transparent; } #sidebar a.gradient:hover, #sidebar a.gradient:active, #sidebar a.gradient:focus { border-right: 5px solid #00BCD4; } #sidebar li.active a.gradient, #sidebar a.gradient.active { border-right: 5px solid #ff0000; } #sidebar li.dropdown ul li.normal.by-0:not(:last-child) { border-bottom: 1px solid #3e3e3e !important; } .child-bg { background-color: #111; } #sidebar li.dropdown a span.caret { position: absolute; right: 15px; top: calc(50% - 1px); } #sidebar .activated { border-left: 3px solid #f43000; } #sidebar li.dropdown ul li a { padding-top: 8px; padding-bottom: 8px; } #sidebar li.dropdown ul li a:hover, #sidebar li.dropdown ul li a:active, #sidebar li.dropdown ul li a:focus { color: #848484; background-color: #0d0d0d; }
Java
namespace GemsCraft.Entities.Metadata.Flags { public enum TameableFlags: byte { IsSitting = 0x01, /// <summary> /// Only used with wolves /// </summary> IsAngry = 0x02, IsTamed = 0x04 } }
Java
import React from 'react'; import { connect } from 'react-redux'; import { View, Text, FlatList } from 'react-native'; import sb from 'react-native-style-block'; import dateHelper from '@shared/utils/date-helper'; import appConfig from '../config.app'; import ConvItem from '../components/ConvItem'; import { reloadConverseList } from '@shared/redux/actions/chat'; import styled from 'styled-components/native'; import TRefreshControl from '../components/TComponent/TRefreshControl'; import { ChatType } from '../types/params'; import type { TRPGState, TRPGDispatchProp } from '@redux/types/__all__'; import _get from 'lodash/get'; import _values from 'lodash/values'; import _sortBy from 'lodash/sortBy'; import _size from 'lodash/size'; import { TMemo } from '@shared/components/TMemo'; import { useSpring, animated } from 'react-spring/native'; import { useTRPGSelector } from '@shared/hooks/useTRPGSelector'; import { TRPGTabScreenProps } from '@app/router'; import { switchToChatScreen } from '@app/navigate'; const NetworkContainer = styled(animated.View as any)<{ isOnline: boolean; tryReconnect: boolean; }>` position: absolute; top: -26px; left: 0; right: 0; height: 26px; background-color: ${({ isOnline, tryReconnect }) => isOnline ? '#2ecc71' : tryReconnect ? '#f39c12' : '#c0392b'}; color: white; align-items: center; justify-content: center; `; const NetworkText = styled.Text` color: white; `; const NetworkTip: React.FC = TMemo((props) => { const network = useTRPGSelector((state) => state.ui.network); const style = useSpring({ to: { top: network.isOnline ? -26 : 0, }, }); return ( <NetworkContainer style={style} isOnline={network.isOnline} tryReconnect={network.tryReconnect} > <NetworkText>{network.msg}</NetworkText> </NetworkContainer> ); }); NetworkTip.displayName = 'NetworkTip'; interface Props extends TRPGDispatchProp, TRPGTabScreenProps<'TRPG'> { converses: any; conversesDesc: any; groups: any; usercache: any; } class HomeScreen extends React.Component<Props> { state = { isRefreshing: false, }; getList() { if (_size(this.props.converses) > 0) { const arr: any[] = _sortBy( _values(this.props.converses), (item) => new Date(item.lastTime || 0) ) .reverse() .map((item, index) => { const uuid = item.uuid; const defaultIcon = uuid === 'trpgsystem' ? appConfig.defaultImg.trpgsystem : appConfig.defaultImg.user; let avatar: string; if (item.type === 'user') { avatar = _get(this.props.usercache, [uuid, 'avatar']); } else if (item.type === 'group') { const group = this.props.groups.find((g) => g.uuid === uuid); avatar = group ? group.avatar : ''; } return { icon: item.icon || avatar || defaultIcon, title: item.name, content: item.lastMsg, time: item.lastTime ? dateHelper.getShortDiff(item.lastTime) : '', uuid, unread: item.unread, onPress: () => { this.handleSelectConverse(uuid, item.type, item); }, }; }); return ( <FlatList refreshControl={ <TRefreshControl refreshing={this.state.isRefreshing} onRefresh={() => this.handleRefresh()} /> } keyExtractor={(item, index) => item.uuid} data={arr} renderItem={({ item }) => <ConvItem {...item} />} /> ); } else { return <Text style={styles.tipText}>{this.props.conversesDesc}</Text>; } } handleRefresh() { this.setState({ isRefreshing: true }); const timer = setTimeout(() => { this.setState({ isRefreshing: false }); }, 10000); // 10秒后自动取消 this.props.dispatch( reloadConverseList(() => { this.setState({ isRefreshing: false }); clearTimeout(timer); }) ); } handleSelectConverse(uuid: string, type: ChatType, info) { switchToChatScreen( this.props.navigation.dangerouslyGetParent(), uuid, type, info.name ); } render() { return ( <View style={styles.container}> {this.getList()} <NetworkTip /> </View> ); } } const styles = { container: [sb.flex()], tipText: [sb.textAlign('center'), sb.margin(80, 0, 0, 0), sb.color('#999')], }; export default connect((state: TRPGState) => ({ converses: state.chat.converses, conversesDesc: state.chat.conversesDesc, groups: state.group.groups, usercache: state.cache.user, }))(HomeScreen);
Java
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_Groups_Tools_Polls_Polls_New { /// <summary> /// PollNew control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Polls_Controls_PollNew PollNew; }
Java
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class ReadSavedData { public static void StartRead() throws IOException { FileReader file = new FileReader("C:/Users/Public/Documents/SavedData.txt"); BufferedReader reader = new BufferedReader(file); String text = ""; String line = reader.readLine(); while (line != null) { text += line; line = reader.readLine(); } reader.close(); System.out.println(text); } }
Java
enum MessageType { TYPE_CHAT_MESSAGE = 2000 }; enum PropertyType { PR_CHAT_NICK = 3000, PR_CHAT_TEXT };
Java
.block { background:yellow; /*max-height:50px;*/ border:5px; border-color:red; max-width:300px; -moz-border-radius: 15px; padding-left:5px; padding-right:10px; z-index:11; } .block:not(.block-inlist):last-of-type,.block-inlist{ border-bottom-right-radius: 10px; } .block-instack { list-style-position:inside; position:relative; left:-20px; z-index:11; } .stack { list-style-type:none; list-style-position:inside; padding: 0; padding-bottom:10px; margin-left: 0; position:absolute; background:green; overflow:visible; max-height:100%; /*max-width:500px;*/ min-width:100px; min-height:50px; background:green; z-index:-1; border-radius:5px; } #trash img { max-width:100px; max-height:100px; position:fixed; right:0px; bottom:0px; z-index:-1; } .createStack { background:green; max-height:50px; border:5px; max-width:300px; } .canvas { min-width:100%; min-height:100%; top:0px;left:0px; position:absolute; z-index:5; overflow:auto; } #objects li { border-style:solid; border-width:1px; border-color:orange; } custom-menu { list-style-type:none; list-style-position:inside; z-index:99; background:white; border-style:solid; border-width:1px; border-radius:5px; border-color:grey; min-width:100px; padding-left:-5px; margin-left:0px; font-size:14px; padding-right:500px; } custom-menu li, cmenu-item { width:100%; border-width:1px; border-color:white; border-style:solid; border-top-color:black; border-left-color:black; font-size:14px; position:relative; left:-3px; top:-3px; padding:0px; margin:0px; padding-right:5px; } custom-menu li:last-child, custom-menu cmenu-item:last-child { border-bottom-left-radius:5px; border-bottom-right-radius:5px; margin-bottom:-6px; border-bottom-color:grey; } custom-menu li:first-child, custom-menu cmenu-item:first-child { border-top-left-radius:5px; border-top-right-radius:5px; } custom-menu li:hover, custom-menu cmenu-item:hover { border-color:black; border-radius:5px; } cmenu-item { display:list-item; } .block-type-variable { background-color:#F000FC; } .data { border-radius:10px; background-color:#00FFFF; padding-left:5px; } .block-type-camera, .camera { background-color:#FF0040; } #webcam-ask { z-index: 1000; } #webcam-hide { opacity:0.0; filter:alpha(opacity=0); } #webcam-dialog { background-color:#DDDDDD; min-width:100px; min-height:100px; z-index:999; } .hide { z-index:9999; opacity:0; } #window { x-index:9999; opacity:1; width:300px; height:300px; border-width: 1px; border-color: black; border-radius: 5px; }
Java
/************************************************************************** * Karlyriceditor - a lyrics editor and CD+G / video export for Karaoke * * songs. * * Copyright (C) 2009-2013 George Yunaev, support@ulduzsoft.com * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * **************************************************************************/ #ifndef BACKGROUND_H #define BACKGROUND_H #include <QImage> #include "ffmpegvideodecoder.h" class Background { public: Background(); virtual ~Background(); // Actual draw function to implement. Should return time when the next // doDraw() should be called - for example, for videos it should only // be called when it is time to show the next frame; for static images // it should not be called at all. If 0 is returned, doDraw() will be called // again the next update. If -1 is returned, doDraw() will never be called // again, and the cached image will be used. virtual qint64 doDraw( QImage& image, qint64 timing ) = 0; // This function is called if timing went backward (user seek back), in which // case it will be called before doDraw() with a new time. Video players, for // example, may use it to seek back to zero. Default implementation does nothing. virtual void reset(); // Should return true if the event was created successfully virtual bool isValid() const = 0; }; class BackgroundImage : public Background { public: BackgroundImage( const QString& filename ); bool isValid() const; qint64 doDraw( QImage& image, qint64 timing ); private: QImage m_image; }; class BackgroundVideo : public Background { public: BackgroundVideo( const QString& arg ); bool isValid() const; qint64 doDraw( QImage& image, qint64 timing ); private: FFMpegVideoDecoder m_videoDecoder; bool m_valid; }; #endif // BACKGROUND_H
Java
#!/bin/sh declare -x PATH_TO_SOURCE=`dirname $0`/.. cd $PATH_TO_SOURCE bsc -e "(module-compile-to-standalone \"ensanche-core\" 'main)"
Java
class ApplicationController < ActionController::Base class ForbiddenException < StandardError; end protect_from_forgery before_filter :set_locale before_filter :authenticate_user! layout :get_layout def set_locale I18n.locale = params[:locale] || I18n.default_locale end def get_layout if !user_signed_in? get_layout = "logged_out" else get_layout = "application" end end def after_sign_out_path_for(resource) new_user_session_path end def administrator_only_access unless user_signed_in? && current_user.admin? raise ApplicationController::ForbiddenException end end end
Java
/** * Copyright 2010 David Froehlich <david.froehlich@businesssoftware.at>, * Samuel Kogler <samuel.kogler@gmail.com>, * Stephan Stiboller <stistc06@htlkaindorf.at> * * This file is part of Codesearch. * * Codesearch is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Codesearch is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Codesearch. If not, see <http://www.gnu.org/licenses/>. */ package com.uwyn.jhighlight.pcj.hash; /** * This interface represents hash functions from char values * to int values. The int value result is chosen to achieve * consistence with the common * {@link Object#hashCode() hashCode()} * method. The interface is provided to alter the hash functions used * by hashing data structures, like * {@link com.uwyn.rife.pcj.map.CharKeyIntChainedHashMap CharKeyIntChainedHashMap} * or * {@link com.uwyn.rife.pcj.set.CharChainedHashSet CharChainedHashSet}. * * @see DefaultCharHashFunction * * @author S&oslash;ren Bak * @version 1.0 2002/29/12 * @since 1.0 */ public interface CharHashFunction { /** * Returns a hash code for a specified char value. * * @param v * the value for which to return a hash code. * * @return a hash code for the specified value. */ int hash(char v); }
Java
using System; using System.Diagnostics; using System.Text; using System.Windows.Forms; using OpenDentBusiness; namespace OpenDental.Eclaims { /// <summary> /// Summary description for BCBSGA. /// </summary> public class BCBSGA{ /// <summary></summary> public static string ErrorMessage=""; public BCBSGA() { } ///<summary>Returns true if the communications were successful, and false if they failed. If they failed, a rollback will happen automatically by deleting the previously created X12 file. The batchnum is supplied for the possible rollback.</summary> public static bool Launch(Clearinghouse clearinghouseClin,int batchNum){ //called from Eclaims.cs. Clinic-level clearinghouse passed in. bool retVal=true; FormTerminal FormT=new FormTerminal(); try{ FormT.Show(); FormT.OpenConnection(clearinghouseClin.ModemPort); //1. Dial FormT.Dial("17065713158"); //2. Wait for connect, then pause 3 seconds FormT.WaitFor("CONNECT 9600",50000); FormT.Pause(3000); FormT.ClearRxBuff(); //3. Send Submitter login record string submitterLogin= //position,length indicated for each "/SLRON"//1,6 /SLRON=Submitter login +FormT.Sout(clearinghouseClin.LoginID,12,12)//7,12 Submitter ID +FormT.Sout(clearinghouseClin.Password,8,8)//19,8 submitter password +"NAT"//27,3 use NAT //30,8 suggested 8-BYTE CRC of the file for unique ID. No spaces. //But I used the batch number instead +batchNum.ToString().PadLeft(8,'0') +"ANSI837D 1 "//38,15 "ANSI837D 1 "=Dental claims +"X"//53,1 X=Xmodem, or Y for transmission protocol +"ANSI"//54,4 use ANSI +"BCS"//58,3 BCS=BlueCrossBlueShield +"00";//61,2 use 00 for filler FormT.Send(submitterLogin); //4. Receive Y, indicating login accepted if(FormT.WaitFor("Y","N",20000)=="Y"){ //5. Wait 1 second. FormT.Pause(1000); } else{ //6. If login rejected, receive an N, //followed by Transmission acknowledgement explaining throw new Exception(FormT.Receive(5000)); } //7. Send file using X-modem or Z-modem //slash not handled properly if missing: FormT.UploadXmodem(clearinghouseClin.ExportPath+"claims"+batchNum.ToString()+".txt"); //8. After transmitting, pause for 1 second. FormT.Pause(1000); FormT.ClearRxBuff(); //9. Send submitter logout record string submitterLogout= "/SLROFF"//1,7 /SLROFF=Submitter logout +FormT.Sout(clearinghouseClin.LoginID,12,12)//8,12 Submitter ID +batchNum.ToString().PadLeft(8,'0')//20,8 matches field in submitter Login +"!"//28,1 use ! to retrieve transmission acknowledgement record +"\r\n"; FormT.Send(submitterLogout); //10. Prepare to receive the Transmission acknowledgement. This is a receipt. FormT.Receive(5000);//this is displayed in the progress box so user can see. } catch(Exception ex){ ErrorMessage=ex.Message; x837Controller.Rollback(clearinghouseClin,batchNum); retVal=false; } finally{ FormT.CloseConnection(); } return retVal; } ///<summary>Retrieves any waiting reports from this clearinghouse. Returns true if the communications were successful, and false if they failed.</summary> public static bool Retrieve(Clearinghouse clearinghouseClin) { //Called from FormClaimReports. Clinic-level Clearinghouse passed in. bool retVal=true; FormTerminal FormT=new FormTerminal(); try{ FormT.Show(); FormT.OpenConnection(clearinghouseClin.ModemPort); FormT.Dial("17065713158"); //2. Wait for connect, then pause 3 seconds FormT.WaitFor("CONNECT 9600",50000); FormT.Pause(3000); FormT.ClearRxBuff(); //1. Send submitter login record string submitterLogin= "/SLRON"//1,6 /SLRON=Submitter login +FormT.Sout(clearinghouseClin.LoginID,12,12)//7,12 Submitter ID +FormT.Sout(clearinghouseClin.Password,8,8)//19,8 submitter password +" "//27,3 use 3 spaces //Possible issue with Trans ID +"12345678"//30,8. they did not explain this field very well in documentation +"* "//38,15 " * "=All available. spacing ok? +"X"//53,1 X=Xmodem, or Y for transmission protocol +"MDD "//54,4 use 'MDD ' +"VND"//58,3 Vendor ID is yet to be assigned by BCBS +"00";//61,2 Software version not important byte response=(byte)'Y'; string retrieveFile=""; while(response==(byte)'Y'){ FormT.ClearRxBuff(); FormT.Send(submitterLogin); response=0; while(response!=(byte)'N' && response!=(byte)'Y' && response!=(byte)'Z') { response=FormT.GetOneByte(20000); FormT.ClearRxBuff(); Application.DoEvents(); } //2. If not accepted, N is returned //3. and must receive transmission acknowledgement if(response==(byte)'N'){ MessageBox.Show(FormT.Receive(10000)); break; } //4. If login accepted, but no records, Z is returned. Hang up. if(response==(byte)'Z'){ MessageBox.Show("No reports to retrieve"); break; } //5. If record(s) available, Y is returned, followed by dos filename and 32 char subj. //less than one second since all text is supposed to immediately follow the Y retrieveFile=FormT.Receive(800).Substring(0,12);//12 char in dos filename FormT.ClearRxBuff(); //6. Pause for 1 second. (already mostly handled); FormT.Pause(200); //7. Receive file using Xmodem //path must include trailing slash for now. FormT.DownloadXmodem(clearinghouseClin.ResponsePath+retrieveFile); //8. Pause for 5 seconds. FormT.Pause(5000); //9. Repeat all steps including login until a Z is returned. } } catch(Exception ex){ ErrorMessage=ex.Message; //FormT.Close();//Also closes connection retVal=false; } finally{ FormT.CloseConnection(); } return retVal; } } }
Java
-- -- Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com). -- -- Licensed under the GPL, Version 3.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.gnu.org/licenses/gpl.html -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- select * from dual t1, dual t2 join dual t3 using(dummy) left outer join dual t4 using(dummy) left outer join dual t5 using(dummy)
Java
/** ****************************************************************************** * @file I2C/I2C_TwoBoards_ComPolling/Src/stm32f4xx_it.c * @author MCD Application Team * @version V1.2.7 * @date 17-February-2017 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup I2C_TwoBoards_ComPolling * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* I2C handler declared in "main.c" file */ extern I2C_HandleTypeDef hi2c; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { HAL_IncTick(); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Java
all: ocp-build init ocp-build opam-deps: opam install ocp-build
Java
#include "inventorypage.h" #include "ui_inventorypage.h" #include "fak.h" #include "inventorypage.h" #include <QtDebug> #include "QtDebug" #include <QSqlQuery> #include <QSqlError> #include <QSqlRecord> static const QString path = "C:/Sr.GUI/FAKKIT/db/fakdb4.db"; InventoryPage::InventoryPage(QWidget *parent) : QDialog(parent), ui(new Ui::InventoryPage) { ui->setupUi(this); this->setStyleSheet("background-color:#626065;"); DbManager db(path); qDebug() << "Stuff in db:"; QSqlQuery query; query.exec("SELECT * FROM codes"); int idName = query.record().indexOf("name"); while (query.next()) { QString name = query.value(idName).toString(); qDebug() << "===" << name; //ui->dbOutput->setPlainText(name); ui->dbOutput->append(name); } } DbManager::DbManager(const QString &path) { m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(path); if (!m_db.open()) { qDebug() << "Error: connection with database fail"; } else { qDebug() << "Database: connection ok"; } } InventoryPage::~InventoryPage() { delete ui; } void InventoryPage::on_HomeButton_clicked() { }
Java
var gulp = require('gulp'); var browserSync = require('browser-sync'); var jshint = require('gulp-jshint'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); // 静态服务器 gulp.task('browser-sync', function() { browserSync.init({ files: "src/**", server: { baseDir: "src/" } }); }); // js语法检查 gulp.task('jshint', function() { return gulp.src('src/js/*.js') .on('error') .pipe(jshint()) .pipe(jshint.reporter('default')); }); // js文件合并及压缩 gulp.task('minifyjs', function() { return gulp.src('src/js/*.js') .pipe(concat('all.js')) .pipe(gulp.dest('dist/js')) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('dist/js')); }); // 事件监听 gulp.task('watch', function() { gulp.watch('src/js/*.js', ['jshint','minifyjs']); }); gulp.task('default',['browser-sync','watch']);
Java
#ifndef __CLOCK_ROM_H__ #define __CLOCK_ROM_H__ #define ROM_ALARM0_DAY_MASK 0 #define ROM_ALARM0_HOUR 1 #define ROM_ALARM0_MIN 2 #define ROM_ALARM0_DUR 3 #define ROM_ALARM1_ENABLE 4 #define ROM_TIME_IS12 10 #define ROM_BEEPER_MUSIC_INDEX 11 #define ROM_BEEPER_ENABLE 12 #define ROM_POWERSAVE_TO 13 #define ROM_REMOTE_ONOFF 14 #define ROM_AUTO_LIGHT_ONOFF 15 #define ROM_FUSE_HG_ONOFF 20 #define ROM_FUSE_MPU 21 #define ROM_FUSE_THERMO_HI 22 #define ROM_FUSE_THERMO_LO 23 #define ROM_FUSE_REMOTE_ONOFF 24 #define ROM_FUSE_PASSWORD 25 // 6字节是password #define ROM_LT_TIMER_YEAR 40 #define ROM_LT_TIMER_MONTH 41 #define ROM_LT_TIMER_DATE 42 #define ROM_LT_TIMER_HOUR 43 #define ROM_LT_TIMER_MIN 44 #define ROM_LT_TIMER_SEC 45 #define ROM_RADIO_FREQ_HI 50 #define ROM_RADIO_FREQ_LO 51 #define ROM_RADIO_VOLUME 52 #define ROM_RADIO_HLSI 53 #define ROM_RADIO_MS 54 #define ROM_RADIO_BL 55 #define ROM_RADIO_HCC 56 #define ROM_RADIO_SNC 57 #define ROM_RADIO_DTC 58 unsigned char rom_read(unsigned char addr); void rom_write(unsigned char addr, unsigned char val); void rom_initialize(void); bit rom_is_factory_reset(void); #endif
Java
/* Copyright (C) 2010 Erik Hjortsberg <erik.hjortsberg@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #ifndef SERIALTASK_H_ #define SERIALTASK_H_ #include "TemplateNamedTask.h" #include <vector> namespace Ember { namespace Tasks { /** * @author Erik Hjortsberg <erik.hjortsberg@gmail.com> * @brief A task which wraps two or more other tasks, which will be executed in order. * This is useful if you want to make sure that a certain task is executed after another task. */ class SerialTask: public TemplateNamedTask<SerialTask> { public: typedef std::vector<ITask*> TaskStore; /** * @brief Ctor. * @param subTasks The tasks to execute, in order. */ SerialTask(const TaskStore& subTasks); /** * @brief Ctor. * This is a convenience constructor which allows you to specify the tasks directly without having to first create a vector instance. * @param firstTask The first task to execute. * @param secondTask The second task to execute. * @param thirdTask The third task to execute. * @param firstTask The fourth task to execute. */ SerialTask(ITask* firstTask, ITask* secondTask, ITask* thirdTask = 0, ITask* fourthTask = 0); virtual ~SerialTask(); virtual void executeTaskInBackgroundThread(TaskExecutionContext& context); private: TaskStore mSubTasks; }; } } #endif /* SERIALTASK_H_ */
Java
\hypertarget{_coloring_8java}{}\doxysection{src/ch/innovazion/arionide/menu/structure/\+Coloring.java File Reference} \label{_coloring_8java}\index{src/ch/innovazion/arionide/menu/structure/Coloring.java@{src/ch/innovazion/arionide/menu/structure/Coloring.java}} \doxysubsection*{Classes} \begin{DoxyCompactItemize} \item class \mbox{\hyperlink{classch_1_1innovazion_1_1arionide_1_1menu_1_1structure_1_1_coloring}{ch.\+innovazion.\+arionide.\+menu.\+structure.\+Coloring}} \end{DoxyCompactItemize} \doxysubsection*{Packages} \begin{DoxyCompactItemize} \item package \mbox{\hyperlink{namespacech_1_1innovazion_1_1arionide_1_1menu_1_1structure}{ch.\+innovazion.\+arionide.\+menu.\+structure}} \end{DoxyCompactItemize}
Java
/*****************************************************************/ /* Source Of Evil Engine */ /* */ /* Copyright (C) 2000-2001 Andreas Zahnleiter GreenByte Studios */ /* */ /*****************************************************************/ /* Dynamic object list */ class C4ObjectLink { public: C4Object *Obj; C4ObjectLink *Prev,*Next; }; class C4ObjectList { public: C4ObjectList(); ~C4ObjectList(); public: C4ObjectLink *First,*Last; int Mass; char *szEnumerated; public: void SortByCategory(); void Default(); void Clear(); void Sort(); void Enumerate(); void Denumerate(); void Copy(C4ObjectList &rList); void Draw(C4FacetEx &cgo); void DrawList(C4Facet &cgo, int iSelection=-1, DWORD dwCategory=C4D_All); void DrawIDList(C4Facet &cgo, int iSelection, C4DefList &rDefs, DWORD dwCategory, C4RegionList *pRegions=NULL, int iRegionCom=COM_None, BOOL fDrawOneCounts=TRUE); void DrawSelectMark(C4FacetEx &cgo); void CloseMenus(); void UpdateFaces(); void SyncClearance(); void ResetAudibility(); void UpdateTransferZones(); void SetOCF(); void GetIDList(C4IDList &rList, DWORD dwCategory=C4D_All); void ClearInfo(C4ObjectInfo *pInfo); void PutSolidMasks(); void RemoveSolidMasks(BOOL fCauseInstability=TRUE); BOOL Add(C4Object *nObj, BOOL fSorted=TRUE); BOOL Remove(C4Object *pObj); BOOL Save(const char *szFilename, BOOL fSaveGame); BOOL Save(C4Group &hGroup, BOOL fSaveGame); BOOL AssignInfo(); BOOL ValidateOwners(); BOOL WriteNameList(char *szTarget, C4DefList &rDefs, DWORD dwCategory=C4D_All); BOOL IsClear(); BOOL ReadEnumerated(const char *szSource); BOOL DenumerateRead(); BOOL Write(char *szTarget); int Load(C4Group &hGroup); int ObjectNumber(C4Object *pObj); int ClearPointers(C4Object *pObj); int ObjectCount(C4ID id=C4ID_None, DWORD dwCategory=C4D_All); int MassCount(); int ListIDCount(DWORD dwCategory); C4Object* Denumerated(C4Object *pObj); C4Object* Enumerated(C4Object *pObj); C4Object* ObjectPointer(int iNumber); C4Object* GetObject(int Index=0); C4Object* Find(C4ID id, int iOwner=ANY_OWNER); C4Object* FindOther(C4ID id, int iOwner=ANY_OWNER); C4ObjectLink* GetLink(C4Object *pObj); C4ID GetListID(DWORD dwCategory, int Index); protected: void InsertLink(C4ObjectLink *pLink, C4ObjectLink *pAfter); void RemoveLink(C4ObjectLink *pLnk); };
Java
using UnityEngine; using System.Collections; public class TimeScaleManager : MonoBehaviour { public static TimeScaleManager instance; public delegate void OnTimeScaleChangeCallback(); public event OnTimeScaleChangeCallback TimeScaleChange; public bool isPlaying; public bool IsPaused { get { return !isPlaying; } } public enum TimeScale{ ONE, TWO, THREE } public TimeScale timeScale; void Awake(){ instance = this; timeScale = TimeScale.ONE; Time.timeScale = 0f; isPlaying = false; } public void SelectNextTimeScale(){ switch(timeScale){ case TimeScale.ONE: timeScale = TimeScale.TWO; if (isPlaying) { Time.timeScale = 2f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; case TimeScale.TWO: timeScale = TimeScale.THREE; if (isPlaying) { Time.timeScale = 3f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; case TimeScale.THREE: timeScale = TimeScale.ONE; if (isPlaying) { Time.timeScale = 1f; } if (TimeScaleChange != null){ TimeScaleChange(); } break; } } public string GetCurrentTimeScaleLabel(){ switch(timeScale){ case TimeScale.ONE: return "1"; case TimeScale.TWO: return "2"; case TimeScale.THREE: return "3"; default: return "error"; } } }
Java
#ifndef __ASSIGN_SPRITES_H #define __ASSIGN_SPRITES_H void AssignSprites(void); #endif
Java
# Dockerfile "Big" Intended for a big webapplications which expects the following tools: - texlive (pdflatex)
Java