text
stringlengths
2
1.04M
meta
dict
using Yak; using Yak.Nerves; namespace Yak.Infrastructure { public delegate void LoggedSherpaTest(Body sherpa, LogResult logResult); public static class Tests { public static void Run(LoggedSherpaTest test) { var log = new DebugLog(); var yak = new LoggingYakNerves(log); LogResult logResult = () => log.CurrentContent; var sherpa = new Body(yak); test(sherpa, logResult); } } }
{ "content_hash": "6c70d90dc7252489cecfc035f599a3e6", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 76, "avg_line_length": 25.31578947368421, "alnum_prop": 0.6008316008316008, "repo_name": "YakShavers/YakServer", "id": "97fe998087e83d99da7d98b40589b42419dc04e9", "size": "483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Yak.Tests/Infrastructure/Tests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "32200" } ], "symlink_target": "" }
package org.spongepowered.common.mixin.core.world.biome; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import net.minecraft.block.state.IBlockState; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeDecorator; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.common.SpongeImplHooks; import org.spongepowered.common.bridge.world.biome.BiomeBridge; import org.spongepowered.common.world.biome.SpongeBiomeGenerationSettings; import org.spongepowered.common.world.gen.WorldGenConstants; import javax.annotation.Nullable; @Mixin(Biome.class) public abstract class BiomeMixin implements BiomeBridge { @Shadow public IBlockState topBlock; @Shadow public IBlockState fillerBlock; @Shadow public BiomeDecorator decorator; @Nullable @MonotonicNonNull private String impl$id; @Nullable @MonotonicNonNull private String impl$modId; @Override public void bridge$buildPopulators(final World world, final SpongeBiomeGenerationSettings gensettings) { WorldGenConstants.buildPopulators(world, gensettings, this.decorator, this.topBlock, this.fillerBlock); } @Inject(method = "registerBiome", at = @At("HEAD")) private static void onRegisterBiome(final int id, final String name, final Biome biome, final CallbackInfo ci) { final String modId = SpongeImplHooks.getModIdFromClass(biome.getClass()); final String biomeName = name.toLowerCase().replace(" ", "_").replaceAll("[^A-Za-z0-9_]", ""); ((BiomeBridge) biome).bridge$setModId(modId); ((BiomeBridge) biome).bridge$setId(modId + ":" + biomeName); } @Override public void bridge$setId(final String id) { checkState(this.impl$id == null, "Attempt made to set ID!"); this.impl$id = id; } @Override public String bridge$getId() { return checkNotNull(this.impl$id, "BiomeType id is null"); } @SuppressWarnings("ConstantConditions") @Override public String bridge$getModId() { return this.impl$modId; } @Override public void bridge$setModId(final String modId) { checkState(this.impl$modId == null || "unknown".equals(this.impl$modId), "Attempt made to set Mod ID!"); this.impl$modId = modId; } }
{ "content_hash": "615989ff102e0fb9ae41192525813aa5", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 116, "avg_line_length": 36.0945945945946, "alnum_prop": 0.7420441782104081, "repo_name": "SpongePowered/SpongeCommon", "id": "be64cae2197e6645f5ed80763126e475dfbedd1f", "size": "3918", "binary": false, "copies": "1", "ref": "refs/heads/stable-7", "path": "src/main/java/org/spongepowered/common/mixin/core/world/biome/BiomeMixin.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "14153592" }, { "name": "Shell", "bytes": "1072" } ], "symlink_target": "" }
package util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; /** * A simple utilty program that takes the master.json realm configuration file and base64 encodes it for use in the * fabric8/2-secret.yml data.sso-demo.json entry */ public class EncodeJsonConfig { public static void main(String[] args) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = EncodeJsonConfig.class.getResourceAsStream("/master.json"); byte[] tmp = new byte[1024]; int length = is.read(tmp); while (length > 0) { baos.write(tmp, 0, length); length = is.read(tmp); } is.close(); baos.close(); tmp = baos.toByteArray(); Base64.Encoder encoder = Base64.getEncoder(); String encoded = encoder.encodeToString(tmp); System.out.printf(" sso-demo.json: %s\n", encoded); } }
{ "content_hash": "ff3e987ae10ec07a809ec68807ef821a", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 115, "avg_line_length": 31.15625, "alnum_prop": 0.6519558676028084, "repo_name": "starksm64/wf-demo", "id": "52ef884556474a42e73ac04ae00d7697dd973445", "size": "1671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sso/src/main/java/util/EncodeJsonConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "48219" }, { "name": "Python", "bytes": "3616" }, { "name": "Shell", "bytes": "1538" } ], "symlink_target": "" }
#region Apache Notice #endregion using System; using System.Xml.Serialization; namespace IBatisNet.DataMapper.Configuration.Statements { /// <summary> /// Update. /// </summary> [Serializable] [XmlRoot("update", Namespace = "http://ibatis.apache.org/mapping")] public class Update : Statement { #region Fields [NonSerialized] private Generate _generate = null; #endregion /// <summary> /// The Generate tag used by a generated update statement. /// (CRUD operation) /// </summary> [XmlElement("generate", typeof(Generate))] public Generate Generate { get { return _generate; } set { _generate = value; } } /// <summary> /// Do not use direclty, only for serialization. /// </summary> public Update() : base() { } } }
{ "content_hash": "1e0acfaeb2e98fec6e884f0fd12d3f5d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 71, "avg_line_length": 23.435897435897434, "alnum_prop": 0.5557986870897156, "repo_name": "chookrib/Castle.Facilities.IBatisNet", "id": "edf5605dea52a3527c7373bd2ed888f372f30a6d", "size": "1802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/IBatisNet.DataMapper/Configuration/Statements/Update.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "612" }, { "name": "C#", "bytes": "1911845" }, { "name": "PLpgSQL", "bytes": "1244" } ], "symlink_target": "" }
<?php /** * Este arquivo contem o model Atividade * * @package Model */ App::uses('RegistroAtividadeAppModel', 'RegistroAtividade.Model'); /** * Model para registro de atividade * * @package Model */ class Atividade extends RegistroAtividadeAppModel { public $useTable = 'atividades'; /** * Habilita o virtual field total * * @access public * @return null */ public function habilitarVirtualFieldTotal() { $this->virtualFields['total'] = 'COUNT(' . $this->alias . '.id)'; } }
{ "content_hash": "5cdd872a884c29cc84eeda8cbd08b0d8", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 73, "avg_line_length": 19.88888888888889, "alnum_prop": 0.62756052141527, "repo_name": "rochamarcelo/RegistroAtividade", "id": "26991f1d3229204d76afbf448fbccf7ca802e6b2", "size": "537", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Model/Atividade.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "12781" } ], "symlink_target": "" }
/** * @ngdoc module * @name material.components.tooltip */ angular .module('material.components.tooltip', [ 'material.core', 'material.components.panel' ]) .directive('mdTooltip', MdTooltipDirective) .service('$$mdTooltipRegistry', MdTooltipRegistry); /** * @ngdoc directive * @name mdTooltip * @module material.components.tooltip * @description * Tooltips are used to describe elements that are interactive and primarily * graphical (not textual). * * Place a `<md-tooltip>` as a child of the element it describes. * * A tooltip will activate when the user hovers over, focuses, or touches the * parent element. * * @usage * <hljs lang="html"> * <md-button class="md-fab md-accent" aria-label="Play"> * <md-tooltip>Play Music</md-tooltip> * <md-icon md-svg-src="img/icons/ic_play_arrow_24px.svg"></md-icon> * </md-button> * </hljs> * * @param {number=} md-z-index The visual level that the tooltip will appear * in comparison with the rest of the elements of the application. * @param {expression=} md-visible Boolean bound to whether the tooltip is * currently visible. * @param {number=} md-delay How many milliseconds to wait to show the tooltip * after the user hovers over, focuses, or touches the parent element. * Defaults to 0ms on non-touch devices and 75ms on touch. * @param {boolean=} md-autohide If present or provided with a boolean value, * the tooltip will hide on mouse leave, regardless of focus. * @param {string=} md-direction The direction that the tooltip is shown, * relative to the parent element. Supports top, right, bottom, and left. * Defaults to bottom. */ function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate, $mdUtil, $mdPanel, $$mdTooltipRegistry) { var ENTER_EVENTS = 'focus touchstart mouseenter'; var LEAVE_EVENTS = 'blur touchcancel mouseleave'; var TOOLTIP_DEFAULT_Z_INDEX = 100; var TOOLTIP_DEFAULT_SHOW_DELAY = 0; var TOOLTIP_DEFAULT_DIRECTION = 'bottom'; var TOOLTIP_DIRECTIONS = { top: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.ABOVE }, right: { x: $mdPanel.xPosition.OFFSET_END, y: $mdPanel.yPosition.CENTER }, bottom: { x: $mdPanel.xPosition.CENTER, y: $mdPanel.yPosition.BELOW }, left: { x: $mdPanel.xPosition.OFFSET_START, y: $mdPanel.yPosition.CENTER } }; return { restrict: 'E', priority: 210, // Before ngAria scope: { mdZIndex: '=?mdZIndex', mdDelay: '=?mdDelay', mdVisible: '=?mdVisible', mdAutohide: '=?mdAutohide', mdDirection: '@?mdDirection' // Do not expect expressions. }, link: linkFunc }; function linkFunc(scope, element, attr) { // Set constants. var parent = $mdUtil.getParentWithPointerEvents(element); var debouncedOnResize = $$rAF.throttle(updatePosition); var mouseActive = false; var origin, position, panelPosition, panelRef, autohide, showTimeout, elementFocusedOnWindowBlur = null; // Set defaults setDefaults(); // Set parent aria-label. addAriaLabel(); // Remove the element from its current DOM position. element.detach(); updatePosition(); bindEvents(); configureWatchers(); function setDefaults() { scope.mdZIndex = scope.mdZIndex || TOOLTIP_DEFAULT_Z_INDEX; scope.mdDelay = scope.mdDelay || TOOLTIP_DEFAULT_SHOW_DELAY; if (!TOOLTIP_DIRECTIONS[scope.mdDirection]) { scope.mdDirection = TOOLTIP_DEFAULT_DIRECTION; } } function addAriaLabel(override) { if (override || !parent.attr('aria-label')) { // Only interpolate the text from the HTML element because otherwise the custom text // could be interpolated twice and cause XSS violations. var interpolatedText = override || $interpolate(element.text().trim())(scope.$parent); parent.attr('aria-label', interpolatedText); } } function updatePosition() { setDefaults(); // If the panel has already been created, remove the current origin // class from the panel element. if (panelRef && panelRef.panelEl) { panelRef.panelEl.removeClass(origin); } // Set the panel element origin class based off of the current // mdDirection. origin = 'md-origin-' + scope.mdDirection; // Create the position of the panel based off of the mdDirection. position = TOOLTIP_DIRECTIONS[scope.mdDirection]; // Using the newly created position object, use the MdPanel // panelPosition API to build the panel's position. panelPosition = $mdPanel.newPanelPosition() .relativeTo(parent) .addPanelPosition(position.x, position.y); // If the panel has already been created, add the new origin class to // the panel element and update it's position with the panelPosition. if (panelRef && panelRef.panelEl) { panelRef.panelEl.addClass(origin); panelRef.updatePosition(panelPosition); } } function bindEvents() { // Add a mutationObserver where there is support for it and the need // for it in the form of viable host(parent[0]). if (parent[0] && 'MutationObserver' in $window) { // Use a mutationObserver to tackle #2602. var attributeObserver = new MutationObserver(function(mutations) { if (isDisabledMutation(mutations)) { $mdUtil.nextTick(function() { setVisible(false); }); } }); attributeObserver.observe(parent[0], { attributes: true }); } elementFocusedOnWindowBlur = false; $$mdTooltipRegistry.register('scroll', windowScrollEventHandler, true); $$mdTooltipRegistry.register('blur', windowBlurEventHandler); $$mdTooltipRegistry.register('resize', debouncedOnResize); scope.$on('$destroy', onDestroy); // To avoid 'synthetic clicks', we listen to mousedown instead of // 'click'. parent.on('mousedown', mousedownEventHandler); parent.on(ENTER_EVENTS, enterEventHandler); function isDisabledMutation(mutations) { mutations.some(function(mutation) { return mutation.attributeName === 'disabled' && parent[0].disabled; }); return false; } function windowScrollEventHandler() { setVisible(false); } function windowBlurEventHandler() { elementFocusedOnWindowBlur = document.activeElement === parent[0]; } function enterEventHandler($event) { // Prevent the tooltip from showing when the window is receiving // focus. if ($event.type === 'focus' && elementFocusedOnWindowBlur) { elementFocusedOnWindowBlur = false; } else if (!scope.mdVisible) { parent.on(LEAVE_EVENTS, leaveEventHandler); setVisible(true); // If the user is on a touch device, we should bind the tap away // after the 'touched' in order to prevent the tooltip being // removed immediately. if ($event.type === 'touchstart') { parent.one('touchend', function() { $mdUtil.nextTick(function() { $document.one('touchend', leaveEventHandler); }, false); }); } } } function leaveEventHandler() { autohide = scope.hasOwnProperty('mdAutohide') ? scope.mdAutohide : attr.hasOwnProperty('mdAutohide'); if (autohide || mouseActive || $document[0].activeElement !== parent[0]) { // When a show timeout is currently in progress, then we have // to cancel it, otherwise the tooltip will remain showing // without focus or hover. if (showTimeout) { $timeout.cancel(showTimeout); setVisible.queued = false; showTimeout = null; } parent.off(LEAVE_EVENTS, leaveEventHandler); parent.triggerHandler('blur'); setVisible(false); } mouseActive = false; } function mousedownEventHandler() { mouseActive = true; } function onDestroy() { $$mdTooltipRegistry.deregister('scroll', windowScrollEventHandler, true); $$mdTooltipRegistry.deregister('blur', windowBlurEventHandler); $$mdTooltipRegistry.deregister('resize', debouncedOnResize); parent .off(ENTER_EVENTS, enterEventHandler) .off(LEAVE_EVENTS, leaveEventHandler) .off('mousedown', mousedownEventHandler); // Trigger the handler in case any of the tooltips are // still visible. leaveEventHandler(); attributeObserver && attributeObserver.disconnect(); } } function configureWatchers() { if (element[0] && 'MutationObserver' in $window) { var attributeObserver = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.attributeName === 'md-visible' && !scope.visibleWatcher ) { scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged); } }); }); attributeObserver.observe(element[0], { attributes: true }); // Build watcher only if mdVisible is being used. if (attr.hasOwnProperty('mdVisible')) { scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged); } } else { // MutationObserver not supported scope.visibleWatcher = scope.$watch('mdVisible', onVisibleChanged); } // Direction watcher scope.$watch('mdDirection', updatePosition); // Clean up if the element or parent was removed via jqLite's .remove. // A couple of notes: // - In these cases the scope might not have been destroyed, which // is why we destroy it manually. An example of this can be having // `md-visible="false"` and adding tooltips while they're // invisible. If `md-visible` becomes true, at some point, you'd // usually get a lot of tooltips. // - We use `.one`, not `.on`, because this only needs to fire once. // If we were using `.on`, it would get thrown into an infinite // loop. // - This kicks off the scope's `$destroy` event which finishes the // cleanup. element.one('$destroy', onElementDestroy); parent.one('$destroy', onElementDestroy); scope.$on('$destroy', function() { setVisible(false); panelRef && panelRef.destroy(); attributeObserver && attributeObserver.disconnect(); element.remove(); }); // Updates the aria-label when the element text changes. This watch // doesn't need to be set up if the element doesn't have any data // bindings. if (element.text().indexOf($interpolate.startSymbol()) > -1) { scope.$watch(function() { return element.text().trim(); }, addAriaLabel); } function onElementDestroy() { scope.$destroy(); } } function setVisible(value) { // Break if passed value is already in queue or there is no queue and // passed value is current in the controller. if (setVisible.queued && setVisible.value === !!value || !setVisible.queued && scope.mdVisible === !!value) { return; } setVisible.value = !!value; if (!setVisible.queued) { if (value) { setVisible.queued = true; showTimeout = $timeout(function() { scope.mdVisible = setVisible.value; setVisible.queued = false; showTimeout = null; if (!scope.visibleWatcher) { onVisibleChanged(scope.mdVisible); } }, scope.mdDelay); } else { $mdUtil.nextTick(function() { scope.mdVisible = false; if (!scope.visibleWatcher) { onVisibleChanged(false); } }); } } } function onVisibleChanged(isVisible) { isVisible ? showTooltip() : hideTooltip(); } function showTooltip() { // Do not show the tooltip if the text is empty. if (!element[0].textContent.trim()) { throw new Error('Text for the tooltip has not been provided. ' + 'Please include text within the mdTooltip element.'); } if (!panelRef) { var id = 'tooltip-' + $mdUtil.nextUid(); var attachTo = angular.element(document.body); var panelAnimation = $mdPanel.newPanelAnimation() .openFrom(parent) .closeTo(parent) .withAnimation({ open: 'md-show', close: 'md-hide' }); var panelConfig = { id: id, attachTo: attachTo, contentElement: element, propagateContainerEvents: true, panelClass: 'md-tooltip ' + origin, animation: panelAnimation, position: panelPosition, zIndex: scope.mdZIndex, focusOnOpen: false }; panelRef = $mdPanel.create(panelConfig); } panelRef.open().then(function() { panelRef.panelEl.attr('role', 'tooltip'); }); } function hideTooltip() { panelRef && panelRef.close(); } } } /** * Service that is used to reduce the amount of listeners that are being * registered on the `window` by the tooltip component. Works by collecting * the individual event handlers and dispatching them from a global handler. * * @ngInject */ function MdTooltipRegistry() { var listeners = {}; var ngWindow = angular.element(window); return { register: register, deregister: deregister }; /** * Global event handler that dispatches the registered handlers in the * service. * @param {!Event} event Event object passed in by the browser */ function globalEventHandler(event) { if (listeners[event.type]) { listeners[event.type].forEach(function(currentHandler) { currentHandler.call(this, event); }, this); } } /** * Registers a new handler with the service. * @param {string} type Type of event to be registered. * @param {!Function} handler Event handler. * @param {boolean} useCapture Whether to use event capturing. */ function register(type, handler, useCapture) { var handlers = listeners[type] = listeners[type] || []; if (!handlers.length) { useCapture ? window.addEventListener(type, globalEventHandler, true) : ngWindow.on(type, globalEventHandler); } if (handlers.indexOf(handler) === -1) { handlers.push(handler); } } /** * Removes an event handler from the service. * @param {string} type Type of event handler. * @param {!Function} handler The event handler itself. * @param {boolean} useCapture Whether the event handler used event capturing. */ function deregister(type, handler, useCapture) { var handlers = listeners[type]; var index = handlers ? handlers.indexOf(handler) : -1; if (index > -1) { handlers.splice(index, 1); if (handlers.length === 0) { useCapture ? window.removeEventListener(type, globalEventHandler, true) : ngWindow.off(type, globalEventHandler); } } } }
{ "content_hash": "159fa48a18ee326aa8cb5b0d74e8b9d9", "timestamp": "", "source": "github", "line_count": 468, "max_line_length": 94, "avg_line_length": 33.19017094017094, "alnum_prop": 0.6172664649455997, "repo_name": "Frank3K/material", "id": "45e182e6929499a6bcbc7320c87768d964672720", "size": "15533", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/components/tooltip/tooltip.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "259153" }, { "name": "HTML", "bytes": "192519" }, { "name": "JavaScript", "bytes": "2329458" }, { "name": "PHP", "bytes": "7211" }, { "name": "Shell", "bytes": "11090" } ], "symlink_target": "" }
namespace v8 { namespace internal { namespace wasm { class WasmOpcodesTest : public TestWithZone {}; TEST_F(WasmOpcodesTest, EveryOpcodeHasAName) { static const struct { WasmOpcode opcode; const char* debug_name; } kValues[] = { #define DECLARE_ELEMENT(name, opcode, sig) {kExpr##name, "kExpr" #name}, FOREACH_OPCODE(DECLARE_ELEMENT)}; #undef DECLARE_ELEMENT for (size_t i = 0; i < arraysize(kValues); i++) { const char* result = WasmOpcodes::OpcodeName(kValues[i].opcode); if (strcmp("unknown", result) == 0) { EXPECT_TRUE(false) << "WasmOpcodes::OpcodeName(" << kValues[i].debug_name << ") == \"unknown\";" " plazz halp in src/wasm/wasm-opcodes.cc"; } } } } // namespace wasm } // namespace internal } // namespace v8
{ "content_hash": "ff7514f77a660f97f41c4978f91e68fc", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 79, "avg_line_length": 30.333333333333332, "alnum_prop": 0.6166056166056166, "repo_name": "arangodb/arangodb", "id": "12739ff44fcdaa7803017e193d0c582522f827f6", "size": "1063", "binary": false, "copies": "9", "ref": "refs/heads/devel", "path": "3rdParty/V8/v7.9.317/test/unittests/wasm/wasm-opcodes-unittest.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "61827" }, { "name": "C", "bytes": "311036" }, { "name": "C++", "bytes": "35149373" }, { "name": "CMake", "bytes": "387268" }, { "name": "CSS", "bytes": "210549" }, { "name": "EJS", "bytes": "232160" }, { "name": "HTML", "bytes": "23114" }, { "name": "JavaScript", "bytes": "33841256" }, { "name": "LLVM", "bytes": "15003" }, { "name": "NASL", "bytes": "381737" }, { "name": "NSIS", "bytes": "47138" }, { "name": "Pascal", "bytes": "75391" }, { "name": "Perl", "bytes": "9811" }, { "name": "PowerShell", "bytes": "6806" }, { "name": "Python", "bytes": "190515" }, { "name": "SCSS", "bytes": "255542" }, { "name": "Shell", "bytes": "133576" }, { "name": "TypeScript", "bytes": "179074" }, { "name": "Yacc", "bytes": "79620" } ], "symlink_target": "" }
/* */ (function(Buffer) { var assert = require("assert"); var asn1 = require("../lib/asn1"); var Buffer = require("buffer").Buffer; describe('asn1.js models', function() { describe('plain use', function() { it('should encode submodel', function() { var SubModel = asn1.define('SubModel', function() { this.seq().obj(this.key('b').octstr()); }); var Model = asn1.define('Model', function() { this.seq().obj(this.key('a').int(), this.key('sub').use(SubModel)); }); var data = { a: 1, sub: {b: new Buffer("XXX")} }; var wire = Model.encode(data, 'der'); assert.equal(wire.toString('hex'), '300a02010130050403585858'); var back = Model.decode(wire, 'der'); assert.deepEqual(back, data); }); it('should honour implicit tag from parent', function() { var SubModel = asn1.define('SubModel', function() { this.seq().obj(this.key('x').octstr()); }); var Model = asn1.define('Model', function() { this.seq().obj(this.key('a').int(), this.key('sub').use(SubModel).implicit(0)); }); var data = { a: 1, sub: {x: new Buffer("123")} }; var wire = Model.encode(data, 'der'); assert.equal(wire.toString('hex'), '300a020101a0050403313233'); var back = Model.decode(wire, 'der'); assert.deepEqual(back, data); }); it('should honour explicit tag from parent', function() { var SubModel = asn1.define('SubModel', function() { this.seq().obj(this.key('x').octstr()); }); var Model = asn1.define('Model', function() { this.seq().obj(this.key('a').int(), this.key('sub').use(SubModel).explicit(0)); }); var data = { a: 1, sub: {x: new Buffer("123")} }; var wire = Model.encode(data, 'der'); assert.equal(wire.toString('hex'), '300c020101a00730050403313233'); var back = Model.decode(wire, 'der'); assert.deepEqual(back, data); }); it('should get model with function call', function() { var SubModel = asn1.define('SubModel', function() { this.seq().obj(this.key('x').octstr()); }); var Model = asn1.define('Model', function() { this.seq().obj(this.key('a').int(), this.key('sub').use(function(obj) { assert.equal(obj.a, 1); return SubModel; })); }); var data = { a: 1, sub: {x: new Buffer("123")} }; var wire = Model.encode(data, 'der'); assert.equal(wire.toString('hex'), '300a02010130050403313233'); var back = Model.decode(wire, 'der'); assert.deepEqual(back, data); }); it('should support recursive submodels', function() { var PlainSubModel = asn1.define('PlainSubModel', function() { this.int(); }); var RecursiveModel = asn1.define('RecursiveModel', function() { this.seq().obj(this.key('plain').bool(), this.key('content').use(function(obj) { if (obj.plain) { return PlainSubModel; } else { return RecursiveModel; } })); }); var data = { 'plain': false, 'content': { 'plain': true, 'content': 1 } }; var wire = RecursiveModel.encode(data, 'der'); assert.equal(wire.toString('hex'), '300b01010030060101ff020101'); var back = RecursiveModel.decode(wire, 'der'); assert.deepEqual(back, data); }); }); }); })(require("buffer").Buffer);
{ "content_hash": "cadfb090730503b5df93208cef39e611", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 90, "avg_line_length": 36.63725490196079, "alnum_prop": 0.5164570511105164, "repo_name": "robwormald/gitrank", "id": "149715b18c15ba8e6f29a96d956150189c89077d", "size": "3737", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/packages/npm/[email protected]/test/use-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "613" }, { "name": "CSS", "bytes": "879936" }, { "name": "CoffeeScript", "bytes": "2294" }, { "name": "Emacs Lisp", "bytes": "178" }, { "name": "Gnuplot", "bytes": "5822" }, { "name": "HTML", "bytes": "9337" }, { "name": "JavaScript", "bytes": "8389690" }, { "name": "LiveScript", "bytes": "5528" }, { "name": "Makefile", "bytes": "3179" }, { "name": "Perl", "bytes": "21591" }, { "name": "Shell", "bytes": "2503" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0"> <DefaultLanguage xmlns="" code="en-US" /> <Languages xmlns=""> <Language code="de-DE" /> <Language code="en-GB" /> <Language code="en-US" /> <Language code="de-DE" /> <Language code="ro-RO" /> <Language code="sl-SI" /> <Language code="zh-CN" /> <Language code="ar-SA" /> <Language code="hr-HR" /> <Language code="nl-NL" /> <Language code="fi-FI" /> <Language code="fr-FR" /> <Language code="he-IL" /> <Language code="hu-HU" /> <Language code="it-IT" /> <Language code="lt-LT" /> <Language code="pl-PL" /> <Language code="pt-BR" /> <Language code="pt-PT" /> <Language code="ru-RU" /> <Language code="uk-UA" /> <Language code="vi-VN" /> <Language code="sv-SE" /> <Language code="nb-NO" /> <Language code="pl-PL" /> <Language code="es-ES" /> <Language code="ar-SA" /> </Languages> <App xmlns="" ProductID="{75ef9338-4d56-4b90-bf28-ab5f9a784bb4}" Title="RateMyPanoramaApp" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="RateMyPanoramaApp author" Description="Sample description" Publisher="RateMyPanoramaApp" PublisherID="{eab5a3fd-04db-4994-a934-b88776a52a8d}"> <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath> <Capabilities> <Capability Name="ID_CAP_NETWORKING" /> <Capability Name="ID_CAP_MEDIALIB_AUDIO" /> <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" /> <Capability Name="ID_CAP_SENSORS" /> <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" /> </Capabilities> <Tasks> <DefaultTask Name="_default" NavigationPage="MainPage.xaml" /> </Tasks> <Tokens> <PrimaryToken TokenID="RateMyPanoramaAppToken" TaskName="_default"> <TemplateFlip> <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI> <Count>0</Count> <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI> <Title>RateMyPanoramaApp</Title> <BackContent></BackContent> <BackBackgroundImageURI></BackBackgroundImageURI> <BackTitle></BackTitle> <DeviceLockImageURI></DeviceLockImageURI> <HasLarge></HasLarge> </TemplateFlip> </PrimaryToken> </Tokens> <ScreenResolutions> <ScreenResolution Name="ID_RESOLUTION_WVGA" /> <ScreenResolution Name="ID_RESOLUTION_WXGA" /> <ScreenResolution Name="ID_RESOLUTION_HD720P" /> </ScreenResolutions> </App> </Deployment>
{ "content_hash": "c89db72dd6b3f334750e9f11d24e08b1", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 307, "avg_line_length": 41.515151515151516, "alnum_prop": 0.6448905109489051, "repo_name": "greenSyntax/BookerWP", "id": "e710a40a1840129e6dced2df3db73c1b8f3bdb41", "size": "2742", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Docu_Booker/RateMe/rate-my-app-master/RateMyAppDemos/WP8/RateMyPanoramaApp/Properties/WMAppManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "526" }, { "name": "C#", "bytes": "149752" }, { "name": "C++", "bytes": "28065" } ], "symlink_target": "" }
using bookmarks::BookmarkModel; namespace { template<typename T> void GetValueAndQuit(T* result, const base::Closure& quit, T actual) { *result = actual; quit.Run(); } template<typename T> T GetCallbackResult( const base::Callback<void(const base::Callback<void(T)>&)>& callback) { T result = false; base::RunLoop loop; callback.Run(base::Bind(&GetValueAndQuit<T>, &result, loop.QuitClosure())); loop.Run(); return result; } // A pref store that can have its read_error property changed for testing. class TestingPrefStoreWithCustomReadError : public TestingPrefStore { public: TestingPrefStoreWithCustomReadError() : read_error_(PersistentPrefStore::PREF_READ_ERROR_NO_FILE) { // By default the profile is "new" (NO_FILE means that the profile // wasn't found on disk, so it was created). } PrefReadError GetReadError() const override { return read_error_; } bool IsInitializationComplete() const override { return true; } void set_read_error(PrefReadError read_error) { read_error_ = read_error; } private: ~TestingPrefStoreWithCustomReadError() override {} PrefReadError read_error_; }; #if BUILDFLAG(ENABLE_EXTENSIONS) #if defined(OS_WIN) const base::FilePath::CharType kExtensionFilePath[] = FILE_PATH_LITERAL("c:\\foo"); #elif defined(OS_POSIX) const base::FilePath::CharType kExtensionFilePath[] = FILE_PATH_LITERAL("/oo"); #endif static scoped_refptr<extensions::Extension> CreateExtension( const std::string& name, const std::string& id, extensions::Manifest::Location location) { base::DictionaryValue manifest; manifest.SetString(extensions::manifest_keys::kVersion, "1.0.0.0"); manifest.SetString(extensions::manifest_keys::kName, name); std::string error; scoped_refptr<extensions::Extension> extension = extensions::Extension::Create( base::FilePath(kExtensionFilePath).AppendASCII(name), location, manifest, extensions::Extension::NO_FLAGS, id, &error); return extension; } #endif } // namespace class ProfileSigninConfirmationHelperTest : public testing::Test { public: ProfileSigninConfirmationHelperTest() : user_prefs_(NULL), model_(NULL) { } void SetUp() override { // Create the profile. TestingProfile::Builder builder; user_prefs_ = new TestingPrefStoreWithCustomReadError; sync_preferences::TestingPrefServiceSyncable* pref_service = new sync_preferences::TestingPrefServiceSyncable( new TestingPrefStore(), new TestingPrefStore(), user_prefs_, new TestingPrefStore(), new user_prefs::PrefRegistrySyncable(), new PrefNotifierImpl()); chrome::RegisterUserProfilePrefs(pref_service->registry()); builder.SetPrefService( base::WrapUnique<sync_preferences::PrefServiceSyncable>(pref_service)); profile_ = builder.Build(); // Initialize the services we check. profile_->CreateBookmarkModel(true); model_ = BookmarkModelFactory::GetForBrowserContext(profile_.get()); bookmarks::test::WaitForBookmarkModelToLoad(model_); ASSERT_TRUE(profile_->CreateHistoryService(true, false)); #if BUILDFLAG(ENABLE_EXTENSIONS) extensions::TestExtensionSystem* system = static_cast<extensions::TestExtensionSystem*>( extensions::ExtensionSystem::Get(profile_.get())); base::CommandLine command_line(base::CommandLine::NO_PROGRAM); system->CreateExtensionService(&command_line, base::FilePath(kExtensionFilePath), false); #endif } void TearDown() override { // TestExtensionSystem uses DeleteSoon, so we need to delete the profile // and then run the message queue to clean up. profile_.reset(); base::RunLoop().RunUntilIdle(); } protected: content::TestBrowserThreadBundle thread_bundle_; std::unique_ptr<TestingProfile> profile_; TestingPrefStoreWithCustomReadError* user_prefs_; BookmarkModel* model_; #if defined OS_CHROMEOS chromeos::ScopedTestDeviceSettingsService test_device_settings_service_; chromeos::ScopedTestCrosSettings test_cros_settings_; chromeos::ScopedTestUserManager test_user_manager_; #endif }; // http://crbug.com/393149 TEST_F(ProfileSigninConfirmationHelperTest, DISABLED_DoNotPromptForNewProfile) { // Profile is new and there's no profile data. EXPECT_FALSE( GetCallbackResult( base::Bind( &ui::CheckShouldPromptForNewProfile, profile_.get()))); } TEST_F(ProfileSigninConfirmationHelperTest, PromptForNewProfile_Bookmarks) { ASSERT_TRUE(model_); // Profile is new but has bookmarks. model_->AddURL(model_->bookmark_bar_node(), 0, base::string16(base::ASCIIToUTF16("foo")), GURL("http://foo.com")); EXPECT_TRUE( GetCallbackResult( base::Bind( &ui::CheckShouldPromptForNewProfile, profile_.get()))); } #if BUILDFLAG(ENABLE_EXTENSIONS) TEST_F(ProfileSigninConfirmationHelperTest, PromptForNewProfile_Extensions) { ExtensionService* extensions = extensions::ExtensionSystem::Get(profile_.get())->extension_service(); ASSERT_TRUE(extensions); // Profile is new but has synced extensions. // (The web store doesn't count.) scoped_refptr<extensions::Extension> webstore = CreateExtension("web store", extensions::kWebStoreAppId, extensions::Manifest::COMPONENT); extensions::ExtensionPrefs::Get(profile_.get()) ->AddGrantedPermissions(webstore->id(), extensions::PermissionSet()); extensions->AddExtension(webstore.get()); EXPECT_FALSE(GetCallbackResult( base::Bind(&ui::CheckShouldPromptForNewProfile, profile_.get()))); scoped_refptr<extensions::Extension> extension = CreateExtension("foo", std::string(), extensions::Manifest::INTERNAL); extensions::ExtensionPrefs::Get(profile_.get()) ->AddGrantedPermissions(extension->id(), extensions::PermissionSet()); extensions->AddExtension(extension.get()); EXPECT_TRUE(GetCallbackResult( base::Bind(&ui::CheckShouldPromptForNewProfile, profile_.get()))); } #endif // http://crbug.com/393149 TEST_F(ProfileSigninConfirmationHelperTest, DISABLED_PromptForNewProfile_History) { history::HistoryService* history = HistoryServiceFactory::GetForProfile( profile_.get(), ServiceAccessType::EXPLICIT_ACCESS); ASSERT_TRUE(history); // Profile is new but has more than $(kHistoryEntriesBeforeNewProfilePrompt) // history items. char buf[18]; for (int i = 0; i < 10; i++) { base::snprintf(buf, arraysize(buf), "http://foo.com/%d", i); history->AddPage( GURL(std::string(buf)), base::Time::Now(), NULL, 1, GURL(), history::RedirectList(), ui::PAGE_TRANSITION_LINK, history::SOURCE_BROWSED, false); } EXPECT_TRUE( GetCallbackResult( base::Bind( &ui::CheckShouldPromptForNewProfile, profile_.get()))); } // http://crbug.com/393149 TEST_F(ProfileSigninConfirmationHelperTest, DISABLED_PromptForNewProfile_TypedURLs) { history::HistoryService* history = HistoryServiceFactory::GetForProfile( profile_.get(), ServiceAccessType::EXPLICIT_ACCESS); ASSERT_TRUE(history); // Profile is new but has a typed URL. history->AddPage( GURL("http://example.com"), base::Time::Now(), NULL, 1, GURL(), history::RedirectList(), ui::PAGE_TRANSITION_TYPED, history::SOURCE_BROWSED, false); EXPECT_TRUE( GetCallbackResult( base::Bind( &ui::CheckShouldPromptForNewProfile, profile_.get()))); } TEST_F(ProfileSigninConfirmationHelperTest, PromptForNewProfile_Restarted) { // Browser has been shut down since profile was created. user_prefs_->set_read_error(PersistentPrefStore::PREF_READ_ERROR_NONE); EXPECT_TRUE( GetCallbackResult( base::Bind( &ui::CheckShouldPromptForNewProfile, profile_.get()))); }
{ "content_hash": "470eb7fb64af70916290f5c403e31437", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 80, "avg_line_length": 34.81818181818182, "alnum_prop": 0.6901653611836379, "repo_name": "google-ar/WebARonARCore", "id": "5c81cb09feb1b07dfcb42ddfb69807ac1e03aafc", "size": "10334", "binary": false, "copies": "2", "ref": "refs/heads/webarcore_57.0.2987.5", "path": "chrome/browser/ui/sync/profile_signin_confirmation_helper_unittest.cc", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Modules\Blog\Http\Controllers; use Modules\Blog\Entities\Post; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Vain\Http\Controllers\Controller; class PostController extends Controller { public function index() { $this->authorize('index', Post::class); $posts = Post::with('user', 'category', 'comments') ->published() ->orderBy('published_at', 'desc') ->simplePaginate(config('blog.posts_per_page')); return view('blog::index')->with('posts', $posts); } public function show($slug) { $post = Post::published() ->with('user', 'category') ->where('slug', $slug) ->first(); if ($post === null) { throw new NotFoundHttpException('post with slug \'' . $slug . '\' not found'); } $this->authorize($post); return view('blog::post')->with('post', $post); } }
{ "content_hash": "d53733acf602f6e7c09fea5866cda867", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 90, "avg_line_length": 25.55263157894737, "alnum_prop": 0.5695159629248198, "repo_name": "vainproject/vain-blog", "id": "0ef039a8dcdc23d90e5d1dd2f0875e0f6b34b43e", "size": "971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Blog/Http/Controllers/PostController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2556" }, { "name": "HTML", "bytes": "27034" }, { "name": "PHP", "bytes": "54445" } ], "symlink_target": "" }
=================== Pelican FontAwesome =================== Pelican FontAwesome allows you to embed `FontAwesome <https://fortawesome.github.io/Font-Awesome/>`__ icons in your RST posts and pages. Installation ============ To install pelican-fontawesome, simply install it from PyPI: .. code-block:: bash $ pip install pelican-fontawesome Then enabled it in your pelicanconf.py .. code-block:: python PLUGINS = [ # ... 'pelican_fontawesome', # ... ] Include the FontAwesome CSS in your base template. .. code-block:: html <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> Usage ===== In your article or page, you simply need to add a reference to FontAwesome and then the icon name. .. code-block:: rst :fa:`fa-github` Which will result in: .. code-block:: html <span class="fa fa-github"></span> And to the user will see: :fa:`fa-github` You can also increase the size, just like the `FontAwesome documentation <https://fortawesome.github.io/Font-Awesome/examples/>`__ shows. .. code-block:: rst :fa:`fa-github fa-4x` Will result in: :fa:`fa-github fa-4x` License ======= `MIT`_ license. .. _MIT: http://opensource.org/licenses/MIT
{ "content_hash": "0bff9b5e49e7c8eecc2ced90faabc36d", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 104, "avg_line_length": 18.58823529411765, "alnum_prop": 0.6534810126582279, "repo_name": "kura/pelican-fontawesome", "id": "1896e00433c16c8766abde2f4dd166244c04b96b", "size": "1264", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "4371" } ], "symlink_target": "" }
package com.example.propertyanimation.mvp.model; import com.example.propertyanimation.mvp.presenter.onSearchListener; /** * 创建者 李文东 * 创建时间 2017/11/30 18:52 * 描述 * 更新者 $Author$ * 更新时间 $Date$ * 更新描述 */ public interface ISearchModel { void getIpaddressInfos(String ipAddress,onSearchListener onSearchListener); }
{ "content_hash": "cdb97cfb26dd37517ee39c49e0cabbb8", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 77, "avg_line_length": 20.875, "alnum_prop": 0.7275449101796407, "repo_name": "lwd1815/Transition", "id": "950828e9698da6d8e96a12a3b8bf9a24bb7bd58c", "size": "380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "propertyanimation/src/main/java/com/example/propertyanimation/mvp/model/ISearchModel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "700790" } ], "symlink_target": "" }
import CoverageTools const MallocInfo = CoverageTools.MallocInfo const analyze_malloc = CoverageTools.analyze_malloc const analyze_malloc_files = CoverageTools.analyze_malloc_files const find_malloc_files = CoverageTools.find_malloc_files const sortbybytes = CoverageTools.sortbybytes # Support Unix command line usage like `julia Coverage.jl $(find ~/.julia/v0.6 -name "*.jl.mem")` if abspath(PROGRAM_FILE) == joinpath(@__DIR__, "Coverage.jl") bc = analyze_malloc_files(ARGS) println(bc) end
{ "content_hash": "354d890caced27077d5ca8d9f0d28907", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 97, "avg_line_length": 38.69230769230769, "alnum_prop": 0.7693836978131213, "repo_name": "IainNZ/Coverage.jl", "id": "14aae93025641fcab3f393330e9902c60d1d0e6a", "size": "503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/memalloc.jl", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "28647" } ], "symlink_target": "" }
<!doctype html> <html amp <?php echo AMP_HTML_Utils::build_attributes_string( $this->get( 'html_tag_attributes' ) ); ?>> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <?php do_action( 'amp_post_template_head', $this ); ?> <style amp-custom> <?php $this->load_parts( array( 'style' ) ); ?> <?php do_action( 'amp_post_template_css', $this ); ?> </style> </head> <body class="<?php echo esc_attr( $this->get( 'body_class' ) ); ?>"> <?php $this->load_parts( array( 'header-bar' ) ); ?> <article class="amp-wp-article"> <header class="amp-wp-article-header"> <h1 class="amp-wp-title"><?php echo wp_kses_data( $this->get( 'post_title' ) ); ?></h1> <?php $this->load_parts( apply_filters( 'amp_post_article_header_meta', array( 'meta-author', 'meta-time' ) ) ); ?> </header> <?php $this->load_parts( array( 'featured-image' ) ); ?> <div class="amp-wp-article-content"> <?php echo $this->get( 'post_amp_content' ); // amphtml content; no kses ?> </div> <footer class="amp-wp-article-footer"> <?php $this->load_parts( apply_filters( 'amp_post_article_footer_meta', array( 'meta-taxonomy', 'meta-comments-link' ) ) ); ?> </footer> </article> <?php $this->load_parts( array( 'footer' ) ); ?> <?php do_action( 'amp_post_template_footer', $this ); ?> </body> </html>
{ "content_hash": "c6a74ba3fec9c61316be395eff62bcf0", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 128, "avg_line_length": 33.90243902439025, "alnum_prop": 0.6287769784172662, "repo_name": "nicholasgriffintn/Accelerated-Mobile-Pages", "id": "9b1348618d665ce8cb62e27929999b35bde8185e", "size": "1390", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "includes/vendor/amp/templates/single.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "120727" }, { "name": "JavaScript", "bytes": "326140" }, { "name": "PHP", "bytes": "1787669" } ], "symlink_target": "" }
#ifndef __DALI_INTERNAL_SCENE_GRAPH_ANIMATOR_H__ #define __DALI_INTERNAL_SCENE_GRAPH_ANIMATOR_H__ // INTERNAL INCLUDES #include <dali/devel-api/common/owner-container.h> #include <dali/internal/event/animation/key-frames-impl.h> #include <dali/internal/event/animation/path-impl.h> #include <dali/internal/update/nodes/node.h> #include <dali/internal/update/common/property-base.h> #include <dali/public-api/animation/alpha-function.h> #include <dali/public-api/animation/animation.h> #include <dali/public-api/animation/time-period.h> #include <dali/public-api/common/constants.h> #include <dali/public-api/common/dali-common.h> #include <dali/public-api/math/quaternion.h> #include <dali/public-api/math/radian.h> #include <dali/internal/update/animation/property-accessor.h> namespace Dali { namespace Internal { typedef Dali::Animation::Interpolation Interpolation; struct AnimatorFunctionBase; namespace SceneGraph { class AnimatorBase; typedef OwnerContainer< AnimatorBase* > AnimatorContainer; typedef AnimatorContainer::Iterator AnimatorIter; typedef AnimatorContainer::ConstIterator AnimatorConstIter; /** * An abstract base class for Animators, which can be added to scene graph animations. * Each animator changes a single property of an object in the scene graph. */ class AnimatorBase { public: typedef float (*AlphaFunc)(float progress); ///< Definition of an alpha function /** * Constructor. */ AnimatorBase() : mDurationSeconds(1.0f), mInitialDelaySeconds(0.0f), mAlphaFunction(AlphaFunction::DEFAULT), mDisconnectAction(Dali::Animation::BakeFinal), mActive(false), mEnabled(true), mConnectedToSceneGraph(false) { } /** * Virtual destructor. */ virtual ~AnimatorBase() { } /** * Called when Animator is added to the scene-graph in update-thread. */ virtual void ConnectToSceneGraph() = 0; /** * Set the duration of the animator. * @pre durationSeconds must be zero or greater; zero is useful when animating boolean values. * @param [in] seconds Duration in seconds. */ void SetDuration(float seconds) { DALI_ASSERT_DEBUG(seconds >= 0.0f); mDurationSeconds = seconds; } /** * Retrieve the duration of the animator. * @return The duration in seconds. */ float GetDuration() { return mDurationSeconds; } /** * Set the delay before the animator should take effect. * The default is zero i.e. no delay. * @param [in] seconds The delay in seconds. */ void SetInitialDelay(float seconds) { mInitialDelaySeconds = seconds; } /** * Retrieve the initial delay of the animator. * @return The delay in seconds. */ float GetInitialDelay() { return mInitialDelaySeconds; } /** * Set the alpha function for an animator. * @param [in] alphaFunc The alpha function to apply to the animation progress. */ void SetAlphaFunction(const AlphaFunction& alphaFunction) { mAlphaFunction = alphaFunction; } /** * Retrieve the alpha function of an animator. * @return The function. */ AlphaFunction GetAlphaFunction() const { return mAlphaFunction; } /* * Applies the alpha function to the specified progress * @param[in] Current progress * @return The progress after the alpha function has been aplied */ float ApplyAlphaFunction( float progress ) const { float result = progress; AlphaFunction::Mode alphaFunctionMode( mAlphaFunction.GetMode() ); if( alphaFunctionMode == AlphaFunction::BUILTIN_FUNCTION ) { switch(mAlphaFunction.GetBuiltinFunction()) { case AlphaFunction::DEFAULT: case AlphaFunction::LINEAR: { break; } case AlphaFunction::REVERSE: { result = 1.0f-progress; break; } case AlphaFunction::EASE_IN_SQUARE: { result = progress * progress; break; } case AlphaFunction::EASE_OUT_SQUARE: { result = 1.0f - (1.0f-progress) * (1.0f-progress); break; } case AlphaFunction::EASE_IN: { result = progress * progress * progress; break; } case AlphaFunction::EASE_OUT: { result = (progress-1.0f) * (progress-1.0f) * (progress-1.0f) + 1.0f; break; } case AlphaFunction::EASE_IN_OUT: { result = progress*progress*(3.0f-2.0f*progress); break; } case AlphaFunction::EASE_IN_SINE: { result = -1.0f * cosf(progress * Math::PI_2) + 1.0f; break; } case AlphaFunction::EASE_OUT_SINE: { result = sinf(progress * Math::PI_2); break; } case AlphaFunction::EASE_IN_OUT_SINE: { result = -0.5f * (cosf(Math::PI * progress) - 1.0f); break; } case AlphaFunction::BOUNCE: { result = sinf(progress * Math::PI); break; } case AlphaFunction::SIN: { result = 0.5f - cosf(progress * 2.0f * Math::PI) * 0.5f; break; } case AlphaFunction::EASE_OUT_BACK: { const float sqrt2 = 1.70158f; progress -= 1.0f; result = 1.0f + progress * progress * ( ( sqrt2 + 1.0f ) * progress + sqrt2 ); break; } case AlphaFunction::COUNT: { break; } } } else if( alphaFunctionMode == AlphaFunction::CUSTOM_FUNCTION ) { AlphaFunctionPrototype customFunction = mAlphaFunction.GetCustomFunction(); if( customFunction ) { result = customFunction(progress); } } else { //If progress is very close to 0 or very close to 1 we don't need to evaluate the curve as the result will //be almost 0 or almost 1 respectively if( ( progress > Math::MACHINE_EPSILON_1 ) && ((1.0f - progress) > Math::MACHINE_EPSILON_1) ) { Dali::Vector4 controlPoints = mAlphaFunction.GetBezierControlPoints(); static const float tolerance = 0.001f; //10 iteration max //Perform a binary search on the curve float lowerBound(0.0f); float upperBound(1.0f); float currentT(0.5f); float currentX = EvaluateCubicBezier( controlPoints.x, controlPoints.z, currentT); while( fabs( progress - currentX ) > tolerance ) { if( progress > currentX ) { lowerBound = currentT; } else { upperBound = currentT; } currentT = (upperBound+lowerBound)*0.5f; currentX = EvaluateCubicBezier( controlPoints.x, controlPoints.z, currentT); } result = EvaluateCubicBezier( controlPoints.y, controlPoints.w, currentT); } } return result; } /** * Whether to bake the animation if attached property owner is disconnected. * Property is only baked if the animator is active. * @param [in] action The disconnect action. */ void SetDisconnectAction( Dali::Animation::EndAction action ) { mDisconnectAction = action; } /** * Retrieve the disconnect action of an animator. * @return The disconnect action. */ Dali::Animation::EndAction GetDisconnectAction() const { return mDisconnectAction; } /** * Whether the animator is active or not. * @param [in] active The new active state. * @post When the animator becomes active, it applies the disconnect-action if the property owner is then disconnected. * @note When the property owner is disconnected, the active state is set to false. */ void SetActive( bool active ) { mActive = active; } /** * Retrieve whether the animator has been set to active or not. * @return The active state. */ bool GetActive() const { return mActive; } /* * Retrive wheter the animator's target object is valid and on the stage. * @return The enabled state. */ bool IsEnabled() const { return mEnabled; } /** * Returns wheter the target object of the animator is still valid * or has been destroyed. * @return True if animator is orphan, false otherwise * * @note The SceneGraph::Animation will delete any orphan animator in its Update method. */ virtual bool Orphan() = 0; /** * Update the scene object attached to the animator. * @param[in] bufferIndex The buffer to animate. * @param[in] progress A value from 0 to 1, where 0 is the start of the animation, and 1 is the end point. * @param[in] bake Bake. */ virtual void Update(BufferIndex bufferIndex, float progress, bool bake) = 0; protected: /** * Helper function to evaluate a cubic bezier curve assuming first point is at 0.0 and last point is at 1.0 * @param[in] p0 First control point of the bezier curve * @param[in] p1 Second control point of the bezier curve * @param[in] t A floating point value between 0.0 and 1.0 * @return Value of the curve at progress t */ inline float EvaluateCubicBezier( float p0, float p1, float t ) const { float tSquare = t*t; return 3.0f*(1.0f-t)*(1.0f-t)*t*p0 + 3.0f*(1.0f-t)*tSquare*p1 + tSquare*t; } float mDurationSeconds; float mInitialDelaySeconds; AlphaFunction mAlphaFunction; Dali::Animation::EndAction mDisconnectAction; ///< EndAction to apply when target object gets disconnected from the stage. bool mActive:1; ///< Animator is "active" while it's running. bool mEnabled:1; ///< Animator is "enabled" while its target object is valid and on the stage. bool mConnectedToSceneGraph:1; ///< True if ConnectToSceneGraph() has been called in update-thread. }; /** * An animator for a specific property type PropertyType. */ template < typename PropertyType, typename PropertyAccessorType > class Animator : public AnimatorBase, public PropertyOwner::Observer { public: /** * Construct a new property animator. * @param[in] property The animatable property; only valid while the Animator is attached. * @param[in] animatorFunction The function used to animate the property. * @param[in] alphaFunction The alpha function to apply. * @param[in] timePeriod The time period of this animation. * @return A newly allocated animator. */ static AnimatorBase* New( const PropertyOwner& propertyOwner, const PropertyBase& property, AnimatorFunctionBase* animatorFunction, AlphaFunction alphaFunction, const TimePeriod& timePeriod ) { typedef Animator< PropertyType, PropertyAccessorType > AnimatorType; // The property was const in the actor-thread, but animators are used in the scene-graph thread. AnimatorType* animator = new AnimatorType( const_cast<PropertyOwner*>( &propertyOwner ), const_cast<PropertyBase*>( &property ), animatorFunction ); animator->SetAlphaFunction( alphaFunction ); animator->SetInitialDelay( timePeriod.delaySeconds ); animator->SetDuration( timePeriod.durationSeconds ); return animator; } /** * Virtual destructor. */ virtual ~Animator() { if (mPropertyOwner && mConnectedToSceneGraph) { mPropertyOwner->RemoveObserver(*this); } delete mAnimatorFunction; } /** * Called when Animator is added to the scene-graph in update-thread. */ virtual void ConnectToSceneGraph() { mConnectedToSceneGraph = true; mPropertyOwner->AddObserver(*this); } /** * Called when mPropertyOwner is connected to the scene graph. */ virtual void PropertyOwnerConnected( PropertyOwner& owner ) { mEnabled = true; } /** * Called when mPropertyOwner is disconnected from the scene graph. */ virtual void PropertyOwnerDisconnected( BufferIndex bufferIndex, PropertyOwner& owner ) { // If we are active, then bake the value if required if ( mActive && mDisconnectAction != Dali::Animation::Discard ) { // Bake to target-value if BakeFinal, otherwise bake current value Update( bufferIndex, ( mDisconnectAction == Dali::Animation::Bake ? mCurrentProgress : 1.0f ), true ); } mActive = false; mEnabled = false; } /** * Called shortly before mPropertyOwner is destroyed */ virtual void PropertyOwnerDestroyed( PropertyOwner& owner ) { mPropertyOwner = NULL; } /** * From AnimatorBase. */ virtual void Update( BufferIndex bufferIndex, float progress, bool bake ) { float alpha = ApplyAlphaFunction(progress); const PropertyType& current = mPropertyAccessor.Get( bufferIndex ); const PropertyType result = (*mAnimatorFunction)( alpha, current ); if ( bake ) { mPropertyAccessor.Bake( bufferIndex, result ); } else { mPropertyAccessor.Set( bufferIndex, result ); } mCurrentProgress = progress; } /** * From AnimatorBase. */ virtual bool Orphan() { return (mPropertyOwner == NULL); } private: /** * Private constructor; see also Animator::New(). */ Animator( PropertyOwner* propertyOwner, PropertyBase* property, AnimatorFunctionBase* animatorFunction ) : mPropertyOwner( propertyOwner ), mPropertyAccessor( property ), mAnimatorFunction( animatorFunction ), mCurrentProgress( 0.0f ) { // WARNING - this object is created in the event-thread // The scene-graph mPropertyOwner object cannot be observed here } // Undefined Animator( const Animator& ); // Undefined Animator& operator=( const Animator& ); protected: PropertyOwner* mPropertyOwner; PropertyAccessorType mPropertyAccessor; AnimatorFunctionBase* mAnimatorFunction; float mCurrentProgress; }; /** * An animator for a specific property type PropertyType. */ template <typename T, typename PropertyAccessorType> class AnimatorTransformProperty : public AnimatorBase, public PropertyOwner::Observer { public: /** * Construct a new property animator. * @param[in] property The animatable property; only valid while the Animator is attached. * @param[in] animatorFunction The function used to animate the property. * @param[in] alphaFunction The alpha function to apply. * @param[in] timePeriod The time period of this animation. * @return A newly allocated animator. */ static AnimatorBase* New( const PropertyOwner& propertyOwner, const PropertyBase& property, AnimatorFunctionBase* animatorFunction, AlphaFunction alphaFunction, const TimePeriod& timePeriod ) { // The property was const in the actor-thread, but animators are used in the scene-graph thread. AnimatorTransformProperty* animator = new AnimatorTransformProperty( const_cast<PropertyOwner*>( &propertyOwner ), const_cast<PropertyBase*>( &property ), animatorFunction ); animator->SetAlphaFunction( alphaFunction ); animator->SetInitialDelay( timePeriod.delaySeconds ); animator->SetDuration( timePeriod.durationSeconds ); return animator; } /** * Virtual destructor. */ virtual ~AnimatorTransformProperty() { if (mPropertyOwner && mConnectedToSceneGraph) { mPropertyOwner->RemoveObserver(*this); } delete mAnimatorFunction; } /** * Called when Animator is added to the scene-graph in update-thread. */ virtual void ConnectToSceneGraph() { mConnectedToSceneGraph = true; mPropertyOwner->AddObserver(*this); } /** * Called when mPropertyOwner is connected to the scene graph. */ virtual void PropertyOwnerConnected( PropertyOwner& owner ) { mEnabled = true; } /** * Called when mPropertyOwner is disconnected from the scene graph. */ virtual void PropertyOwnerDisconnected( BufferIndex bufferIndex, PropertyOwner& owner ) { // If we are active, then bake the value if required if ( mActive && mDisconnectAction != Dali::Animation::Discard ) { // Bake to target-value if BakeFinal, otherwise bake current value Update( bufferIndex, ( mDisconnectAction == Dali::Animation::Bake ? mCurrentProgress : 1.0f ), true ); } mActive = false; mEnabled = false; } /** * Called shortly before mPropertyOwner is destroyed */ virtual void PropertyOwnerDestroyed( PropertyOwner& owner ) { mPropertyOwner = NULL; } /** * From AnimatorBase. */ virtual void Update( BufferIndex bufferIndex, float progress, bool bake ) { float alpha = ApplyAlphaFunction(progress); const T& current = mPropertyAccessor.Get( bufferIndex ); const T result = (*mAnimatorFunction)( alpha, current ); if ( bake ) { mPropertyAccessor.Bake( bufferIndex, result ); } else { mPropertyAccessor.Set( bufferIndex, result ); } mCurrentProgress = progress; } /** * From AnimatorBase. */ virtual bool Orphan() { return (mPropertyOwner == NULL); } private: /** * Private constructor; see also Animator::New(). */ AnimatorTransformProperty( PropertyOwner* propertyOwner, PropertyBase* property, AnimatorFunctionBase* animatorFunction ) : mPropertyOwner( propertyOwner ), mPropertyAccessor( property ), mAnimatorFunction( animatorFunction ), mCurrentProgress( 0.0f ) { // WARNING - this object is created in the event-thread // The scene-graph mPropertyOwner object cannot be observed here } // Undefined AnimatorTransformProperty( const AnimatorTransformProperty& ); // Undefined AnimatorTransformProperty& operator=( const AnimatorTransformProperty& ); protected: PropertyOwner* mPropertyOwner; PropertyAccessorType mPropertyAccessor; AnimatorFunctionBase* mAnimatorFunction; float mCurrentProgress; }; } // namespace SceneGraph /* * AnimatorFunction base class. * All update functions must inherit from AnimatorFunctionBase and overload the appropiate "()" operator */ struct AnimatorFunctionBase { /** * Constructor */ AnimatorFunctionBase(){} /* * Virtual destructor (Intended as base class) */ virtual ~AnimatorFunctionBase(){} ///Stub "()" operators. virtual bool operator()(float progress, const bool& property) { return property; } virtual float operator()(float progress, const int& property) { return property; } virtual float operator()(float progress, const unsigned int& property) { return property; } virtual float operator()(float progress, const float& property) { return property; } virtual Vector2 operator()(float progress, const Vector2& property) { return property; } virtual Vector3 operator()(float progress, const Vector3& property) { return property; } virtual Vector4 operator()(float progress, const Vector4& property) { return property; } virtual Quaternion operator()(float progress, const Quaternion& property) { return property; } }; // Update functions struct AnimateByInteger : public AnimatorFunctionBase { AnimateByInteger(const int& relativeValue) : mRelative(relativeValue) { } float operator()(float alpha, const int& property) { return int(property + mRelative * alpha + 0.5f ); } int mRelative; }; struct AnimateToInteger : public AnimatorFunctionBase { AnimateToInteger(const int& targetValue) : mTarget(targetValue) { } float operator()(float alpha, const int& property) { return int(property + ((mTarget - property) * alpha) + 0.5f); } int mTarget; }; struct AnimateByFloat : public AnimatorFunctionBase { AnimateByFloat(const float& relativeValue) : mRelative(relativeValue) { } float operator()(float alpha, const float& property) { return float(property + mRelative * alpha); } float mRelative; }; struct AnimateToFloat : public AnimatorFunctionBase { AnimateToFloat(const float& targetValue) : mTarget(targetValue) { } float operator()(float alpha, const float& property) { return float(property + ((mTarget - property) * alpha)); } float mTarget; }; struct AnimateByVector2 : public AnimatorFunctionBase { AnimateByVector2(const Vector2& relativeValue) : mRelative(relativeValue) { } Vector2 operator()(float alpha, const Vector2& property) { return Vector2(property + mRelative * alpha); } Vector2 mRelative; }; struct AnimateToVector2 : public AnimatorFunctionBase { AnimateToVector2(const Vector2& targetValue) : mTarget(targetValue) { } Vector2 operator()(float alpha, const Vector2& property) { return Vector2(property + ((mTarget - property) * alpha)); } Vector2 mTarget; }; struct AnimateByVector3 : public AnimatorFunctionBase { AnimateByVector3(const Vector3& relativeValue) : mRelative(relativeValue) { } Vector3 operator()(float alpha, const Vector3& property) { return Vector3(property + mRelative * alpha); } Vector3 mRelative; }; struct AnimateToVector3 : public AnimatorFunctionBase { AnimateToVector3(const Vector3& targetValue) : mTarget(targetValue) { } Vector3 operator()(float alpha, const Vector3& property) { return Vector3(property + ((mTarget - property) * alpha)); } Vector3 mTarget; }; struct AnimateByVector4 : public AnimatorFunctionBase { AnimateByVector4(const Vector4& relativeValue) : mRelative(relativeValue) { } Vector4 operator()(float alpha, const Vector4& property) { return Vector4(property + mRelative * alpha); } Vector4 mRelative; }; struct AnimateToVector4 : public AnimatorFunctionBase { AnimateToVector4(const Vector4& targetValue) : mTarget(targetValue) { } Vector4 operator()(float alpha, const Vector4& property) { return Vector4(property + ((mTarget - property) * alpha)); } Vector4 mTarget; }; struct AnimateByOpacity : public AnimatorFunctionBase { AnimateByOpacity(const float& relativeValue) : mRelative(relativeValue) { } Vector4 operator()(float alpha, const Vector4& property) { Vector4 result(property); result.a += mRelative * alpha; return result; } float mRelative; }; struct AnimateToOpacity : public AnimatorFunctionBase { AnimateToOpacity(const float& targetValue) : mTarget(targetValue) { } Vector4 operator()(float alpha, const Vector4& property) { Vector4 result(property); result.a = property.a + ((mTarget - property.a) * alpha); return result; } float mTarget; }; struct AnimateByBoolean : public AnimatorFunctionBase { AnimateByBoolean(bool relativeValue) : mRelative(relativeValue) { } bool operator()(float alpha, const bool& property) { // Alpha is not useful here, just keeping to the same template as other update functors return bool(alpha >= 1.0f ? (property || mRelative) : property); } bool mRelative; }; struct AnimateToBoolean : public AnimatorFunctionBase { AnimateToBoolean(bool targetValue) : mTarget(targetValue) { } bool operator()(float alpha, const bool& property) { // Alpha is not useful here, just keeping to the same template as other update functors return bool(alpha >= 1.0f ? mTarget : property); } bool mTarget; }; struct RotateByAngleAxis : public AnimatorFunctionBase { RotateByAngleAxis(const Radian& angleRadians, const Vector3& axis) : mAngleRadians( angleRadians ), mAxis(axis.x, axis.y, axis.z) { } Quaternion operator()(float alpha, const Quaternion& rotation) { if (alpha > 0.0f) { return rotation * Quaternion(mAngleRadians * alpha, mAxis); } return rotation; } Radian mAngleRadians; Vector3 mAxis; }; struct RotateToQuaternion : public AnimatorFunctionBase { RotateToQuaternion(const Quaternion& targetValue) : mTarget(targetValue) { } Quaternion operator()(float alpha, const Quaternion& rotation) { return Quaternion::Slerp(rotation, mTarget, alpha); } Quaternion mTarget; }; struct KeyFrameBooleanFunctor : public AnimatorFunctionBase { KeyFrameBooleanFunctor(KeyFrameBooleanPtr keyFrames) : mKeyFrames(keyFrames) { } bool operator()(float progress, const bool& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, Dali::Animation::Linear); } return property; } KeyFrameBooleanPtr mKeyFrames; }; struct KeyFrameIntegerFunctor : public AnimatorFunctionBase { KeyFrameIntegerFunctor(KeyFrameIntegerPtr keyFrames, Interpolation interpolation) : mKeyFrames(keyFrames),mInterpolation(interpolation) { } float operator()(float progress, const int& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, mInterpolation); } return property; } KeyFrameIntegerPtr mKeyFrames; Interpolation mInterpolation; }; struct KeyFrameNumberFunctor : public AnimatorFunctionBase { KeyFrameNumberFunctor(KeyFrameNumberPtr keyFrames, Interpolation interpolation) : mKeyFrames(keyFrames),mInterpolation(interpolation) { } float operator()(float progress, const float& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, mInterpolation); } return property; } KeyFrameNumberPtr mKeyFrames; Interpolation mInterpolation; }; struct KeyFrameVector2Functor : public AnimatorFunctionBase { KeyFrameVector2Functor(KeyFrameVector2Ptr keyFrames, Interpolation interpolation) : mKeyFrames(keyFrames),mInterpolation(interpolation) { } Vector2 operator()(float progress, const Vector2& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, mInterpolation); } return property; } KeyFrameVector2Ptr mKeyFrames; Interpolation mInterpolation; }; struct KeyFrameVector3Functor : public AnimatorFunctionBase { KeyFrameVector3Functor(KeyFrameVector3Ptr keyFrames, Interpolation interpolation) : mKeyFrames(keyFrames),mInterpolation(interpolation) { } Vector3 operator()(float progress, const Vector3& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, mInterpolation); } return property; } KeyFrameVector3Ptr mKeyFrames; Interpolation mInterpolation; }; struct KeyFrameVector4Functor : public AnimatorFunctionBase { KeyFrameVector4Functor(KeyFrameVector4Ptr keyFrames, Interpolation interpolation) : mKeyFrames(keyFrames),mInterpolation(interpolation) { } Vector4 operator()(float progress, const Vector4& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, mInterpolation); } return property; } KeyFrameVector4Ptr mKeyFrames; Interpolation mInterpolation; }; struct KeyFrameQuaternionFunctor : public AnimatorFunctionBase { KeyFrameQuaternionFunctor(KeyFrameQuaternionPtr keyFrames) : mKeyFrames(keyFrames) { } Quaternion operator()(float progress, const Quaternion& property) { if(mKeyFrames->IsActive(progress)) { return mKeyFrames->GetValue(progress, Dali::Animation::Linear); } return property; } KeyFrameQuaternionPtr mKeyFrames; }; struct PathPositionFunctor : public AnimatorFunctionBase { PathPositionFunctor( PathPtr path ) : mPath(path) { } Vector3 operator()(float progress, const Vector3& property) { Vector3 position(property); static_cast<void>( mPath->SamplePosition(progress, position) ); return position; } PathPtr mPath; }; struct PathRotationFunctor : public AnimatorFunctionBase { PathRotationFunctor( PathPtr path, const Vector3& forward ) : mPath(path), mForward( forward ) { mForward.Normalize(); } Quaternion operator()(float progress, const Quaternion& property) { Vector3 tangent; if( mPath->SampleTangent(progress, tangent) ) { return Quaternion( mForward, tangent ); } else { return property; } } PathPtr mPath; Vector3 mForward; }; } // namespace Internal } // namespace Dali #endif // __DALI_INTERNAL_SCENE_GRAPH_ANIMATOR_H__
{ "content_hash": "41b8d7fe1b7aeb5fcdef17893ae72314", "timestamp": "", "source": "github", "line_count": 1166, "max_line_length": 129, "avg_line_length": 24.49828473413379, "alnum_prop": 0.6714510764922107, "repo_name": "pwisbey/dali-core", "id": "b3694b7b458d6e894a3dbd3b1e9e4d95986314c9", "size": "29180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dali/internal/update/animation/scene-graph-animator.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "60713" }, { "name": "C++", "bytes": "7154020" }, { "name": "CMake", "bytes": "2359" }, { "name": "M4", "bytes": "4140" }, { "name": "Makefile", "bytes": "9168" }, { "name": "Perl", "bytes": "55782" }, { "name": "Shell", "bytes": "27707" } ], "symlink_target": "" }
#import "hsp.h" @interface HSP(dpmread) int dpm_ini( char *dpmfile, long dpmofs, int chksum, int deckey ); void dpm_bye( void ); FILE *dpm_open( char *fname ); int dpm_fread( void *mem, int size, FILE *stream ); void dpm_close(); int dpm_read( char *fname, void *readmem, int rlen, int seekofs ); int dpm_exist( char *fname ); void dpm_getinf( char *inf ); int dpm_filecopy( char *fname, char *sname ); int dpm_filebase( char *fname ); void dpm_memfile( void *mem, int size ); char *dpm_readalloc( char *fname ); @end
{ "content_hash": "5f10b2c5ef91771709c505361ac5ff68", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 66, "avg_line_length": 28.36842105263158, "alnum_prop": 0.660482374768089, "repo_name": "dolphilia/hsp3cl-macosx", "id": "d5c139e20b75d960a8205a839f981b1a62d2afe6", "size": "563", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "13_update/hspcl-strnote-objc/dpmread.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1037449" }, { "name": "C++", "bytes": "445944" }, { "name": "Objective-C", "bytes": "1135059" }, { "name": "Objective-C++", "bytes": "7599439" } ], "symlink_target": "" }
package org.jasig.portal.events.aggr.concuser; import org.jasig.portal.events.aggr.BaseGroupedAggregationDiscriminatorImpl; import org.jasig.portal.events.aggr.groups.AggregatedGroupMapping; import org.jasig.portal.utils.ComparableExtractingComparator; public final class ConcurrentUserAggregationDiscriminatorImpl extends BaseGroupedAggregationDiscriminatorImpl implements ConcurrentUserAggregationDiscriminator { private static final long serialVersionUID = 1L; public ConcurrentUserAggregationDiscriminatorImpl(ConcurrentUserAggregation concurrentUserAggregation) { super(concurrentUserAggregation); } public ConcurrentUserAggregationDiscriminatorImpl(AggregatedGroupMapping aggregatedGroupMapping) { super(aggregatedGroupMapping); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof ConcurrentUserAggregationDiscriminator)) return false; return super.equals(obj); } // Compare discriminators based on the group name public static class Comparator extends ComparableExtractingComparator<ConcurrentUserAggregationDiscriminator, String> { public static Comparator INSTANCE = new Comparator(); @Override protected String getComparable(ConcurrentUserAggregationDiscriminator o) { return o.getAggregatedGroup().getGroupName(); } } @Override public String toString() { return "ConcurrentUserAggregationDiscriminator [" + super.toString() + "]"; } }
{ "content_hash": "2b9c45e82f5556ba15827c9b7b1543af", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 109, "avg_line_length": 34.69565217391305, "alnum_prop": 0.743734335839599, "repo_name": "joansmith/uPortal", "id": "4f97033b982a2399c72f12212d11c92221945c9c", "size": "2395", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "uportal-war/src/main/java/org/jasig/portal/events/aggr/concuser/ConcurrentUserAggregationDiscriminatorImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "907" }, { "name": "CSS", "bytes": "381173" }, { "name": "Groovy", "bytes": "61435" }, { "name": "HTML", "bytes": "262691" }, { "name": "Java", "bytes": "9396107" }, { "name": "JavaScript", "bytes": "814510" }, { "name": "Perl", "bytes": "1769" }, { "name": "Shell", "bytes": "7292" }, { "name": "XSLT", "bytes": "292088" } ], "symlink_target": "" }
var get = Ember.get, set = Ember.set; var Person, store, array; var testSerializer = DS.JSONSerializer.create({ primaryKey: function() { return 'id'; } }); var TestAdapter = DS.Adapter.extend({ serializer: testSerializer }); module("DS.Model", { setup: function() { store = DS.Store.create({ adapter: TestAdapter.create() }); Person = DS.Model.extend({ name: DS.attr('string'), isDrugAddict: DS.attr('boolean') }); }, teardown: function() { Person = null; store = null; } }); test("can have a property set on it", function() { var record = store.createRecord(Person); set(record, 'name', 'bar'); equal(get(record, 'name'), 'bar', "property was set on the record"); }); test("setting a property on a record that has not changed does not cause it to become dirty", function() { store.load(Person, { id: 1, name: "Peter", isDrugAddict: true }); var person = store.find(Person, 1); equal(person.get('isDirty'), false, "precond - person record should not be dirty"); person.set('name', "Peter"); person.set('isDrugAddict', true); equal(person.get('isDirty'), false, "record does not become dirty after setting property to old value"); }); test("a record reports its unique id via the `id` property", function() { store.load(Person, { id: 1 }); var record = store.find(Person, 1); equal(get(record, 'id'), 1, "reports id as id by default"); }); test("a record's id is included in its toString representation", function() { store.load(Person, { id: 1 }); var record = store.find(Person, 1); equal(record.toString(), '<(subclass of DS.Model):'+Ember.guidFor(record)+':1>', "reports id in toString"); }); test("trying to set an `id` attribute should raise", function() { Person = DS.Model.extend({ id: DS.attr('number'), name: "Scumdale" }); expectAssertion(function() { store.load(Person, { id: 1, name: "Scumdale" }); var person = store.find(Person, 1); }, /You may not set `id`/); }); test("it should use `_reference` and not `reference` to store its reference", function() { store.load(Person, { id: 1 }); var record = store.find(Person, 1); equal(record.get('reference'), undefined, "doesn't shadow reference key"); }); test("it should cache attributes", function() { var store = DS.Store.create(); var Post = DS.Model.extend({ updatedAt: DS.attr('string') }); var dateString = "Sat, 31 Dec 2011 00:08:16 GMT"; var date = new Date(dateString); store.load(Post, { id: 1 }); var record = store.find(Post, 1); record.set('updatedAt', date); deepEqual(date, get(record, 'updatedAt'), "setting a date returns the same date"); strictEqual(get(record, 'updatedAt'), get(record, 'updatedAt'), "second get still returns the same object"); }); module("DS.Model updating", { setup: function() { array = [{ id: 1, name: "Scumbag Dale" }, { id: 2, name: "Scumbag Katz" }, { id: 3, name: "Scumbag Bryn" }]; Person = DS.Model.extend({ name: DS.attr('string') }); store = DS.Store.create(); store.loadMany(Person, array); }, teardown: function() { Person = null; store = null; array = null; } }); test("a DS.Model can update its attributes", function() { var person = store.find(Person, 2); set(person, 'name', "Brohuda Katz"); equal(get(person, 'name'), "Brohuda Katz", "setting took hold"); }); test("a DS.Model can have a defaultValue", function() { var Tag = DS.Model.extend({ name: DS.attr('string', { defaultValue: "unknown" }) }); var tag = Tag.createRecord(); equal(get(tag, 'name'), "unknown", "the default value is found"); set(tag, 'name', null); equal(get(tag, 'name'), null, "null doesn't shadow defaultValue"); }); test("a defaultValue for an attribite can be a function", function() { var Tag = DS.Model.extend({ createdAt: DS.attr('string', { defaultValue: function() { return "le default value"; } }) }); var tag = Tag.createRecord(); equal(get(tag, 'createdAt'), "le default value", "the defaultValue function is evaluated"); }); test("when a DS.Model updates its attributes, its changes affect its filtered Array membership", function() { var people = store.filter(Person, function(hash) { if (hash.get('name').match(/Katz$/)) { return true; } }); equal(get(people, 'length'), 1, "precond - one item is in the RecordArray"); var person = people.objectAt(0); equal(get(person, 'name'), "Scumbag Katz", "precond - the item is correct"); set(person, 'name', "Yehuda Katz"); equal(get(people, 'length'), 1, "there is still one item"); equal(get(person, 'name'), "Yehuda Katz", "it has the updated item"); set(person, 'name', "Yehuda Katz-Foo"); equal(get(people, 'length'), 0, "there are now no items"); }); module("with a simple Person model", { setup: function() { array = [{ id: 1, name: "Scumbag Dale" }, { id: 2, name: "Scumbag Katz" }, { id: 3, name: "Scumbag Bryn" }]; Person = DS.Model.extend({ name: DS.attr('string') }); store = DS.Store.create(); store.loadMany(Person, array); }, teardown: function() { Person = null; store = null; array = null; } }); test("when a DS.Model updates its attributes, its changes affect its filtered Array membership", function() { var people = store.filter(Person, function(hash) { if (hash.get('name').match(/Katz$/)) { return true; } }); equal(get(people, 'length'), 1, "precond - one item is in the RecordArray"); var person = people.objectAt(0); equal(get(person, 'name'), "Scumbag Katz", "precond - the item is correct"); set(person, 'name', "Yehuda Katz"); equal(get(people, 'length'), 1, "there is still one item"); equal(get(person, 'name'), "Yehuda Katz", "it has the updated item"); set(person, 'name', "Yehuda Katz-Foo"); equal(get(people, 'length'), 0, "there are now no items"); }); test("can ask if record with a given id is loaded", function() { equal(store.recordIsLoaded(Person, 1), true, 'should have person with id 1'); equal(store.recordIsLoaded(Person, 4), false, 'should not have person with id 2'); }); test("a listener can be added to a record", function() { var count = 0; var F = function() { count++; }; var record = store.createRecord(Person); record.on('event!', F); record.trigger('event!'); equal(count, 1, "the event was triggered"); record.trigger('event!'); equal(count, 2, "the event was triggered"); }); test("when an event is triggered on a record the method with the same name is invoked with arguments", function(){ var count = 0; var F = function() { count++; }; var record = store.createRecord(Person); record.eventNamedMethod = F; record.trigger('eventNamedMethod'); equal(count, 1, "the corresponding method was called"); }); test("when a method is invoked from an event with the same name the arguments are passed through", function(){ var eventMethodArgs = null; var F = function() { eventMethodArgs = arguments; }; var record = store.createRecord(Person); record.eventThatTriggersMethod = F; record.trigger('eventThatTriggersMethod', 1, 2); equal( eventMethodArgs[0], 1); equal( eventMethodArgs[1], 2); }); var converts = function(type, provided, expected) { var testStore = DS.Store.create(); var Model = DS.Model.extend({ name: DS.attr(type) }); testStore.load(Model, { id: 1, name: provided }); testStore.load(Model, { id: 2 }); var record = testStore.find(Model, 1); deepEqual(get(record, 'name'), expected, type + " coerces " + provided + " to " + expected); // See: Github issue #421 // record = testStore.find(Model, 2); // set(record, 'name', provided); // deepEqual(get(record, 'name'), expected, type + " coerces " + provided + " to " + expected); }; var convertsFromServer = function(type, provided, expected) { var testStore = DS.Store.create(); var Model = DS.Model.extend({ name: DS.attr(type) }); testStore.load(Model, { id: 1, name: provided }); var record = testStore.find(Model, 1); deepEqual(get(record, 'name'), expected, type + " coerces " + provided + " to " + expected); }; var convertsWhenSet = function(type, provided, expected) { var testStore = DS.Store.create(); var Model = DS.Model.extend({ name: DS.attr(type) }); testStore.load(Model, { id: 2 }); var record = testStore.find(Model, 2); set(record, 'name', provided); deepEqual(record.serialize().name, expected, type + " saves " + provided + " as " + expected); }; test("a DS.Model can describe String attributes", function() { converts('string', "Scumbag Tom", "Scumbag Tom"); converts('string', 1, "1"); converts('string', "", ""); converts('string', null, null); converts('string', undefined, null); convertsFromServer('string', undefined, null); }); test("a DS.Model can describe Number attributes", function() { converts('number', "1", 1); converts('number', "0", 0); converts('number', 1, 1); converts('number', 0, 0); converts('number', "", null); converts('number', null, null); converts('number', undefined, null); converts('number', true, 1); converts('number', false, 0); }); test("a DS.Model can describe Boolean attributes", function() { converts('boolean', "1", true); converts('boolean', "", false); converts('boolean', 1, true); converts('boolean', 0, false); converts('boolean', null, false); converts('boolean', true, true); converts('boolean', false, false); }); test("a DS.Model can describe Date attributes", function() { converts('date', null, null); converts('date', undefined, undefined); var dateString = "Sat, 31 Dec 2011 00:08:16 GMT"; var date = new Date(dateString); var store = DS.Store.create(); var Person = DS.Model.extend({ updatedAt: DS.attr('date') }); store.load(Person, { id: 1 }); var record = store.find(Person, 1); record.set('updatedAt', date); deepEqual(date, get(record, 'updatedAt'), "setting a date returns the same date"); convertsFromServer('date', dateString, date); convertsWhenSet('date', date, dateString); }); test("don't allow setting", function(){ var store = DS.Store.create(); var Person = DS.Model.extend(); var record = store.createRecord(Person); raises(function(){ record.set('isLoaded', true); }, "raised error when trying to set an unsettable record"); }); test("ensure model exits loading state, materializes data and fulfills promise only after data is available", function () { expect(7); var store = DS.Store.create({ adapter: DS.Adapter.create({ find: Ember.K }) }); var person = store.find(Person, 1); equal(get(person, 'stateManager.currentState.path'), 'rootState.loading', 'model is in loading state'); equal(get(person, 'isLoaded'), false, 'model is not loaded'); equal(get(person, '_deferred.promise.isFulfilled'), undefined, 'model is not fulfilled'); get(person, 'name'); //trigger data setup equal(get(person, 'stateManager.currentState.path'), 'rootState.loading', 'model is still in loading state'); store.load(Person, { id: 1, name: "John", isDrugAddict: false }); equal(get(person, 'stateManager.currentState.path'), 'rootState.loaded.saved', 'model is in loaded state'); equal(get(person, 'isLoaded'), true, 'model is loaded'); equal(get(person, '_deferred.promise.isFulfilled'), true, 'model is fulfilled'); });
{ "content_hash": "13d48930b9221349e3c141f55d955119", "timestamp": "", "source": "github", "line_count": 387, "max_line_length": 123, "avg_line_length": 29.521963824289404, "alnum_prop": 0.6467396061269146, "repo_name": "kagemusha/data", "id": "9a3280e93b22d1bad6459524f6679d95def2402d", "size": "11425", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/ember-data/tests/unit/model_test.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System; using System.Threading.Tasks; using Deveel.Data.Serialization; using Xunit; namespace Deveel.Data.Sql.Expressions { public static class SqlGroupExpressionTests { [Fact] public static async Task ReduceGroup() { var exp = SqlExpression.Binary(SqlExpressionType.Equal, SqlExpression.Constant(SqlObject.Boolean(true)), SqlExpression.Constant(SqlObject.Boolean(false))); var group = SqlExpression.Group(exp); var reduced = await group.ReduceAsync(null); Assert.NotNull(reduced); Assert.IsType<SqlConstantExpression>(reduced); Assert.IsType<SqlObject>(((SqlConstantExpression)reduced).Value); } [Fact] public static void GetGroupString() { var exp = SqlExpression.Binary(SqlExpressionType.Equal, SqlExpression.Constant(SqlObject.Integer(33)), SqlExpression.Constant(SqlObject.Integer(54))); var group = SqlExpression.Group(exp); const string expected = "(33 = 54)"; var sql = group.ToString(); Assert.Equal(expected, sql); } [Fact] public static void SerializeGroup() { var exp = SqlExpression.Binary(SqlExpressionType.Equal, SqlExpression.Constant(SqlObject.Integer(33)), SqlExpression.Constant(SqlObject.Integer(54))); var group = SqlExpression.Group(exp); var result = BinarySerializeUtil.Serialize(group); Assert.NotNull(result); Assert.IsType<SqlBinaryExpression>(result.Expression); } [Theory] [InlineData("(674)", SqlExpressionType.Constant)] [InlineData("((a + b))", SqlExpressionType.Group)] public static void ParseString(string s, SqlExpressionType innerType) { var exp = SqlExpression.Parse(s); Assert.NotNull(exp); Assert.IsType<SqlGroupExpression>(exp); var group = (SqlGroupExpression) exp; Assert.NotNull(group.Expression); Assert.Equal(innerType, group.Expression.ExpressionType); } } }
{ "content_hash": "a59a4e7a1258706c36db3887e7d4bd3b", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 73, "avg_line_length": 28.84375, "alnum_prop": 0.7351029252437703, "repo_name": "deveel/deveeldb.core", "id": "22edbcb4ea055989afce44f12de6447f02f6ede8", "size": "1848", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/DeveelDb.Core.Tests/Data/Sql/Expressions/SqlGroupExpressionTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "38869" }, { "name": "Batchfile", "bytes": "104" }, { "name": "C#", "bytes": "1162288" }, { "name": "PowerShell", "bytes": "102" }, { "name": "Shell", "bytes": "543" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" /> <title>Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../assets/css/default.css" rel="stylesheet" type="text/css"> <!-- JAVASCRIPT --> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script src="../../../assets/js/android_3p-bundle.js" type="text/javascript"></script> <script type="text/javascript"> var toRoot = "../../../"; var devsite = false; </script> <script src="../../../assets/js/docs.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5831155-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body class="gc-documentation develop guide" itemscope itemtype="http://schema.org/Article"> <a name="top"></a> <!-- Header --> <div id="header"> <div class="wrap" id="header-wrap"> <div class="col-3 logo"> <a href="../../../index.html"> <img src="../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" /> </a> <div class="btn-quicknav" id="btn-quicknav"> <a href="#" class="arrow-inactive">Quicknav</a> <a href="#" class="arrow-active">Quicknav</a> </div> </div> <ul class="nav-x col-9"> <li class="design"> <a href="../../../design/index.html" zh-tw-lang="設計" zh-cn-lang="设计" ru-lang="Проектирование" ko-lang="디자인" ja-lang="設計" es-lang="Diseñar" >Design</a></li> <li class="develop"><a href="../../../develop/index.html" zh-tw-lang="開發" zh-cn-lang="开发" ru-lang="Разработка" ko-lang="개발" ja-lang="開発" es-lang="Desarrollar" >Develop</a></li> <li class="distribute last"><a href="../../../distribute/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir" >Distribute</a></li> </ul> <!-- New Search --> <div class="menu-container"> <div class="moremenu"> <div id="more-btn"></div> </div> <div class="morehover" id="moremenu"> <div class="top"></div> <div class="mid"> <div class="header">Links</div> <ul> <li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li> <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li> <li><a href="../../../about/index.html">About Android</a></li> </ul> <div class="header">Android Sites</div> <ul> <li><a href="http://www.android.com">Android.com</a></li> <li class="active"><a>Android Developers</a></li> <li><a href="http://source.android.com">Android Open Source Project</a></li> </ul> <br class="clearfix" /> </div> <div class="bottom"></div> </div> <div class="search" id="search-container"> <div class="search-inner"> <div id="search-btn"></div> <div class="left"></div> <form onsubmit="return submit_search()"> <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q" onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../')" onkeyup="return search_changed(event, false, '../../../')" /> </form> <div class="right"></div> <a class="close hide">close</a> <div class="left"></div> <div class="right"></div> </div> </div> <div class="search_filtered_wrapper reference"> <div class="suggest-card reference no-display"> <ul class="search_filtered"> </ul> </div> </div> <div class="search_filtered_wrapper docs"> <div class="suggest-card dummy no-display">&nbsp;</div> <div class="suggest-card develop no-display"> <ul class="search_filtered"> </ul> <div class="child-card guides no-display"> </div> <div class="child-card training no-display"> </div> </div> <div class="suggest-card design no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card distribute no-display"> <ul class="search_filtered"> </ul> </div> </div> </div> <!-- /New Search> <!-- Expanded quicknav --> <div id="quicknav" class="col-9"> <ul> <li class="design"> <ul> <li><a href="../../../design/index.html">Get Started</a></li> <li><a href="../../../design/style/index.html">Style</a></li> <li><a href="../../../design/patterns/index.html">Patterns</a></li> <li><a href="../../../design/building-blocks/index.html">Building Blocks</a></li> <li><a href="../../../design/downloads/index.html">Downloads</a></li> <li><a href="../../../design/videos/index.html">Videos</a></li> </ul> </li> <li class="develop"> <ul> <li><a href="../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li><a href="../../../guide/components/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li><a href="../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li><a href="../../../tools/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a> <ul><li><a href="../../../sdk/index.html">Get the SDK</a></li></ul> </li> <li><a href="../../../google/index.html">Google Services</a> </li> </ul> </li> <li class="distribute last"> <ul> <li><a href="../../../distribute/index.html">Google Play</a></li> <li><a href="../../../distribute/googleplay/publish/index.html">Publishing</a></li> <li><a href="../../../distribute/googleplay/promote/index.html">Promoting</a></li> <li><a href="../../../distribute/googleplay/quality/index.html">App Quality</a></li> <li><a href="../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li> <li><a href="../../../distribute/open.html">Open Distribution</a></li> </ul> </li> </ul> </div> <!-- /Expanded quicknav --> </div> </div> <!-- /Header --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> <!-- Secondary x-nav --> <div id="nav-x"> <div class="wrap"> <ul class="nav-x col-9 develop" style="width:100%"> <li class="training"><a href="../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li class="guide"><a href="../../../guide/components/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li class="reference"><a href="../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li class="tools"><a href="../../../tools/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a></li> <li class="google"><a href="../../../google/index.html" >Google Services</a> </li> </ul> </div> </div> <!-- /Sendondary x-nav --> <div class="wrap clearfix" id="body-content"> <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav" class="scroll-pane"> <a class="totop" href="#top" data-g-event="left-nav-top">to top</a> <ul id="nav"> <!-- Walkthrough for Developers -- quick overview of what it's like to develop on Android --> <!--<li style="color:red">Overview</li> --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/components/index.html"> <span class="en">App Components</span> </a></div> <ul> <li><a href="../../../guide/components/fundamentals.html"> <span class="en">App Fundamentals</span></a> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/components/activities.html"> <span class="en">Activities</span> </a></div> <ul> <li><a href="../../../guide/components/fragments.html"> <span class="en">Fragments</span> </a></li> <li><a href="../../../guide/components/loaders.html"> <span class="en">Loaders</span> </a></li> <li><a href="../../../guide/components/tasks-and-back-stack.html"> <span class="en">Tasks and Back Stack</span> </a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/components/services.html"> <span class="en">Services</span> </a></div> <ul> <li><a href="../../../guide/components/bound-services.html"> <span class="en">Bound Services</span> </a></li> <li><a href="../../../guide/components/aidl.html"> <span class="en">AIDL</span> </a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/providers/content-providers.html"> <span class="en">Content Providers</span> </a></div> <ul> <li><a href="../../../guide/topics/providers/content-provider-basics.html"> <span class="en">Content Provider Basics</span> </a></li> <li><a href="../../../guide/topics/providers/content-provider-creating.html"> <span class="en">Creating a Content Provider</span> </a></li> <li><a href="../../../guide/topics/providers/calendar-provider.html"> <span class="en">Calendar Provider</span> </a></li> <li><a href="../../../guide/topics/providers/contacts-provider.html"> <span class="en">Contacts Provider</span> </a></li> <li><a href="../../../guide/topics/providers/document-provider.html"> <span class="en">Storage Access Framework</span> </a></li> </ul> </li> <li><a href="../../../guide/components/intents-filters.html"> <span class="en">Intents and Intent Filters</span> </a></li> <li><a href="../../../guide/components/processes-and-threads.html"> <span class="en">Processes and Threads</span> </a> </li> <li><a href="../../../guide/topics/security/permissions.html"> <span class="en">Permissions</span> </a> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/appwidgets/index.html"> <span class="en">App Widgets</span> </a></div> <ul> <li><a href="../../../guide/topics/appwidgets/host.html"> <span class="en">App Widget Host</span> </a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/manifest/manifest-intro.html"> <span class="en">Android Manifest</span> </a></div> <ul> <li><a href="../../../guide/topics/manifest/action-element.html">&lt;action&gt;</a></li> <li><a href="../../../guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li> <li><a href="../../../guide/topics/manifest/activity-alias-element.html">&lt;activity-alias&gt;</a></li> <li><a href="../../../guide/topics/manifest/application-element.html">&lt;application&gt;</a></li> <li><a href="../../../guide/topics/manifest/category-element.html">&lt;category&gt;</a></li> <li><a href="../../../guide/topics/manifest/compatible-screens-element.html">&lt;compatible-screens&gt;</a></li> <li><a href="../../../guide/topics/manifest/data-element.html">&lt;data&gt;</a></li> <li><a href="../../../guide/topics/manifest/grant-uri-permission-element.html">&lt;grant-uri-permission&gt;</a></li> <li><a href="../../../guide/topics/manifest/instrumentation-element.html">&lt;instrumentation&gt;</a></li> <li><a href="../../../guide/topics/manifest/intent-filter-element.html">&lt;intent-filter&gt;</a></li> <li><a href="../../../guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></li> <li><a href="../../../guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a></li> <li><a href="../../../guide/topics/manifest/path-permission-element.html">&lt;path-permission&gt;</a></li> <li><a href="../../../guide/topics/manifest/permission-element.html">&lt;permission&gt;</a></li> <li><a href="../../../guide/topics/manifest/permission-group-element.html">&lt;permission-group&gt;</a></li> <li><a href="../../../guide/topics/manifest/permission-tree-element.html">&lt;permission-tree&gt;</a></li> <li><a href="../../../guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></li> <li><a href="../../../guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li> <li><a href="../../../guide/topics/manifest/service-element.html">&lt;service&gt;</a></li> <li><a href="../../../guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;</a></li> <li><a href="../../../guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li><!-- ##api level 4## --> <li><a href="../../../guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li> <li><a href="../../../guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## --> <li><a href="../../../guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li> <li><a href="../../../guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li> <li><a href="../../../guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li> </ul> </li><!-- end of the manifest file --> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/ui/index.html"> <span class="en">User Interface</span> </a></div> <ul> <li><a href="../../../guide/topics/ui/overview.html"> <span class="en">Overview</span> </a></li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/ui/declaring-layout.html"> <span class="en">Layouts</span> </a></div> <ul> <li><a href="../../../guide/topics/ui/layout/linear.html"> <span class="en">Linear Layout</span> </a></li> <li><a href="../../../guide/topics/ui/layout/relative.html"> <span class="en">Relative Layout</span> </a></li> <!-- <li><a href="../../../guide/topics/ui/layout/grid.html"> <span class="en">Grid Layout</span> </a></li> --> <li><a href="../../../guide/topics/ui/layout/listview.html"> <span class="en">List View</span> </a></li> <li><a href="../../../guide/topics/ui/layout/gridview.html"> <span class="en">Grid View</span> </a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/ui/controls.html"> <span class="en">Input Controls</span> </a></div> <ul> <li><a href="../../../guide/topics/ui/controls/button.html"> <span class="en">Buttons</span> </a></li> <li><a href="../../../guide/topics/ui/controls/text.html"> <span class="en">Text Fields</span> </a></li> <li><a href="../../../guide/topics/ui/controls/checkbox.html"> <span class="en">Checkboxes</span> </a></li> <li><a href="../../../guide/topics/ui/controls/radiobutton.html"> <span class="en">Radio Buttons</span> </a></li> <li><a href="../../../guide/topics/ui/controls/togglebutton.html"> <span class="en">Toggle Buttons</span> </a></li> <li><a href="../../../guide/topics/ui/controls/spinner.html"> <span class="en">Spinners</span> </a></li> <li><a href="../../../guide/topics/ui/controls/pickers.html"> <span class="en">Pickers</span> </a></li> <!-- <li><a href="../../../guide/topics/ui/controls/progress.html"> <span class="en">Seek and Progress Bars</span> </a></li> --> </ul> </li> <li><a href="../../../guide/topics/ui/ui-events.html"> <span class="en">Input Events</span> </a></li> <li><a href="../../../guide/topics/ui/menus.html"> <span class="en">Menus</span></span> </a></li> <li><a href="../../../guide/topics/ui/actionbar.html"> <span class="en">Action Bar</span> </a></li> <li><a href="../../../guide/topics/ui/settings.html"> <span class="en">Settings</span> </a></li> <li><a href="../../../guide/topics/ui/dialogs.html"> <span class="en">Dialogs</span> </a></li> <li><a href="../../../guide/topics/ui/notifiers/notifications.html"> <span class="en">Notifications</span> </a></li> <li><a href="../../../guide/topics/ui/notifiers/toasts.html"> <span class="en">Toasts</span> </a></li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/search/index.html"> <span class="en">Search</span> </a></div> <ul> <li><a href="../../../guide/topics/search/search-dialog.html">Creating a Search Interface</a></li> <li><a href="../../../guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li> <li><a href="../../../guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li> <li><a href="../../../guide/topics/search/searchable-config.html">Searchable Configuration</a></li> </ul> </li> <li><a href="../../../guide/topics/ui/drag-drop.html"> <span class="en">Drag and Drop</span> </a></li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/ui/accessibility/index.html"> <span class="en">Accessibility</span> </a></div> <ul> <li><a href="../../../guide/topics/ui/accessibility/apps.html"> <span class="en">Making Applications Accessible</span> </a></li> <li><a href="../../../guide/topics/ui/accessibility/checklist.html"> <span class="en">Accessibility Developer Checklist</span> </a></li> <li><a href="../../../guide/topics/ui/accessibility/services.html"> <span class="en">Building Accessibility Services</span> </a></li> </ul> </li> <li><a href="../../../guide/topics/ui/themes.html"> <span class="en">Styles and Themes</span> </a></li> <li><a href="../../../guide/topics/ui/custom-components.html"> <span class="en">Custom Components</span> </a></li> </ul> </li><!-- end of User Interface --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/resources/index.html"> <span class="en">App Resources</span> </a></div> <ul> <li><a href="../../../guide/topics/resources/overview.html"> <span class="en">Overview</span> </a></li> <li><a href="../../../guide/topics/resources/providing-resources.html"> <span class="en">Providing Resources</span> </a></li> <li><a href="../../../guide/topics/resources/accessing-resources.html"> <span class="en">Accessing Resources</span> </a></li> <li><a href="../../../guide/topics/resources/runtime-changes.html"> <span class="en">Handling Runtime Changes</span> </a></li> <li><a href="../../../guide/topics/resources/localization.html"> <span class="en">Localization</span> </a></li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/resources/available-resources.html"> <span class="en">Resource Types</span> </a></div> <ul> <li><a href="../../../guide/topics/resources/animation-resource.html">Animation</a></li> <li><a href="../../../guide/topics/resources/color-list-resource.html">Color State List</a></li> <li><a href="../../../guide/topics/resources/drawable-resource.html">Drawable</a></li> <li><a href="../../../guide/topics/resources/layout-resource.html">Layout</a></li> <li><a href="../../../guide/topics/resources/menu-resource.html">Menu</a></li> <li><a href="../../../guide/topics/resources/string-resource.html">String</a></li> <li><a href="../../../guide/topics/resources/style-resource.html">Style</a></li> <li><a href="../../../guide/topics/resources/more-resources.html">More Types</a></li> </ul> </li><!-- end of resource types --> </ul> </li><!-- end of app resources --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/graphics/index.html"> <span class="en">Animation and Graphics</span> </a></div> <ul> <li class="nav-section"> <li><a href="../../../guide/topics/graphics/overview.html"> <span class="en">Overview</span> </a></li> <li><a href="../../../guide/topics/graphics/prop-animation.html"> <span class="en">Property Animation</span> </a></li> <li><a href="../../../guide/topics/graphics/view-animation.html"> <span class="en">View Animation</span> </a></li> <li><a href="../../../guide/topics/graphics/drawable-animation.html"> <span class="en">Drawable Animation</span> </a></li> <li><a href="../../../guide/topics/graphics/2d-graphics.html"> <span class="en">Canvas and Drawables</span> </a></li> <li><a href="../../../guide/topics/graphics/opengl.html"> <span class="en">OpenGL ES</span> </a></li> <li><a href="../../../guide/topics/graphics/hardware-accel.html"> <span class="en">Hardware Acceleration</span> </a></li> </ul> </li><!-- end of graphics and animation--> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/renderscript/index.html"> <span class="en">Computation</span> </a></div> <ul> <li><a href="../../../guide/topics/renderscript/compute.html"> <span class="en">RenderScript</span></a> </li> <li><a href="../../../guide/topics/renderscript/advanced.html"> <span class="en">Advanced RenderScript</span></a> </li> <li><a href="../../../guide/topics/renderscript/reference.html"> <span class="en">Runtime API Reference</span></a> </li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/media/index.html"> <span class="en">Media and Camera</span> </a></div> <ul> <li><a href="../../../guide/topics/media/mediaplayer.html"> <span class="en">Media Playback</span></a> </li> <li><a href="../../../guide/appendix/media-formats.html"> <span class="en">Supported Media Formats</span></a> </li> <li><a href="../../../guide/topics/media/audio-capture.html"> <span class="en">Audio Capture</span></a> </li> <li><a href="../../../guide/topics/media/jetplayer.html"> <span class="en">JetPlayer</span></a> </li> <li><a href="../../../guide/topics/media/camera.html"> <span class="en">Camera</span></a> </li> </ul> </li><!-- end of media and camera --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/sensors/index.html"> <span class="en">Location and Sensors</span> </a></div> <ul> <li><a href="../../../guide/topics/location/index.html"> <span class="en">Location and Maps</span> </a> <li><a href="../../../guide/topics/location/strategies.html"> <span class="en">Location Strategies</span> </a></li> <li><a href="../../../guide/topics/sensors/sensors_overview.html"> <span class="en">Sensors Overview</span> </a></li> <li><a href="../../../guide/topics/sensors/sensors_motion.html"> <span class="en">Motion Sensors</span> </a></li> <li><a href="../../../guide/topics/sensors/sensors_position.html"> <span class="en">Position Sensors</span> </a></li> <li><a href="../../../guide/topics/sensors/sensors_environment.html"> <span class="en">Environment Sensors</span> </a></li> </ul> </li><!-- end of location and sensors --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/connectivity/index.html"> <span class="en">Connectivity</span> </a></div> <ul> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/connectivity/bluetooth.html"> <span class="en">Bluetooth</span></a> </div> <ul> <li><a href="../../../guide/topics/connectivity/bluetooth-le.html">Bluetooth Low Energy</a></li> </ul> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/connectivity/nfc/index.html"> <span class="en">NFC</span></a> </div> <ul> <li><a href="../../../guide/topics/connectivity/nfc/nfc.html">NFC Basics</a></li> <li><a href="../../../guide/topics/connectivity/nfc/advanced-nfc.html">Advanced NFC</a></li> <li><a href="../../../guide/topics/connectivity/nfc/hce.html">Host-based Card Emulation</a></li> </ul> </li> <li><a href="../../../guide/topics/connectivity/wifip2p.html"> <span class="en">Wi-Fi P2P</span></a> </li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/connectivity/usb/index.html"> <span class="en">USB</span></a> </div> <ul> <li><a href="../../../guide/topics/connectivity/usb/accessory.html">Accessory</a></li> <li><a href="../../../guide/topics/connectivity/usb/host.html">Host</a></li> </ul> </li> <li><a href="../../../guide/topics/connectivity/sip.html"> <span class="en">SIP</span> </a> </li> </ul> </li><!-- end of connectivity --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/text/index.html"> <span class="en">Text and Input</span> </a></div> <ul> <li><a href="../../../guide/topics/text/copy-paste.html"> <span class="en">Copy and Paste</span> </a></li> <li><a href="../../../guide/topics/text/creating-input-method.html"> <span class="en">Creating an IME</span> </a></li> <li><a href="../../../guide/topics/text/spell-checker-framework.html"> <span class="en">Spelling Checker</span> </a></li> </ul> </li><!-- end of text and input --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/data/index.html"> <span class="en">Data Storage</span> </a></div> <ul> <li><a href="../../../guide/topics/data/data-storage.html"> <span class="en">Storage Options</span> </a></li> <li><a href="../../../guide/topics/data/backup.html"> <span class="en">Data Backup</span> </a></li> <li><a href="../../../guide/topics/data/install-location.html"> <span class="en">App Install Location</span> </a></li> </ul> </li><!-- end of data storage --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/topics/admin/index.html"> <span class="en">Administration</span> </a></div> <ul> <li> <a href="../../../guide/topics/admin/device-admin.html"> <span class="en">Device Policies</span></a> </li> <!-- <li> <a href="../../../guide/topics/admin/keychain.html"> <span class="en">Certificate Store</span></a> </li> --> </ul> </li><!-- end of administration --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/webapps/index.html"> <span class="en">Web Apps</span> </a></div> <ul> <li><a href="../../../guide/webapps/overview.html"> <span class="en">Overview</span> </a></li> <li><a href="../../../guide/webapps/targeting.html"> <span class="en">Targeting Screens from Web Apps</span> </a></li> <li><a href="../../../guide/webapps/webview.html"> <span class="en">Building Web Apps in WebView</span> </a></li> <li><a href="../../../guide/webapps/migrating.html"> <span class="en">Migrating to WebView in Android 4.4</span> </a></li> <li><a href="../../../guide/webapps/debugging.html"> <span class="en">Debugging Web Apps</span> </a></li> <li><a href="../../../guide/webapps/best-practices.html"> <span class="en">Best Practices for Web Apps</span> </a></li> </ul> </li><!-- end of web apps --> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/practices/index.html"> <span class="en">Best Practices</span> <span class="de" style="display:none">Bewährte Verfahren</span> <span class="es" style="display:none">Prácticas recomendadas</span> <span class="fr" style="display:none">Meilleures pratiques</span> <span class="it" style="display:none">Best practice</span> <span class="ja" style="display:none">ベスト プラクティス</span> <span class="zh-cn" style="display:none">最佳实践</span> <span class="zh-tw" style="display:none">最佳實務</span> </div></a> <ul> <li><a href="../../../guide/practices/compatibility.html"> <span class="en">Compatibility</span> </a></li> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/practices/screens_support.html"> <span class="en">Supporting Multiple Screens</span> </a></div> <ul> <li><a href="../../../guide/practices/screens-distribution.html"> <span class="en">Distributing to Specific Screens</span> </a></li> <li><a href="../../../guide/practices/screen-compat-mode.html"> <span class="en">Screen Compatibility Mode</span> </a></li> </ul> </li> <li><a href="../../../guide/practices/tablets-and-handsets.html"> <span class="en">Supporting Tablets and Handsets</span> </a></li> </ul> </li> <!-- this needs to move <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/practices/ui_guidelines/index.html"> <span class="en">UI Guidelines</span> </a></div> <ul> <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/practices/ui_guidelines/icon_design.html"> <span class="en">Icon Design</span> </a></div> <ul> <li><a href="../../../guide/practices/ui_guidelines/icon_design_launcher.html"> <span class="en">Launcher Icons</span> </a></li> <li><a href="../../../guide/practices/ui_guidelines/icon_design_menu.html"> <span class="en">Menu Icons</span> </a></li> <li><a href="../../../guide/practices/ui_guidelines/icon_design_action_bar.html"> <span class="en">Action Bar Icons</span> </a></li> <li><a href="../../../guide/practices/ui_guidelines/icon_design_status_bar.html"> <span class="en">Status Bar Icons</span> </a></li> <li><a href="../../../guide/practices/ui_guidelines/icon_design_tab.html"> <span class="en">Tab Icons</span> </a></li> <li><a href="../../../guide/practices/ui_guidelines/icon_design_dialog.html"> <span class="en">Dialog Icons</span> </a></li> <li><a href="../../../guide/practices/ui_guidelines/icon_design_list.html"> <span class="en">List View Icons</span> </a></li> </ul> </li> <li><div><a href="../../../guide/practices/ui_guidelines/widget_design.html"> <span class="en">App Widget Design</span> </a></div> </li> </ul> </li> </ul> --> <!-- Remove <li class="nav-section"> <div class="nav-section-header"><a href="../../../guide/appendix/index.html"> <span class="en">Appendix</span> <span class="de" style="display:none">Anhang</span> <span class="es" style="display:none">Apéndice</span> <span class="fr" style="display:none">Annexes</span> <span class="it" style="display:none">Appendice</span> <span class="ja" style="display:none">付録</span> <span class="zh-cn" style="display:none">附录</span> <span class="zh-tw" style="display:none">附錄</span> </a></div> <ul> <li><a href="../../../guide/appendix/g-app-intents.html"> <span class="en">Intents List: Google Apps</span> </a></li> <li><a href="../../../guide/appendix/glossary.html"> <span class="en">Glossary</span> </a></li> </ul> </li> </li> --> </ul> <script type="text/javascript"> <!-- buildToggleLists(); changeNavLang(getLangPref()); //--> </script> </div> </div> <!-- end side-nav --> <script> $(document).ready(function() { scrollIntoView("devdoc-nav"); }); </script> <div class="col-12" id="doc-col" > <h1 itemprop="name" ></h1> <div id="jd-content"> <div class="jd-descr" itemprop="articleBody"> <script type="text/javascript"> document.location=toRoot+"resources/faq/index.html" </script> <p>You should have already been redirected by your browser. Please follow <a href="../../../resources/faq/index.html">this link</a>.</p> </div> <div class="content-footer layout-content-row" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div class="layout-content-col col-8" style="padding-top:4px"> <div class="g-plusone" data-size="medium"></div> </div> <div class="paging-links layout-content-col col-4"> </div> </div> </div> <!-- end jd-content --> <div id="footer" class="wrap" > <div id="copyright"> Except as noted, this content is licensed under <a href="http://creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>. For details and restrictions, see the <a href="../../../license.html">Content License</a>. </div> <div id="footerlinks"> <p> <a href="../../../about/index.html">About Android</a>&nbsp;&nbsp;|&nbsp; <a href="../../../legal.html">Legal</a>&nbsp;&nbsp;|&nbsp; <a href="../../../support.html">Support</a> </p> </div> </div> <!-- end footer --> </div><!-- end doc-content --> </div> <!-- end body-content --> </body> </html>
{ "content_hash": "cbc31ec2bc577e5367541c0e71b26a3b", "timestamp": "", "source": "github", "line_count": 1090, "max_line_length": 142, "avg_line_length": 37.85045871559633, "alnum_prop": 0.49380711152046924, "repo_name": "terrytowne/android-developer-cn", "id": "bbfdec4e1a4ece5c87e63177e09e8db6b3c09b4f", "size": "41682", "binary": false, "copies": "2", "ref": "refs/heads/4.4.zh_cn", "path": "guide/appendix/faq/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "225261" }, { "name": "JavaScript", "bytes": "218708" } ], "symlink_target": "" }
<?php namespace Drupal\file\Upload; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\File\Event\FileUploadSanitizeNameEvent; use Drupal\Core\File\Exception\FileExistsException; use Drupal\Core\File\Exception\FileWriteException; use Drupal\Core\File\Exception\InvalidStreamWrapperException; use Drupal\Core\File\FileSystemInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface; use Drupal\file\Entity\File; use Drupal\file\FileInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException; use Symfony\Component\HttpFoundation\File\Exception\ExtensionFileException; use Symfony\Component\HttpFoundation\File\Exception\FileException; use Symfony\Component\HttpFoundation\File\Exception\FormSizeFileException; use Symfony\Component\HttpFoundation\File\Exception\IniSizeFileException; use Symfony\Component\HttpFoundation\File\Exception\NoFileException; use Symfony\Component\HttpFoundation\File\Exception\NoTmpDirFileException; use Symfony\Component\HttpFoundation\File\Exception\PartialFileException; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\Mime\MimeTypeGuesserInterface; /** * Handles validating and creating file entities from file uploads. */ class FileUploadHandler { /** * The default extensions if none are provided. */ const DEFAULT_EXTENSIONS = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp'; /** * The file system service. * * @var \Drupal\Core\File\FileSystemInterface */ protected $fileSystem; /** * The entity type manager. * * @var \Drupal\Core\Entity\EntityTypeManagerInterface */ protected $entityTypeManager; /** * The stream wrapper manager. * * @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface */ protected $streamWrapperManager; /** * The event dispatcher. * * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ protected $eventDispatcher; /** * The current user. * * @var \Drupal\Core\Session\AccountInterface */ protected $currentUser; /** * The MIME type guesser. * * @var \Symfony\Component\Mime\MimeTypeGuesserInterface */ protected $mimeTypeGuesser; /** * The request stack. * * @var \Symfony\Component\HttpFoundation\RequestStack */ protected $requestStack; /** * Constructs a FileUploadHandler object. * * @param \Drupal\Core\File\FileSystemInterface $fileSystem * The file system service. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager * The entity type manager. * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $streamWrapperManager * The stream wrapper manager. * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher * The event dispatcher. * @param \Symfony\Component\Mime\MimeTypeGuesserInterface $mimeTypeGuesser * The MIME type guesser. * @param \Drupal\Core\Session\AccountInterface $currentUser * The current user. * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack * The request stack. */ public function __construct(FileSystemInterface $fileSystem, EntityTypeManagerInterface $entityTypeManager, StreamWrapperManagerInterface $streamWrapperManager, EventDispatcherInterface $eventDispatcher, MimeTypeGuesserInterface $mimeTypeGuesser, AccountInterface $currentUser, RequestStack $requestStack) { $this->fileSystem = $fileSystem; $this->entityTypeManager = $entityTypeManager; $this->streamWrapperManager = $streamWrapperManager; $this->eventDispatcher = $eventDispatcher; $this->mimeTypeGuesser = $mimeTypeGuesser; $this->currentUser = $currentUser; $this->requestStack = $requestStack; } /** * Creates a file from an upload. * * @param \Drupal\file\Upload\UploadedFileInterface $uploadedFile * The uploaded file object. * @param array $validators * The validators to run against the uploaded file. * @param string $destination * The destination directory. * @param int $replace * Replace behavior when the destination file already exists: * - FileSystemInterface::EXISTS_REPLACE - Replace the existing file. * - FileSystemInterface::EXISTS_RENAME - Append _{incrementing number} * until the filename is unique. * - FileSystemInterface::EXISTS_ERROR - Throw an exception. * * @return \Drupal\file\Upload\FileUploadResult * The created file entity. * * @throws \Symfony\Component\HttpFoundation\File\Exception\FileException * Thrown when a file upload error occurred. * @throws \Drupal\Core\File\Exception\FileWriteException * Thrown when there is an error moving the file. * @throws \Drupal\Core\File\Exception\FileException * Thrown when a file system error occurs. * @throws \Drupal\file\Upload\FileValidationException * Thrown when file validation fails. */ public function handleFileUpload(UploadedFileInterface $uploadedFile, array $validators = [], string $destination = 'temporary://', int $replace = FileSystemInterface::EXISTS_REPLACE): FileUploadResult { $originalName = $uploadedFile->getClientOriginalName(); if (!$uploadedFile->isValid()) { switch ($uploadedFile->getError()) { case \UPLOAD_ERR_INI_SIZE: throw new IniSizeFileException($uploadedFile->getErrorMessage()); case \UPLOAD_ERR_FORM_SIZE: throw new FormSizeFileException($uploadedFile->getErrorMessage()); case \UPLOAD_ERR_PARTIAL: throw new PartialFileException($uploadedFile->getErrorMessage()); case \UPLOAD_ERR_NO_FILE: throw new NoFileException($uploadedFile->getErrorMessage()); case \UPLOAD_ERR_CANT_WRITE: throw new CannotWriteFileException($uploadedFile->getErrorMessage()); case \UPLOAD_ERR_NO_TMP_DIR: throw new NoTmpDirFileException($uploadedFile->getErrorMessage()); case \UPLOAD_ERR_EXTENSION: throw new ExtensionFileException($uploadedFile->getErrorMessage()); } throw new FileException($uploadedFile->getErrorMessage()); } $extensions = $this->handleExtensionValidation($validators); // Assert that the destination contains a valid stream. $destinationScheme = $this->streamWrapperManager::getScheme($destination); if (!$this->streamWrapperManager->isValidScheme($destinationScheme)) { throw new InvalidStreamWrapperException(sprintf('The file could not be uploaded because the destination "%s" is invalid.', $destination)); } // A file URI may already have a trailing slash or look like "public://". if (substr($destination, -1) != '/') { $destination .= '/'; } // Call an event to sanitize the filename and to attempt to address security // issues caused by common server setups. $event = new FileUploadSanitizeNameEvent($originalName, $extensions); $this->eventDispatcher->dispatch($event); $filename = $event->getFilename(); $mimeType = $this->mimeTypeGuesser->guessMimeType($filename); $destinationFilename = $this->fileSystem->getDestinationFilename($destination . $filename, $replace); if ($destinationFilename === FALSE) { throw new FileExistsException(sprintf('Destination file "%s" exists', $destinationFilename)); } $file = File::create([ 'uid' => $this->currentUser->id(), 'status' => 0, 'uri' => $uploadedFile->getRealPath(), ]); // This will be replaced later with a filename based on the destination. $file->setFilename($filename); $file->setMimeType($mimeType); $file->setSize($uploadedFile->getSize()); // Add in our check of the file name length. $validators['file_validate_name_length'] = []; // Call the validation functions specified by this function's caller. $errors = file_validate($file, $validators); if (!empty($errors)) { throw new FileValidationException('File validation failed', $filename, $errors); } $file->setFileUri($destinationFilename); if (!$this->moveUploadedFile($uploadedFile, $file->getFileUri())) { throw new FileWriteException('File upload error. Could not move uploaded file.'); } // Update the filename with any changes as a result of security or renaming // due to an existing file. $file->setFilename($this->fileSystem->basename($file->getFileUri())); if ($replace === FileSystemInterface::EXISTS_REPLACE) { $existingFile = $this->loadByUri($file->getFileUri()); if ($existingFile) { $file->fid = $existingFile->id(); $file->setOriginalId($existingFile->id()); } } $result = (new FileUploadResult()) ->setOriginalFilename($originalName) ->setSanitizedFilename($filename) ->setFile($file); // If the filename has been modified, let the user know. if ($event->isSecurityRename()) { $result->setSecurityRename(); } // Set the permissions on the new file. $this->fileSystem->chmod($file->getFileUri()); // We can now validate the file object itself before it's saved. $violations = $file->validate(); foreach ($violations as $violation) { $errors[] = $violation->getMessage(); } if (!empty($errors)) { throw new FileValidationException('File validation failed', $filename, $errors); } // If we made it this far it's safe to record this file in the database. $file->save(); // Allow an anonymous user who creates a non-public file to see it. See // \Drupal\file\FileAccessControlHandler::checkAccess(). if ($this->currentUser->isAnonymous() && $destinationScheme !== 'public') { $session = $this->requestStack->getCurrentRequest()->getSession(); $allowed_temp_files = $session->get('anonymous_allowed_file_ids', []); $allowed_temp_files[$file->id()] = $file->id(); $session->set('anonymous_allowed_file_ids', $allowed_temp_files); } return $result; } /** * Move the uploaded file from the temporary path to the destination. * * @todo Allows a sub-class to override this method in order to handle * raw file uploads in https://www.drupal.org/project/drupal/issues/2940383. * * @param \Drupal\file\Upload\UploadedFileInterface $uploadedFile * The uploaded file. * @param string $uri * The destination URI. * * @return bool * Returns FALSE if moving failed. * * @see https://www.drupal.org/project/drupal/issues/2940383 */ protected function moveUploadedFile(UploadedFileInterface $uploadedFile, string $uri) { return $this->fileSystem->moveUploadedFile($uploadedFile->getRealPath(), $uri); } /** * Gets the list of allowed extensions and updates the validators. * * This will add an extension validator to the list of validators if one is * not set. * * If the extension validator is set, but no extensions are specified, it * means all extensions are allowed, so the validator is removed from the list * of validators. * * @param array $validators * The file validators in use. * * @return string * The space delimited list of allowed file extensions. */ protected function handleExtensionValidation(array &$validators): string { // Build a list of allowed extensions. if (isset($validators['file_validate_extensions'])) { if (!isset($validators['file_validate_extensions'][0])) { // If 'file_validate_extensions' is set and the list is empty then the // caller wants to allow any extension. In this case we have to remove the // validator or else it will reject all extensions. unset($validators['file_validate_extensions']); } } else { // No validator was provided, so add one using the default list. // Build a default non-munged safe list for // \Drupal\system\EventSubscriber\SecurityFileUploadEventSubscriber::sanitizeName(). $validators['file_validate_extensions'] = [self::DEFAULT_EXTENSIONS]; } return $validators['file_validate_extensions'][0] ?? ''; } /** * Loads the first File entity found with the specified URI. * * @param string $uri * The file URI. * * @return \Drupal\file\FileInterface|null * The first file with the matched URI if found, NULL otherwise. * * @todo replace with https://www.drupal.org/project/drupal/issues/3223209 */ protected function loadByUri(string $uri): ?FileInterface { $fileStorage = $this->entityTypeManager->getStorage('file'); /** @var \Drupal\file\FileInterface[] $files */ $files = $fileStorage->loadByProperties(['uri' => $uri]); if (count($files)) { foreach ($files as $item) { // Since some database servers sometimes use a case-insensitive // comparison by default, double check that the filename is an exact // match. if ($item->getFileUri() === $uri) { return $item; } } } return NULL; } }
{ "content_hash": "08b3806236dda5100d2a473501f4482a", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 309, "avg_line_length": 37.03370786516854, "alnum_prop": 0.6983464805825242, "repo_name": "electric-eloquence/fepper-drupal", "id": "28d883d444766055046e8dec14f97036aa38c5bd", "size": "13184", "binary": false, "copies": "9", "ref": "refs/heads/dev", "path": "backend/drupal/core/modules/file/src/Upload/FileUploadHandler.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2300765" }, { "name": "HTML", "bytes": "68444" }, { "name": "JavaScript", "bytes": "2453602" }, { "name": "Mustache", "bytes": "40698" }, { "name": "PHP", "bytes": "41684915" }, { "name": "PowerShell", "bytes": "755" }, { "name": "Shell", "bytes": "72896" }, { "name": "Stylus", "bytes": "32803" }, { "name": "Twig", "bytes": "1820730" }, { "name": "VBScript", "bytes": "466" } ], "symlink_target": "" }
package org.apache.solr.search.facet; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.function.IntFunction; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.index.SortedNumericDocValues; import org.apache.lucene.index.SortedSetDocValues; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; import org.apache.solr.schema.SchemaField; /** * Accumulates stats separated by slot number for the fields with {@link * org.apache.lucene.index.DocValues} */ public abstract class DocValuesAcc extends SlotAcc { SchemaField sf; public DocValuesAcc(FacetContext fcontext, SchemaField sf) throws IOException { super(fcontext); this.sf = sf; } @Override public void collect(int doc, int slot, IntFunction<SlotContext> slotContext) throws IOException { if (advanceExact(doc)) { collectValues(doc, slot); } } protected abstract void collectValues(int doc, int slot) throws IOException; /** * Wrapper to {@code org.apache.lucene.index.DocValuesIterator#advanceExact(int)} returns whether * or not given {@code doc} has value */ protected abstract boolean advanceExact(int doc) throws IOException; /** Accumulator for {@link NumericDocValues} */ abstract static class NumericDVAcc extends DocValuesAcc { NumericDocValues values; public NumericDVAcc(FacetContext fcontext, SchemaField sf) throws IOException { super(fcontext, sf); } @Override public void setNextReader(LeafReaderContext readerContext) throws IOException { super.setNextReader(readerContext); values = DocValues.getNumeric(readerContext.reader(), sf.getName()); } @Override protected boolean advanceExact(int doc) throws IOException { return values.advanceExact(doc); } } /** Accumulator for {@link SortedNumericDocValues} */ abstract static class SortedNumericDVAcc extends DocValuesAcc { SortedNumericDocValues values; public SortedNumericDVAcc(FacetContext fcontext, SchemaField sf, int numSlots) throws IOException { super(fcontext, sf); } @Override public void setNextReader(LeafReaderContext readerContext) throws IOException { super.setNextReader(readerContext); values = DocValues.getSortedNumeric(readerContext.reader(), sf.getName()); } @Override protected boolean advanceExact(int doc) throws IOException { return values.advanceExact(doc); } } abstract static class LongSortedNumericDVAcc extends SortedNumericDVAcc { long[] result; long initialValue; public LongSortedNumericDVAcc( FacetContext fcontext, SchemaField sf, int numSlots, long initialValue) throws IOException { super(fcontext, sf, numSlots); this.result = new long[numSlots]; this.initialValue = initialValue; if (initialValue != 0) { Arrays.fill(result, initialValue); } } @Override public int compare(int slotA, int slotB) { return Long.compare(result[slotA], result[slotB]); } @Override public Object getValue(int slotNum) throws IOException { return result[slotNum]; } @Override public void reset() throws IOException { Arrays.fill(result, initialValue); } @Override public void resize(Resizer resizer) { this.result = resizer.resize(result, initialValue); } } abstract static class DoubleSortedNumericDVAcc extends SortedNumericDVAcc { double[] result; double initialValue; public DoubleSortedNumericDVAcc( FacetContext fcontext, SchemaField sf, int numSlots, double initialValue) throws IOException { super(fcontext, sf, numSlots); this.result = new double[numSlots]; this.initialValue = initialValue; if (initialValue != 0) { Arrays.fill(result, initialValue); } } @Override public int compare(int slotA, int slotB) { return Double.compare(result[slotA], result[slotB]); } @Override public Object getValue(int slotNum) throws IOException { return result[slotNum]; } @Override public void reset() throws IOException { Arrays.fill(result, initialValue); } @Override public void resize(Resizer resizer) { this.result = resizer.resize(result, initialValue); } /** converts given long value to double based on field type */ protected double getDouble(long val) { switch (sf.getType().getNumberType()) { case INTEGER: case LONG: case DATE: return val; case FLOAT: return NumericUtils.sortableIntToFloat((int) val); case DOUBLE: return NumericUtils.sortableLongToDouble(val); default: // this would never happen return 0.0d; } } } /** * Base class for standard deviation and variance computation for fields with {@link * SortedNumericDocValues} */ abstract static class SDVSortedNumericAcc extends DoubleSortedNumericDVAcc { int[] counts; double[] sum; public SDVSortedNumericAcc(FacetContext fcontext, SchemaField sf, int numSlots) throws IOException { super(fcontext, sf, numSlots, 0); this.counts = new int[numSlots]; this.sum = new double[numSlots]; } @Override protected void collectValues(int doc, int slot) throws IOException { for (int i = 0, count = values.docValueCount(); i < count; i++) { double val = getDouble(values.nextValue()); result[slot] += val * val; sum[slot] += val; counts[slot]++; } } protected abstract double computeVal(int slot); @Override public int compare(int slotA, int slotB) { return Double.compare(computeVal(slotA), computeVal(slotB)); } @Override public Object getValue(int slot) { if (fcontext.isShard()) { ArrayList<Number> lst = new ArrayList<>(3); lst.add(counts[slot]); lst.add(result[slot]); lst.add(sum[slot]); return lst; } else { return computeVal(slot); } } @Override public void reset() throws IOException { super.reset(); Arrays.fill(counts, 0); Arrays.fill(sum, 0); } @Override public void resize(Resizer resizer) { super.resize(resizer); this.counts = resizer.resize(counts, 0); this.sum = resizer.resize(sum, 0); } } /** Accumulator for {@link SortedDocValues} */ abstract static class SortedDVAcc extends DocValuesAcc { SortedDocValues values; public SortedDVAcc(FacetContext fcontext, SchemaField sf) throws IOException { super(fcontext, sf); } @Override public void setNextReader(LeafReaderContext readerContext) throws IOException { super.setNextReader(readerContext); values = DocValues.getSorted(readerContext.reader(), sf.getName()); } @Override protected boolean advanceExact(int doc) throws IOException { return values.advanceExact(doc); } } /** Accumulator for {@link SortedSetDocValues} */ abstract static class SortedSetDVAcc extends DocValuesAcc { SortedSetDocValues values; public SortedSetDVAcc(FacetContext fcontext, SchemaField sf, int numSlots) throws IOException { super(fcontext, sf); } @Override public void setNextReader(LeafReaderContext readerContext) throws IOException { super.setNextReader(readerContext); values = DocValues.getSortedSet(readerContext.reader(), sf.getName()); } @Override protected boolean advanceExact(int doc) throws IOException { return values.advanceExact(doc); } } abstract static class LongSortedSetDVAcc extends SortedSetDVAcc { long[] result; long initialValue; public LongSortedSetDVAcc( FacetContext fcontext, SchemaField sf, int numSlots, long initialValue) throws IOException { super(fcontext, sf, numSlots); result = new long[numSlots]; this.initialValue = initialValue; if (initialValue != 0) { Arrays.fill(result, initialValue); } } @Override public int compare(int slotA, int slotB) { return Long.compare(result[slotA], result[slotB]); } @Override public Object getValue(int slotNum) throws IOException { return result[slotNum]; } @Override public void reset() throws IOException { Arrays.fill(result, initialValue); } @Override public void resize(Resizer resizer) { this.result = resizer.resize(result, initialValue); } } abstract static class DoubleSortedSetDVAcc extends SortedSetDVAcc { double[] result; double initialValue; public DoubleSortedSetDVAcc( FacetContext fcontext, SchemaField sf, int numSlots, double initialValue) throws IOException { super(fcontext, sf, numSlots); result = new double[numSlots]; this.initialValue = initialValue; if (initialValue != 0) { Arrays.fill(result, initialValue); } } @Override public int compare(int slotA, int slotB) { return Double.compare(result[slotA], result[slotB]); } @Override public Object getValue(int slotNum) throws IOException { return result[slotNum]; } @Override public void reset() throws IOException { Arrays.fill(result, initialValue); } @Override public void resize(Resizer resizer) { this.result = resizer.resize(result, initialValue); } } /** * Base class for standard deviation and variance computation for fields with {@link * SortedSetDocValues} */ abstract static class SDVSortedSetAcc extends DoubleSortedSetDVAcc { int[] counts; double[] sum; public SDVSortedSetAcc(FacetContext fcontext, SchemaField sf, int numSlots) throws IOException { super(fcontext, sf, numSlots, 0); this.counts = new int[numSlots]; this.sum = new double[numSlots]; } @Override protected void collectValues(int doc, int slot) throws IOException { long ord; while ((ord = values.nextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { BytesRef term = values.lookupOrd(ord); Object obj = sf.getType().toObject(sf, term); double val = obj instanceof Date ? ((Date) obj).getTime() : ((Number) obj).doubleValue(); result[slot] += val * val; sum[slot] += val; counts[slot]++; } } protected abstract double computeVal(int slot); @Override public int compare(int slotA, int slotB) { return Double.compare(computeVal(slotA), computeVal(slotB)); } @Override public Object getValue(int slot) { if (fcontext.isShard()) { ArrayList<Number> lst = new ArrayList<>(3); lst.add(counts[slot]); lst.add(result[slot]); lst.add(sum[slot]); return lst; } else { return computeVal(slot); } } @Override public void reset() throws IOException { super.reset(); Arrays.fill(counts, 0); Arrays.fill(sum, 0); } @Override public void resize(Resizer resizer) { super.resize(resizer); this.counts = resizer.resize(counts, 0); this.sum = resizer.resize(sum, 0); } } }
{ "content_hash": "1650a58f4b4deedb38d04f5a08252cbd", "timestamp": "", "source": "github", "line_count": 408, "max_line_length": 100, "avg_line_length": 28.235294117647058, "alnum_prop": 0.6685763888888889, "repo_name": "apache/solr", "id": "fddfcf92118284ff9bec568ceb0b6d9aed552f7a", "size": "12321", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "solr/core/src/java/org/apache/solr/search/facet/DocValuesAcc.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "509" }, { "name": "Batchfile", "bytes": "91853" }, { "name": "CSS", "bytes": "234034" }, { "name": "Emacs Lisp", "bytes": "73" }, { "name": "HTML", "bytes": "326277" }, { "name": "Handlebars", "bytes": "7549" }, { "name": "Java", "bytes": "35849436" }, { "name": "JavaScript", "bytes": "17639" }, { "name": "Python", "bytes": "219385" }, { "name": "Shell", "bytes": "279599" }, { "name": "XSLT", "bytes": "35107" } ], "symlink_target": "" }
FROM gcr.io/oss-fuzz-base/base-builder RUN apt-get update && apt-get install -y \ make \ autoconf \ pkg-config \ automake \ software-properties-common \ wget \ liblzma-dev \ libffi-dev \ libext2fs-dev \ libgpgme-dev libfuse-dev \ python3-pip \ libtool \ bison RUN unset CFLAGS CXXFLAGS && pip3 install -U meson ninja RUN git clone --depth 1 https://gitlab.gnome.org/GNOME/glib RUN git clone https://github.com/ostreedev/ostree && \ cd ostree && \ git submodule update --init COPY build.sh $SRC/ COPY fuzz*.c $SRC/
{ "content_hash": "1ee44887579d02e2ea93f4d9ad73d3b5", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 59, "avg_line_length": 26.09090909090909, "alnum_prop": 0.6550522648083623, "repo_name": "skia-dev/oss-fuzz", "id": "568c9b213f7d1c0fc741ee9b1bc2c1373cb285b3", "size": "1233", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "projects/ostree/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "553498" }, { "name": "C++", "bytes": "412656" }, { "name": "CMake", "bytes": "1635" }, { "name": "Dockerfile", "bytes": "874184" }, { "name": "Go", "bytes": "67217" }, { "name": "HTML", "bytes": "13787" }, { "name": "Java", "bytes": "551460" }, { "name": "JavaScript", "bytes": "2508" }, { "name": "Makefile", "bytes": "13162" }, { "name": "Python", "bytes": "969565" }, { "name": "Ruby", "bytes": "1827" }, { "name": "Rust", "bytes": "8384" }, { "name": "Shell", "bytes": "1356613" }, { "name": "Starlark", "bytes": "5471" }, { "name": "Swift", "bytes": "1363" } ], "symlink_target": "" }
__author__ = 'avathar' class Chromosome(object): """ Chromosome represents an individual """ def __init__(self, genes): self.genes = genes self.fitness = 0 def __str__(self): """ String representation of a chromosome, with fitness and genes """ string = "%3.3i:\t[ " % self.fitness for gen in self.genes: string += "%s " % str(gen) return string + "]"
{ "content_hash": "b850ee15e551a7054049c0a271bb588c", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 73, "avg_line_length": 23.94736842105263, "alnum_prop": 0.512087912087912, "repo_name": "avathardev/ppolom", "id": "a35f20e72936a1824ac3aac22e1a45969ecfca04", "size": "455", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "darwin/chromosome.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "10670" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <copyright // file="StyleCopReportExtensions.cs" // company="Schley Andrew Kutz"> // Copyright (c) Schley Andrew Kutz. All rights reserved. // </copyright> // <authors> // <author>Schley Andrew Kutz</author> // </authors> //------------------------------------------------------------------------------ namespace Net.SF.StyleCopCmd.Core { /// <summary> /// The extensions class for StyleCopReport. /// </summary> public static class StyleCopReportExtensions { /// <summary> /// Creates a ReportBuilder to assist with building this StyleCopReport. /// </summary> /// <param name="report"> /// The StyleCopReport object. /// </param> /// <returns> /// A new ReportBuilder object. /// </returns> public static ReportBuilder ReportBuilder( this StyleCopReport report) { return new ReportBuilder(report); } } }
{ "content_hash": "3d58ff63b2203c4c706c228699481560", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 80, "avg_line_length": 31.58823529411765, "alnum_prop": 0.4823091247672253, "repo_name": "inorton/StyleCopCmd", "id": "6d2c2e5238aa4551b08af5d6d7e8f6d4793d7f85", "size": "2860", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Net.SF.StyleCopCmd.Core/src/StyleCopReportExtensions.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "216408" } ], "symlink_target": "" }
"""Assists with installing symlinks for all dotfiles/configs under this dir.""" import os import sys import errno FILE_MAP = { 'bashrc': '~/.bashrc', 'colordiffrc': '~/.colordiffrc', 'gitconfig': '~/.gitconfig', 'pystartup': '~/.pystartup', 'tmux.conf': '~/.tmux.conf', 'vimrc': '~/.vimrc', 'alacritty.yml': '~/.config/alacritty/alacritty.yml', # TODO(joshcb): This should be OSX only. 'slate': '~/.slate', } DIR_MAP = { 'sublime': '~/.config/sublime-text-3/Packages/User' } def install(src, dst): ensure_dir_exists(dst) os.symlink(src, dst) print "Created %s" % dst def ensure_dir_exists(path): dirname = os.path.dirname(os.path.expanduser(path)) try: os.makedirs(dirname) except OSError as e: if e.errno == errno.EEXIST: pass else: raise def ensure_installed(src, dst): rel = os.path.relpath(dst, os.path.expanduser('~')) if os.path.islink(dst): print "%s is already a symlink, assuming we've already installed it." % rel elif not os.path.exists(dst): result = raw_input("%s doesn't exist. Install symlink? [y/n] " % rel) if result.upper() == 'Y': install(src, dst) else: print "WARNING: %s already exists and is not a symlink, skipping." % rel def main(): # TODO(joshcb): Improve multi-platform support. if sys.platform == 'darwin': del DIR_MAP['sublime'] config_root = os.path.dirname(__file__) full_map = {} for src_dir, dst_dir in DIR_MAP.iteritems(): for file in os.listdir(os.path.join(config_root, src_dir)): full_map[os.path.join(config_root, src_dir, file)] = os.path.join( dst_dir, file) for src_file, dst_file in FILE_MAP.iteritems(): full_map[os.path.join(config_root, src_file)] = dst_file for src in sorted(full_map.keys()): ensure_installed(os.path.abspath(src), os.path.expanduser(full_map[src])) if __name__ == '__main__': main()
{ "content_hash": "9c0e532886033a2ad0611d87b6e2ab18", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 79, "avg_line_length": 26.027397260273972, "alnum_prop": 0.6368421052631579, "repo_name": "minism/config", "id": "b64d9e841c215ed201da924f8c944cecf1884457", "size": "1923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "install.py", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "PowerShell", "bytes": "4145" }, { "name": "Python", "bytes": "5485" }, { "name": "Shell", "bytes": "18011" }, { "name": "Vim Script", "bytes": "347" } ], "symlink_target": "" }
layout: attachment title: FMS-BigPicture-Core-Iterated date: type: attachment published: false status: inherit categories: [] tags: [] meta: {} author: login: scollinsptscd email: [email protected] display_name: scollinsptscd first_name: '' last_name: '' ---
{ "content_hash": "1aaae28645d0e0947cefb9b8f592c031", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 35, "avg_line_length": 16.294117647058822, "alnum_prop": 0.7220216606498195, "repo_name": "scollinspt/scollinspt.github.io", "id": "86e20e51c249b923e5818faaca154d1e2858721b", "size": "281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_attachments/fms-bigpicture-core-iterated.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "71710" }, { "name": "HTML", "bytes": "923040" }, { "name": "JavaScript", "bytes": "52622" }, { "name": "Makefile", "bytes": "178" }, { "name": "R", "bytes": "1308" }, { "name": "Ruby", "bytes": "3254" } ], "symlink_target": "" }
> Simple Mailgun Module some description ### History - 1.0.0: initial release ### Credit - soomtong (github.com/soomtong)
{ "content_hash": "02f8fd10f5e090dc88b0cf36fbd5ece3", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 32, "avg_line_length": 11.454545454545455, "alnum_prop": 0.7063492063492064, "repo_name": "soomtong/blititor", "id": "f88910f5cce317c970f38547e4f6e215e1773945", "size": "138", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "module/mailgun/description.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "73803" }, { "name": "HTML", "bytes": "170570" }, { "name": "JavaScript", "bytes": "367608" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('statmaps', '0002_auto_20141001_2036'), ] operations = [ migrations.AddField( model_name='collection', name='journal_name', field=models.CharField(default=None, max_length=200, null=True, blank=True), preserve_default=True, ), ]
{ "content_hash": "95eb1526fee6cc40e5348e24a936e810", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 88, "avg_line_length": 24.210526315789473, "alnum_prop": 0.6065217391304348, "repo_name": "erramuzpe/NeuroVault", "id": "8ed78489a2424a7e1507a00e951e217343bec449", "size": "484", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "neurovault/apps/statmaps/migrations/0003_collection_journal_name.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "37250" }, { "name": "HTML", "bytes": "178224" }, { "name": "JavaScript", "bytes": "26595" }, { "name": "Nginx", "bytes": "3944" }, { "name": "Perl", "bytes": "1374" }, { "name": "Python", "bytes": "548104" }, { "name": "Shell", "bytes": "4437" } ], "symlink_target": "" }
var initialize_WorkspaceTest = function() { InspectorTest.createWorkspace = function(ignoreEvents) { if (InspectorTest.testFileSystemWorkspaceBinding) InspectorTest.testFileSystemWorkspaceBinding.dispose(); if (InspectorTest.testNetworkMapping) InspectorTest.testNetworkMapping.dispose(); WebInspector.fileSystemMapping.resetForTesting(); InspectorTest.testTargetManager = new WebInspector.TargetManager(); InspectorTest.testWorkspace = new WebInspector.Workspace(); InspectorTest.testFileSystemWorkspaceBinding = new WebInspector.FileSystemWorkspaceBinding(WebInspector.isolatedFileSystemManager, InspectorTest.testWorkspace); InspectorTest.testNetworkMapping = new WebInspector.NetworkMapping(InspectorTest.testTargetManager, InspectorTest.testWorkspace, InspectorTest.testFileSystemWorkspaceBinding, WebInspector.fileSystemMapping); InspectorTest.testNetworkProjectManager = new WebInspector.NetworkProjectManager(InspectorTest.testTargetManager, InspectorTest.testWorkspace, InspectorTest.testNetworkMapping); InspectorTest.testDebuggerWorkspaceBinding = new WebInspector.DebuggerWorkspaceBinding(InspectorTest.testTargetManager, InspectorTest.testWorkspace, InspectorTest.testNetworkMapping); InspectorTest.testCSSWorkspaceBinding = new WebInspector.CSSWorkspaceBinding(InspectorTest.testTargetManager, InspectorTest.testWorkspace, InspectorTest.testNetworkMapping); InspectorTest.testTargetManager.observeTargets({ targetAdded: function(target) { InspectorTest.testNetworkProject = WebInspector.NetworkProject.forTarget(target); }, targetRemoved: function(target) { } }); if (ignoreEvents) return; InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, InspectorTest._defaultWorkspaceEventHandler); InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, InspectorTest._defaultWorkspaceEventHandler); } InspectorTest._mockTargetId = 1; InspectorTest.createMockTarget = function(id, debuggerModelConstructor) { var MockTarget = function(name, connection, callback) { WebInspector.Target.call(this, InspectorTest.testTargetManager, name, WebInspector.Target.Type.Page, connection, null, callback); this.consoleModel = new WebInspector.ConsoleModel(this); this.networkManager = new WebInspector.NetworkManager(this); this.resourceTreeModel = new WebInspector.ResourceTreeModel(this); this.resourceTreeModel._inspectedPageURL = InspectorTest.resourceTreeModel._inspectedPageURL; this.resourceTreeModel._cachedResourcesProcessed = true; this.resourceTreeModel._frameAttached("42", 0); this.runtimeModel = new WebInspector.RuntimeModel(this); this.debuggerModel = debuggerModelConstructor ? new debuggerModelConstructor(this) : new WebInspector.DebuggerModel(this); this._modelByConstructor.set(WebInspector.DebuggerModel, this.debuggerModel); this.domModel = new WebInspector.DOMModel(this); this.cssModel = new WebInspector.CSSModel(this); } MockTarget.prototype = { _loadedWithCapabilities: function() { }, __proto__: WebInspector.Target.prototype } var target = new MockTarget("mock-target-" + id, new WebInspector.StubConnection()); InspectorTest.testTargetManager.addTarget(target); return target; } InspectorTest.createWorkspaceWithTarget = function(ignoreEvents) { InspectorTest.createWorkspace(ignoreEvents); var target = InspectorTest.createMockTarget(InspectorTest._mockTargetId++); return target; } InspectorTest.waitForWorkspaceUISourceCodeAddedEvent = function(callback, count, projectType) { InspectorTest.uiSourceCodeAddedEventsLeft = count || 1; InspectorTest.testWorkspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, InspectorTest._defaultWorkspaceEventHandler); InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded); function uiSourceCodeAdded(event) { if (projectType && event.data.project().type() !== projectType) return; if (!projectType && event.data.project().type() === WebInspector.projectTypes.Service) return; if (!(--InspectorTest.uiSourceCodeAddedEventsLeft)) { InspectorTest.testWorkspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded); InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, InspectorTest._defaultWorkspaceEventHandler); } callback(event.data); } } InspectorTest.waitForWorkspaceUISourceCodeRemovedEvent = function(callback, count) { InspectorTest.uiSourceCodeRemovedEventsLeft = count || 1; InspectorTest.testWorkspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, InspectorTest._defaultWorkspaceEventHandler); InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, uiSourceCodeRemoved); function uiSourceCodeRemoved(event) { if (event.data.project().type() === WebInspector.projectTypes.Service) return; if (!(--InspectorTest.uiSourceCodeRemovedEventsLeft)) { InspectorTest.testWorkspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, uiSourceCodeRemoved); InspectorTest.testWorkspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeRemoved, InspectorTest._defaultWorkspaceEventHandler); } callback(event.data); } } InspectorTest.addMockUISourceCodeToWorkspace = function(url, type, content) { var mockContentProvider = WebInspector.StaticContentProvider.fromString(url, type, content); InspectorTest.testNetworkProject.addFile(mockContentProvider, null, false); } InspectorTest.addMockUISourceCodeViaNetwork = function(url, type, content, target) { var mockContentProvider = WebInspector.StaticContentProvider.fromString(url, type, content); InspectorTest.testNetworkProject.addFile(mockContentProvider, target.resourceTreeModel.mainFrame, false); } InspectorTest._defaultWorkspaceEventHandler = function(event) { var uiSourceCode = event.data; var networkURL = WebInspector.networkMapping.networkURL(uiSourceCode); if (uiSourceCode.project().type() === WebInspector.projectTypes.Debugger && !networkURL) return; if (uiSourceCode.project().type() === WebInspector.projectTypes.Service) return; InspectorTest.addResult("Workspace event: " + event.type + ": " + uiSourceCode.url() + "."); } InspectorTest.uiSourceCodeURL = function(uiSourceCode) { return uiSourceCode.url().replace(/.*LayoutTests/, "LayoutTests"); } InspectorTest.dumpUISourceCode = function(uiSourceCode, callback) { InspectorTest.addResult("UISourceCode: " + InspectorTest.uiSourceCodeURL(uiSourceCode)); if (uiSourceCode.contentType() === WebInspector.resourceTypes.Script || uiSourceCode.contentType() === WebInspector.resourceTypes.Document) InspectorTest.addResult("UISourceCode is content script: " + (uiSourceCode.project().type() === WebInspector.projectTypes.ContentScripts)); uiSourceCode.requestContent().then(didRequestContent); function didRequestContent(content, contentEncoded) { InspectorTest.addResult("Highlighter type: " + WebInspector.NetworkProject.uiSourceCodeMimeType(uiSourceCode)); InspectorTest.addResult("UISourceCode content: " + content); callback(); } } InspectorTest.fileSystemUISourceCodes = function() { var uiSourceCodes = []; var fileSystemProjects = WebInspector.workspace.projectsForType(WebInspector.projectTypes.FileSystem); for (var project of fileSystemProjects) uiSourceCodes = uiSourceCodes.concat(project.uiSourceCodes()); return uiSourceCodes; } InspectorTest.refreshFileSystemProjects = function(callback) { var barrier = new CallbackBarrier(); var projects = WebInspector.workspace.projects(); for (var i = 0; i < projects.length; ++i) projects[i].refresh("/", barrier.createCallback()); barrier.callWhenDone(callback); } InspectorTest.waitForGivenUISourceCode = function(name, callback) { var uiSourceCodes = WebInspector.workspace.uiSourceCodes(); for (var i = 0; i < uiSourceCodes.length; ++i) { if (uiSourceCodes[i].name() === name) { setImmediate(callback); return; } } WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded); function uiSourceCodeAdded(event) { if (event.data.name() === name) { WebInspector.workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeAdded, uiSourceCodeAdded); setImmediate(callback); } } } };
{ "content_hash": "952ec31b9b1f884a88a3428d0ef3351d", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 211, "avg_line_length": 46.266666666666666, "alnum_prop": 0.7598093549102195, "repo_name": "heke123/chromium-crosswalk", "id": "9c7e3de7c4a2c10900a3b061962ad7d3383e454f", "size": "9022", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/WebKit/LayoutTests/http/tests/inspector/workspace-test.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#include "config.h" #include "core/xml/XPathParser.h" #include "bindings/core/v8/ExceptionState.h" #include "core/XPathGrammar.h" #include "core/dom/ExceptionCode.h" #include "core/xml/XPathEvaluator.h" #include "core/xml/XPathNSResolver.h" #include "core/xml/XPathPath.h" #include "wtf/StdLibExtras.h" #include "wtf/text/StringHash.h" using namespace blink; using namespace WTF; using namespace Unicode; using namespace XPath; Parser* Parser::currentParser = nullptr; enum XMLCat { NameStart, NameCont, NotPartOfName }; typedef HashMap<String, Step::Axis> AxisNamesMap; static XMLCat charCat(UChar aChar) { // might need to add some special cases from the XML spec. if (aChar == '_') return NameStart; if (aChar == '.' || aChar == '-') return NameCont; CharCategory category = Unicode::category(aChar); if (category & (Letter_Uppercase | Letter_Lowercase | Letter_Other | Letter_Titlecase | Number_Letter)) return NameStart; if (category & (Mark_NonSpacing | Mark_SpacingCombining | Mark_Enclosing | Letter_Modifier | Number_DecimalDigit)) return NameCont; return NotPartOfName; } static void setUpAxisNamesMap(AxisNamesMap& axisNames) { struct AxisName { const char* name; Step::Axis axis; }; const AxisName axisNameList[] = { { "ancestor", Step::AncestorAxis }, { "ancestor-or-self", Step::AncestorOrSelfAxis }, { "attribute", Step::AttributeAxis }, { "child", Step::ChildAxis }, { "descendant", Step::DescendantAxis }, { "descendant-or-self", Step::DescendantOrSelfAxis }, { "following", Step::FollowingAxis }, { "following-sibling", Step::FollowingSiblingAxis }, { "namespace", Step::NamespaceAxis }, { "parent", Step::ParentAxis }, { "preceding", Step::PrecedingAxis }, { "preceding-sibling", Step::PrecedingSiblingAxis }, { "self", Step::SelfAxis } }; for (unsigned i = 0; i < sizeof(axisNameList) / sizeof(axisNameList[0]); ++i) axisNames.set(axisNameList[i].name, axisNameList[i].axis); } static bool isAxisName(const String& name, Step::Axis& type) { DEFINE_STATIC_LOCAL(AxisNamesMap, axisNames, ()); if (axisNames.isEmpty()) setUpAxisNamesMap(axisNames); AxisNamesMap::iterator it = axisNames.find(name); if (it == axisNames.end()) return false; type = it->value; return true; } static bool isNodeTypeName(const String& name) { DEFINE_STATIC_LOCAL(HashSet<String>, nodeTypeNames, ()); if (nodeTypeNames.isEmpty()) { nodeTypeNames.add("comment"); nodeTypeNames.add("text"); nodeTypeNames.add("processing-instruction"); nodeTypeNames.add("node"); } return nodeTypeNames.contains(name); } // Returns whether the current token can possibly be a binary operator, given // the previous token. Necessary to disambiguate some of the operators // (* (multiply), div, and, or, mod) in the [32] Operator rule // (check http://www.w3.org/TR/xpath#exprlex). bool Parser::isBinaryOperatorContext() const { switch (m_lastTokenType) { case 0: case '@': case AXISNAME: case '(': case '[': case ',': case AND: case OR: case MULOP: case '/': case SLASHSLASH: case '|': case PLUS: case MINUS: case EQOP: case RELOP: return false; default: return true; } } void Parser::skipWS() { while (m_nextPos < m_data.length() && isSpaceOrNewline(m_data[m_nextPos])) ++m_nextPos; } Token Parser::makeTokenAndAdvance(int code, int advance) { m_nextPos += advance; return Token(code); } Token Parser::makeTokenAndAdvance(int code, NumericOp::Opcode val, int advance) { m_nextPos += advance; return Token(code, val); } Token Parser::makeTokenAndAdvance(int code, EqTestOp::Opcode val, int advance) { m_nextPos += advance; return Token(code, val); } // Returns next char if it's there and interesting, 0 otherwise char Parser::peekAheadHelper() { if (m_nextPos + 1 >= m_data.length()) return 0; UChar next = m_data[m_nextPos + 1]; if (next >= 0xff) return 0; return next; } char Parser::peekCurHelper() { if (m_nextPos >= m_data.length()) return 0; UChar next = m_data[m_nextPos]; if (next >= 0xff) return 0; return next; } Token Parser::lexString() { UChar delimiter = m_data[m_nextPos]; int startPos = m_nextPos + 1; for (m_nextPos = startPos; m_nextPos < m_data.length(); ++m_nextPos) { if (m_data[m_nextPos] == delimiter) { String value = m_data.substring(startPos, m_nextPos - startPos); if (value.isNull()) value = ""; ++m_nextPos; // Consume the char. return Token(LITERAL, value); } } // Ouch, went off the end -- report error. return Token(XPATH_ERROR); } Token Parser::lexNumber() { int startPos = m_nextPos; bool seenDot = false; // Go until end or a non-digits character. for (; m_nextPos < m_data.length(); ++m_nextPos) { UChar aChar = m_data[m_nextPos]; if (aChar >= 0xff) break; if (aChar < '0' || aChar > '9') { if (aChar == '.' && !seenDot) seenDot = true; else break; } } return Token(NUMBER, m_data.substring(startPos, m_nextPos - startPos)); } bool Parser::lexNCName(String& name) { int startPos = m_nextPos; if (m_nextPos >= m_data.length()) return false; if (charCat(m_data[m_nextPos]) != NameStart) return false; // Keep going until we get a character that's not good for names. for (; m_nextPos < m_data.length(); ++m_nextPos) { if (charCat(m_data[m_nextPos]) == NotPartOfName) break; } name = m_data.substring(startPos, m_nextPos - startPos); return true; } bool Parser::lexQName(String& name) { String n1; if (!lexNCName(n1)) return false; skipWS(); // If the next character is :, what we just got it the prefix, if not, // it's the whole thing. if (peekAheadHelper() != ':') { name = n1; return true; } String n2; if (!lexNCName(n2)) return false; name = n1 + ":" + n2; return true; } Token Parser::nextTokenInternal() { skipWS(); if (m_nextPos >= m_data.length()) return Token(0); char code = peekCurHelper(); switch (code) { case '(': case ')': case '[': case ']': case '@': case ',': case '|': return makeTokenAndAdvance(code); case '\'': case '\"': return lexString(); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return lexNumber(); case '.': { char next = peekAheadHelper(); if (next == '.') return makeTokenAndAdvance(DOTDOT, 2); if (next >= '0' && next <= '9') return lexNumber(); return makeTokenAndAdvance('.'); } case '/': if (peekAheadHelper() == '/') return makeTokenAndAdvance(SLASHSLASH, 2); return makeTokenAndAdvance('/'); case '+': return makeTokenAndAdvance(PLUS); case '-': return makeTokenAndAdvance(MINUS); case '=': return makeTokenAndAdvance(EQOP, EqTestOp::OpcodeEqual); case '!': if (peekAheadHelper() == '=') return makeTokenAndAdvance(EQOP, EqTestOp::OpcodeNotEqual, 2); return Token(XPATH_ERROR); case '<': if (peekAheadHelper() == '=') return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeLessOrEqual, 2); return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeLessThan); case '>': if (peekAheadHelper() == '=') return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeGreaterOrEqual, 2); return makeTokenAndAdvance(RELOP, EqTestOp::OpcodeGreaterThan); case '*': if (isBinaryOperatorContext()) return makeTokenAndAdvance(MULOP, NumericOp::OP_Mul); ++m_nextPos; return Token(NAMETEST, "*"); case '$': { // $ QName m_nextPos++; String name; if (!lexQName(name)) return Token(XPATH_ERROR); return Token(VARIABLEREFERENCE, name); } } String name; if (!lexNCName(name)) return Token(XPATH_ERROR); skipWS(); // If we're in an operator context, check for any operator names if (isBinaryOperatorContext()) { if (name == "and") // ### hash? return Token(AND); if (name == "or") return Token(OR); if (name == "mod") return Token(MULOP, NumericOp::OP_Mod); if (name == "div") return Token(MULOP, NumericOp::OP_Div); } // See whether we are at a : if (peekCurHelper() == ':') { m_nextPos++; // Any chance it's an axis name? if (peekCurHelper() == ':') { m_nextPos++; // It might be an axis name. Step::Axis axis; if (isAxisName(name, axis)) return Token(AXISNAME, axis); // Ugh, :: is only valid in axis names -> error return Token(XPATH_ERROR); } // Seems like this is a fully qualified qname, or perhaps the * modified // one from NameTest skipWS(); if (peekCurHelper() == '*') { m_nextPos++; return Token(NAMETEST, name + ":*"); } // Make a full qname. String n2; if (!lexNCName(n2)) return Token(XPATH_ERROR); name = name + ":" + n2; } skipWS(); if (peekCurHelper() == '(') { // Note: we don't swallow the ( here! // Either node type of function name if (isNodeTypeName(name)) { if (name == "processing-instruction") return Token(PI, name); return Token(NODETYPE, name); } // Must be a function name. return Token(FUNCTIONNAME, name); } // At this point, it must be NAMETEST. return Token(NAMETEST, name); } Token Parser::nextToken() { Token toRet = nextTokenInternal(); m_lastTokenType = toRet.type; return toRet; } Parser::Parser() { reset(String()); } Parser::~Parser() { } void Parser::reset(const String& data) { m_nextPos = 0; m_data = data; m_lastTokenType = 0; m_topExpr = nullptr; m_gotNamespaceError = false; } int Parser::lex(void* data) { YYSTYPE* yylval = static_cast<YYSTYPE*>(data); Token tok = nextToken(); switch (tok.type) { case AXISNAME: yylval->axis = tok.axis; break; case MULOP: yylval->numop = tok.numop; break; case RELOP: case EQOP: yylval->eqop = tok.eqop; break; case NODETYPE: case PI: case FUNCTIONNAME: case LITERAL: case VARIABLEREFERENCE: case NUMBER: case NAMETEST: yylval->str = new String(tok.str); registerString(yylval->str); break; } return tok.type; } bool Parser::expandQName(const String& qName, AtomicString& localName, AtomicString& namespaceURI) { size_t colon = qName.find(':'); if (colon != kNotFound) { if (!m_resolver) return false; namespaceURI = m_resolver->lookupNamespaceURI(qName.left(colon)); if (namespaceURI.isNull()) return false; localName = AtomicString(qName.substring(colon + 1)); } else { localName = AtomicString(qName); } return true; } Expression* Parser::parseStatement(const String& statement, XPathNSResolver* resolver, ExceptionState& exceptionState) { reset(statement); m_resolver = resolver; Parser* oldParser = currentParser; currentParser = this; int parseError = xpathyyparse(this); currentParser = oldParser; if (parseError) { m_strings.clear(); m_topExpr = nullptr; if (m_gotNamespaceError) exceptionState.throwDOMException(NamespaceError, "The string '" + statement + "' contains unresolvable namespaces."); else exceptionState.throwDOMException(SyntaxError, "The string '" + statement + "' is not a valid XPath expression."); return nullptr; } ASSERT(m_strings.size() == 0); Expression* result = m_topExpr; m_topExpr = nullptr; return result; } void Parser::registerString(String* s) { if (s == 0) return; ASSERT(!m_strings.contains(s)); m_strings.add(adoptPtr(s)); } void Parser::deleteString(String* s) { if (s == 0) return; ASSERT(m_strings.contains(s)); m_strings.remove(s); }
{ "content_hash": "dee7dfc99cf2ec39cb2dc2010aced3da", "timestamp": "", "source": "github", "line_count": 490, "max_line_length": 129, "avg_line_length": 26.079591836734693, "alnum_prop": 0.586822130057125, "repo_name": "zero-rp/miniblink49", "id": "d3a4d72d495ae3b89936c929334f3d73b8b31ed5", "size": "14190", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/xml/XPathParser.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "11324414" }, { "name": "Batchfile", "bytes": "52488" }, { "name": "C", "bytes": "31014938" }, { "name": "C++", "bytes": "281193388" }, { "name": "CMake", "bytes": "88548" }, { "name": "CSS", "bytes": "20839" }, { "name": "DIGITAL Command Language", "bytes": "226954" }, { "name": "HTML", "bytes": "202637" }, { "name": "JavaScript", "bytes": "32544926" }, { "name": "Lua", "bytes": "32432" }, { "name": "M4", "bytes": "125191" }, { "name": "Makefile", "bytes": "1517330" }, { "name": "Objective-C", "bytes": "87691" }, { "name": "Objective-C++", "bytes": "35037" }, { "name": "PHP", "bytes": "307541" }, { "name": "Perl", "bytes": "3283676" }, { "name": "Prolog", "bytes": "29177" }, { "name": "Python", "bytes": "4308928" }, { "name": "R", "bytes": "10248" }, { "name": "Scheme", "bytes": "25457" }, { "name": "Shell", "bytes": "264021" }, { "name": "TypeScript", "bytes": "162421" }, { "name": "Vim script", "bytes": "11362" }, { "name": "XS", "bytes": "4319" }, { "name": "eC", "bytes": "4383" } ], "symlink_target": "" }
BSLS_IDENT("$Id$ $CSID$") namespace bsl { } // close namespace bsl // ---------------------------------------------------------------------------- // Copyright 2019 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
{ "content_hash": "f85506dd99e1d4b344323c51ead5c420", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 79, "avg_line_length": 39.523809523809526, "alnum_prop": 0.6024096385542169, "repo_name": "che2/bde", "id": "c25d40837ec97c461ec11a527157c16deb9d4741", "size": "961", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "groups/bsl/bslstl/bslstl_array.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "153030" }, { "name": "C++", "bytes": "95839894" }, { "name": "Perl", "bytes": "2008" }, { "name": "Python", "bytes": "920" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (C) 2021-2022 Objectos Software LTDA. 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>br.com.objectos.parent-java11</groupId> <artifactId>build</artifactId> <version>0.1.0-SNAPSHOT</version> <relativePath>../br.com.objectos.parent/pom-java11.xml</relativePath> </parent> <groupId>br.com.objectos.concurrent-java11</groupId> <artifactId>concurrent</artifactId> <version>0.1.0-SNAPSHOT</version> <name>${project.groupId}:${project.artifactId}</name> <description>Objectos Concurrency library</description> <url>https://www.objectos.com.br/</url> <licenses> <license> <name>The Apache License, Version 2.0</name> <url>https://www.apache.org/licenses/LICENSE-2.0</url> <distribution>repo</distribution> </license> </licenses> <scm> <connection>scm:git:ssh://git@rio/srv/git/concurrent.git</connection> <developerConnection>scm:git:ssh://git@rio/srv/git/concurrent.git</developerConnection> <url>https://github.com/objectos/concurrent</url> <tag>HEAD</tag> </scm> <organization> <name>Objectos Software LTDA</name> <url>https://www.objectos.com.br/</url> </organization> <developers> <developer> <id>objectos</id> <name>Objectos Software LTDA</name> <email>[email protected]</email> <organization>Objectos Software LTDA</organization> <organizationUrl>https://www.objectos.com.br/</organizationUrl> </developer> </developers> <inceptionYear>2021</inceptionYear> <properties> <objectos.core.groupId>br.com.objectos.core${gid}</objectos.core.groupId> <objectos.core.version>0.1.0-SNAPSHOT</objectos.core.version> <objectos.fs.groupId>br.com.objectos.fs${gid}</objectos.fs.groupId> <objectos.fs.version>0.1.0-SNAPSHOT</objectos.fs.version> </properties> <dependencies> <dependency> <groupId>${objectos.core.groupId}</groupId> <artifactId>logging-testing</artifactId> <version>${objectos.core.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>${objectos.core.groupId}</groupId> <artifactId>list</artifactId> <version>${objectos.core.version}</version> </dependency> <dependency> <groupId>${objectos.core.groupId}</groupId> <artifactId>service</artifactId> <version>${objectos.core.version}</version> </dependency> <dependency> <groupId>${objectos.core.groupId}</groupId> <artifactId>throwable</artifactId> <version>${objectos.core.version}</version> </dependency> <dependency> <groupId>${objectos.fs.groupId}</groupId> <artifactId>testing</artifactId> <version>${objectos.fs.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "87cb5bf363315bf64146431d1df61daf", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 205, "avg_line_length": 21.904191616766468, "alnum_prop": 0.7061235647895024, "repo_name": "objectos/concurrent", "id": "8a1a744c8ba9528de92bec3ba042bdf97f14ee10", "size": "3658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom-java11.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "90713" } ], "symlink_target": "" }
define([ 'jquery' ], function ($) { function syncCssClasses ($dest, $src, adapter) { var classes, replacements = [], adapted; classes = $.trim($dest.attr('class')); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(/\s+/)).each(function () { // Save all Select2 classes if (this.indexOf('select2-') === 0) { replacements.push(this); } }); } classes = $.trim($src.attr('class')); if (classes) { classes = '' + classes; // for IE which returns object $(classes.split(/\s+/)).each(function () { // Only adapt non-Select2 classes if (this.indexOf('select2-') !== 0) { adapted = adapter(this); if (adapted != null) { replacements.push(adapted); } } }); } $dest.attr('class', replacements.join(' ')); } return { syncCssClasses: syncCssClasses }; });
{ "content_hash": "42e3042eb81996ed77402ad69a07ebd7", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 60, "avg_line_length": 21.622222222222224, "alnum_prop": 0.513874614594039, "repo_name": "N00bface/Real-Dolmen-Stage-Opdrachten", "id": "65bdb25edae9fc490035d4fa56737252a7d40a74", "size": "1218", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "stageopdracht/src/main/resources/static/vendors/select2/src/js/select2/compat/utils.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "212672" }, { "name": "HTML", "bytes": "915596" }, { "name": "Java", "bytes": "78870" }, { "name": "JavaScript", "bytes": "9181" } ], "symlink_target": "" }
package org.hisp.dhis.oum.action.organisationunit; import com.opensymphony.xwork2.Action; import org.hisp.dhis.i18n.I18n; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitService; import java.util.List; /** * @author Torgeir Lorange Ostby * @version $Id: ValidateOrganisationUnitAction.java 1898 2006-09-22 12:06:56Z * torgeilo $ */ public class ValidateOrganisationUnitAction implements Action { // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- private OrganisationUnitService organisationUnitService; public void setOrganisationUnitService( OrganisationUnitService organisationUnitService ) { this.organisationUnitService = organisationUnitService; } // ------------------------------------------------------------------------- // Input // ------------------------------------------------------------------------- private Integer id; public void setId( Integer id ) { this.id = id; } private String name; public void setName( String name ) { this.name = name; } private String code; public void setCode( String code ) { this.code = code; } // ------------------------------------------------------------------------- // Output // ------------------------------------------------------------------------- private String message; public String getMessage() { return message; } private I18n i18n; public void setI18n( I18n i18n ) { this.i18n = i18n; } // ------------------------------------------------------------------------- // Action implementation // ------------------------------------------------------------------------- @Override public String execute() { // --------------------------------------------------------------------- // Validate values // --------------------------------------------------------------------- if ( name != null && !name.trim().isEmpty() ) { List<OrganisationUnit> organisationUnits = organisationUnitService.getOrganisationUnitByName( name ); if ( !organisationUnits.isEmpty() && id == null ) { message = i18n.getString( "name_exists" ); return ERROR; } else if ( !organisationUnits.isEmpty() ) { boolean found = false; for ( OrganisationUnit organisationUnit : organisationUnits ) { if ( organisationUnit.getId() == id ) { found = true; } } if ( !found ) { message = i18n.getString( "name_exists" ); return ERROR; } } } if ( code != null && !code.trim().isEmpty() ) { OrganisationUnit match = organisationUnitService.getOrganisationUnitByCode( code ); if ( match != null && (id == null || match.getId() != id) ) { message = i18n.getString( "code_in_use" ); return ERROR; } } message = "OK"; return SUCCESS; } }
{ "content_hash": "dfa896130f5e78bd2fa3a06a1959efc1", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 113, "avg_line_length": 27.583333333333332, "alnum_prop": 0.40346058775061794, "repo_name": "steffeli/inf5750-tracker-capture", "id": "5eb13a948295ccf465be0c03b2b09f78cdcf8e17", "size": "5223", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "dhis-web/dhis-web-maintenance/dhis-web-maintenance-organisationunit/src/main/java/org/hisp/dhis/oum/action/organisationunit/ValidateOrganisationUnitAction.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "404669" }, { "name": "Game Maker Language", "bytes": "20893" }, { "name": "HTML", "bytes": "402350" }, { "name": "Java", "bytes": "15709343" }, { "name": "JavaScript", "bytes": "7104924" }, { "name": "Ruby", "bytes": "1011" }, { "name": "Shell", "bytes": "388" }, { "name": "XSLT", "bytes": "8281" } ], "symlink_target": "" }
<?php namespace Magento\GiftMessage\Test\Block\Cart\GiftOptions; use Magento\Mtf\Block\Form; /** * Class GiftMessageForm * Gift Message Form */ class GiftMessageForm extends Form { // }
{ "content_hash": "211bb0ec3773ab4e1222083ad4340813", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 58, "avg_line_length": 13.133333333333333, "alnum_prop": 0.7208121827411168, "repo_name": "j-froehlich/magento2_wk", "id": "df5a10944a3c90ce1fa12d20b648bd486a4a56c8", "size": "305", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/magento/magento2-base/dev/tests/functional/tests/app/Magento/GiftMessage/Test/Block/Cart/GiftOptions/GiftMessageForm.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
/* global jQuery */ ( function ( $, document ) { 'use strict'; var file = {}; /** * Handles a click on add new file. * Expects `this` to equal the clicked element. * * @param event Click event. */ file.addHandler = function ( event ) { event.preventDefault(); var $this = $( this ), $clone = $this.siblings( '.rwmb-file-input:last' ).clone(); $clone.insertBefore( this ); file.updateVisibility.call( $this.closest( '.rwmb-input' ).find( '.rwmb-uploaded' )[0] ); }; /** * Handles a click on delete new file. * Expects `this` to equal the clicked element. * * @param event Click event. */ file.deleteHandler = function ( event ) { event.preventDefault(); var $this = $( this ), $item = $this.closest( 'li' ), $uploaded = $this.closest( '.rwmb-uploaded' ), data = { action: 'rwmb_delete_file', _ajax_nonce: $uploaded.data( 'delete_nonce' ), post_id: $( '#post_ID' ).val(), field_id: $uploaded.data( 'field_id' ), object_type: $this.closest('.rwmb-meta-box').attr('data-object-type'), attachment_id: $this.data( 'attachment_id' ), force_delete: $uploaded.data( 'force_delete' ) }; $item.remove(); file.updateVisibility.call( $uploaded ); $.post( ajaxurl, data, function ( response ) { if ( ! response.success ) { alert( response.data ); } }, 'json' ); }; /** * Sort uploaded files. * Expects `this` to equal the uploaded file list. */ file.sort = function () { var $this = $( this ), data = { action: 'rwmb_reorder_files', _ajax_nonce: $this.data( 'reorder_nonce' ), post_id: $( '#post_ID' ).val(), field_id: $this.data( 'field_id' ), object_type: $this.closest('.rwmb-meta-box').attr('data-object-type') }; $this.sortable( { placeholder: 'ui-state-highlight', items: 'li', update: function () { data.order = $this.sortable( 'serialize' ); $.post( ajaxurl, data ); } } ); }; /** * Update visibility of upload inputs and Add new file link. * Expect this equal to the uploaded file list. */ file.updateVisibility = function () { var $uploaded = $( this ), max = parseInt( $uploaded.data( 'max_file_uploads' ), 10 ), $uploader = $uploaded.siblings( '.rwmb-new-files' ), $addMore = $uploader.find( '.rwmb-add-file' ), numFiles = $uploaded.children().length, numInputs = $uploader.find( '.rwmb-file-input' ).length; $uploaded.toggle( 0 < numFiles ); if ( 0 === max ) { return; } $uploader.toggle( numFiles < max ); $addMore.toggle( numFiles + numInputs < max ); }; // Initialize when document ready. $( function ( $ ) { $( document ) .on( 'click', '.rwmb-add-file', file.addHandler ) .on( 'click', '.rwmb-delete-file', file.deleteHandler ); var $uploaded = $( '.rwmb-uploaded' ); $uploaded.each( file.sort ); $uploaded.each( file.updateVisibility ); } ); } )( jQuery, document );
{ "content_hash": "864939a335d0a24cab5baab5ea136f6e", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 91, "avg_line_length": 26.87037037037037, "alnum_prop": 0.5999310820124052, "repo_name": "cast-fuse/gingerbread-tips", "id": "5b964da30c40fb50c9d445dd26e7febb25216499", "size": "2902", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wordpress/wp-content/plugins/meta-box/js/file.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "235" }, { "name": "CSS", "bytes": "1682615" }, { "name": "Elm", "bytes": "9863" }, { "name": "HTML", "bytes": "580" }, { "name": "JavaScript", "bytes": "2639957" }, { "name": "PHP", "bytes": "10952013" }, { "name": "Shell", "bytes": "50" } ], "symlink_target": "" }
#pragma once #include <aws/ec2/EC2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/ec2/model/DiskImageFormat.h> #include <aws/ec2/model/ContainerFormat.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace EC2 { namespace Model { /* <p>Describes the format and location for an instance export task.</p> */ class AWS_EC2_API ExportToS3Task { public: ExportToS3Task(); ExportToS3Task(const Aws::Utils::Xml::XmlNode& xmlNode); ExportToS3Task& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /* <p>The format for the exported image.</p> */ inline const DiskImageFormat& GetDiskImageFormat() const{ return m_diskImageFormat; } /* <p>The format for the exported image.</p> */ inline void SetDiskImageFormat(const DiskImageFormat& value) { m_diskImageFormatHasBeenSet = true; m_diskImageFormat = value; } /* <p>The format for the exported image.</p> */ inline void SetDiskImageFormat(DiskImageFormat&& value) { m_diskImageFormatHasBeenSet = true; m_diskImageFormat = value; } /* <p>The format for the exported image.</p> */ inline ExportToS3Task& WithDiskImageFormat(const DiskImageFormat& value) { SetDiskImageFormat(value); return *this;} /* <p>The format for the exported image.</p> */ inline ExportToS3Task& WithDiskImageFormat(DiskImageFormat&& value) { SetDiskImageFormat(value); return *this;} /* <p>The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported.</p> */ inline const ContainerFormat& GetContainerFormat() const{ return m_containerFormat; } /* <p>The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported.</p> */ inline void SetContainerFormat(const ContainerFormat& value) { m_containerFormatHasBeenSet = true; m_containerFormat = value; } /* <p>The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported.</p> */ inline void SetContainerFormat(ContainerFormat&& value) { m_containerFormatHasBeenSet = true; m_containerFormat = value; } /* <p>The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported.</p> */ inline ExportToS3Task& WithContainerFormat(const ContainerFormat& value) { SetContainerFormat(value); return *this;} /* <p>The container format used to combine disk images with metadata (such as OVF). If absent, only the disk image is exported.</p> */ inline ExportToS3Task& WithContainerFormat(ContainerFormat&& value) { SetContainerFormat(value); return *this;} /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline const Aws::String& GetS3Bucket() const{ return m_s3Bucket; } /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline void SetS3Bucket(const Aws::String& value) { m_s3BucketHasBeenSet = true; m_s3Bucket = value; } /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline void SetS3Bucket(Aws::String&& value) { m_s3BucketHasBeenSet = true; m_s3Bucket = value; } /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline void SetS3Bucket(const char* value) { m_s3BucketHasBeenSet = true; m_s3Bucket.assign(value); } /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline ExportToS3Task& WithS3Bucket(const Aws::String& value) { SetS3Bucket(value); return *this;} /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline ExportToS3Task& WithS3Bucket(Aws::String&& value) { SetS3Bucket(value); return *this;} /* <p>The S3 bucket for the destination image. The destination bucket must exist and grant WRITE and READ_ACP permissions to the AWS account <code>[email protected]</code>.</p> */ inline ExportToS3Task& WithS3Bucket(const char* value) { SetS3Bucket(value); return *this;} /* <p>The encryption key for your S3 bucket.</p> */ inline const Aws::String& GetS3Key() const{ return m_s3Key; } /* <p>The encryption key for your S3 bucket.</p> */ inline void SetS3Key(const Aws::String& value) { m_s3KeyHasBeenSet = true; m_s3Key = value; } /* <p>The encryption key for your S3 bucket.</p> */ inline void SetS3Key(Aws::String&& value) { m_s3KeyHasBeenSet = true; m_s3Key = value; } /* <p>The encryption key for your S3 bucket.</p> */ inline void SetS3Key(const char* value) { m_s3KeyHasBeenSet = true; m_s3Key.assign(value); } /* <p>The encryption key for your S3 bucket.</p> */ inline ExportToS3Task& WithS3Key(const Aws::String& value) { SetS3Key(value); return *this;} /* <p>The encryption key for your S3 bucket.</p> */ inline ExportToS3Task& WithS3Key(Aws::String&& value) { SetS3Key(value); return *this;} /* <p>The encryption key for your S3 bucket.</p> */ inline ExportToS3Task& WithS3Key(const char* value) { SetS3Key(value); return *this;} private: DiskImageFormat m_diskImageFormat; bool m_diskImageFormatHasBeenSet; ContainerFormat m_containerFormat; bool m_containerFormatHasBeenSet; Aws::String m_s3Bucket; bool m_s3BucketHasBeenSet; Aws::String m_s3Key; bool m_s3KeyHasBeenSet; }; } // namespace Model } // namespace EC2 } // namespace Aws
{ "content_hash": "743d353a58251bdd7ad252e22e704f3d", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 188, "avg_line_length": 39.50595238095238, "alnum_prop": 0.6968509868916679, "repo_name": "zeliard/aws-sdk-cpp", "id": "64dfe0d67c446aad1f498da71860c18840c1f1a3", "size": "7208", "binary": false, "copies": "3", "ref": "refs/heads/windows-custom", "path": "aws-cpp-sdk-ec2/include/aws/ec2/model/ExportToS3Task.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "13169" }, { "name": "C++", "bytes": "65046472" }, { "name": "CMake", "bytes": "266341" }, { "name": "Java", "bytes": "214644" }, { "name": "Python", "bytes": "45989" } ], "symlink_target": "" }
package org.pitest.mutationtest.execute; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.pitest.mutationtest.LocationMother.aLocation; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import junit.framework.AssertionFailedError; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.pitest.classinfo.ClassName; import org.pitest.functional.F3; import org.pitest.mutationtest.DetectionStatus; import org.pitest.mutationtest.MutationStatusTestPair; import org.pitest.mutationtest.engine.Mutant; import org.pitest.mutationtest.engine.Mutater; import org.pitest.mutationtest.engine.MutationDetails; import org.pitest.mutationtest.engine.MutationIdentifier; import org.pitest.testapi.Description; import org.pitest.testapi.ResultCollector; import org.pitest.testapi.TestUnit; public class MutationTestWorkerTest { private MutationTestWorker testee; @Mock private ClassLoader loader; @Mock private Mutater mutater; @Mock private F3<ClassName, ClassLoader, byte[], Boolean> hotswapper; @Mock private TimeOutDecoratedTestSource testSource; @Mock private Reporter reporter; @Before public void setUp() { MockitoAnnotations.initMocks(this); this.testee = new MutationTestWorker(this.hotswapper, this.mutater, this.loader); } @Test public void shouldDescribeEachExaminedMutation() throws IOException { final MutationDetails mutantOne = makeMutant("foo", 1); final MutationDetails mutantTwo = makeMutant("foo", 2); final Collection<MutationDetails> range = Arrays.asList(mutantOne, mutantTwo); this.testee.run(range, this.reporter, this.testSource); verify(this.reporter).describe(mutantOne.getId()); verify(this.reporter).describe(mutantTwo.getId()); } @Test @Ignore("disabled while checking coverage issue") public void shouldReportNoCoverageForMutationWithNoTestCoverage() throws IOException { final MutationDetails mutantOne = makeMutant("foo", 1); final Collection<MutationDetails> range = Arrays.asList(mutantOne); this.testee.run(range, this.reporter, this.testSource); verify(this.reporter).report(mutantOne.getId(), new MutationStatusTestPair(0, DetectionStatus.NO_COVERAGE)); } @SuppressWarnings("unchecked") @Test public void shouldReportWhenMutationNotDetected() throws IOException { final MutationDetails mutantOne = makeMutant("foo", 1); final Collection<MutationDetails> range = Arrays.asList(mutantOne); final TestUnit tu = makePassingTest(); when(this.testSource.translateTests(any(List.class))).thenReturn( Collections.singletonList(tu)); when( this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), any(byte[].class))).thenReturn(true); this.testee.run(range, this.reporter, this.testSource); verify(this.reporter).report(mutantOne.getId(), new MutationStatusTestPair(1, DetectionStatus.SURVIVED)); } @SuppressWarnings("unchecked") @Test public void shouldReportWhenMutationNotViable() throws IOException { final MutationDetails mutantOne = makeMutant("foo", 1); final Collection<MutationDetails> range = Arrays.asList(mutantOne); final TestUnit tu = makePassingTest(); when(this.testSource.translateTests(any(List.class))).thenReturn( Collections.singletonList(tu)); when( this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), any(byte[].class))).thenReturn(false); this.testee.run(range, this.reporter, this.testSource); verify(this.reporter).report(mutantOne.getId(), new MutationStatusTestPair(0, DetectionStatus.NON_VIABLE)); } @SuppressWarnings("unchecked") @Test public void shouldReportWhenMutationKilledByTest() throws IOException { final MutationDetails mutantOne = makeMutant("foo", 1); final Collection<MutationDetails> range = Arrays.asList(mutantOne); final TestUnit tu = makeFailingTest(); when(this.testSource.translateTests(any(List.class))).thenReturn( Collections.singletonList(tu)); when( this.hotswapper.apply(any(ClassName.class), any(ClassLoader.class), any(byte[].class))).thenReturn(true); this.testee.run(range, this.reporter, this.testSource); verify(this.reporter).report( mutantOne.getId(), new MutationStatusTestPair(1, DetectionStatus.KILLED, tu .getDescription().getName())); } private TestUnit makeFailingTest() { return new TestUnit() { public void execute(final ClassLoader loader, final ResultCollector rc) { rc.notifyStart(getDescription()); rc.notifyEnd(getDescription(), new AssertionFailedError()); } public Description getDescription() { return new Description("atest"); } }; } private TestUnit makePassingTest() { return new TestUnit() { public void execute(final ClassLoader loader, final ResultCollector rc) { rc.notifyStart(getDescription()); rc.notifyEnd(getDescription()); } public Description getDescription() { return new Description("atest"); } }; } public MutationDetails makeMutant(final String clazz, final int index) { final MutationDetails md = new MutationDetails(new MutationIdentifier( aLocation().withClass(clazz), index, "mutator"), "sourceFile", "desc", 42, 0); when(this.mutater.getMutation(md.getId())).thenReturn( new Mutant(md, new byte[0])); return md; } }
{ "content_hash": "b46608ee828df274bdd5c2fd16d925ce", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 79, "avg_line_length": 34.138728323699425, "alnum_prop": 0.7124957670165933, "repo_name": "alipourm/pitest-personalized", "id": "722650975c06285719f552f1e240477c21e9705c", "size": "5906", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "pitest/src/test/java/org/pitest/mutationtest/execute/MutationTestWorkerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "864" }, { "name": "Groovy", "bytes": "949" }, { "name": "Java", "bytes": "1736879" }, { "name": "Shell", "bytes": "53" } ], "symlink_target": "" }
<!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_60) on Tue Aug 26 20:49:58 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.common.cloud.DefaultConnectionStrategy (Solr 4.10.0 API)</title> <meta name="date" content="2014-08-26"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.common.cloud.DefaultConnectionStrategy (Solr 4.10.0 API)"; } //--> </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><a href="../../../../../../org/apache/solr/common/cloud/DefaultConnectionStrategy.html" title="class in org.apache.solr.common.cloud">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="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/common/cloud/class-use/DefaultConnectionStrategy.html" target="_top">Frames</a></li> <li><a href="DefaultConnectionStrategy.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> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.common.cloud.DefaultConnectionStrategy" class="title">Uses of Class<br>org.apache.solr.common.cloud.DefaultConnectionStrategy</h2> </div> <div class="classUseContainer">No usage of org.apache.solr.common.cloud.DefaultConnectionStrategy</div> <!-- ======= 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><a href="../../../../../../org/apache/solr/common/cloud/DefaultConnectionStrategy.html" title="class in org.apache.solr.common.cloud">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="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/common/cloud/class-use/DefaultConnectionStrategy.html" target="_top">Frames</a></li> <li><a href="DefaultConnectionStrategy.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> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
{ "content_hash": "4f77275f09c27980f06e65270ca437aa", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 171, "avg_line_length": 38.083969465648856, "alnum_prop": 0.603126879134095, "repo_name": "Ramzi-Alqrainy/SELK", "id": "2c392d4b2558b99c26f61b8abd543e983be4175e", "size": "4989", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "solr-4.10.0/docs/solr-solrj/org/apache/solr/common/cloud/class-use/DefaultConnectionStrategy.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "666490" }, { "name": "Erlang", "bytes": "5309" }, { "name": "JavaScript", "bytes": "1831427" }, { "name": "Ruby", "bytes": "987996" }, { "name": "Shell", "bytes": "78761" }, { "name": "XSLT", "bytes": "126437" } ], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util = require("./util"); var Profiler = (function () { function Profiler(backendTimer, logger) { this.backendTimer = backendTimer; this.logger = logger; if (logger == null) { this.logger = new Logger(); } } Profiler.prototype.profileKernel = function (kernelName, f) { var _this = this; var result; var holdResultWrapperFn = function () { result = f(); }; var timer = this.backendTimer.time(holdResultWrapperFn); var vals = result.dataSync(); util.checkForNaN(vals, result.dtype, kernelName); timer.then(function (timing) { _this.logger.logKernelProfile(kernelName, result, vals, timing.kernelMs); }); return result; }; return Profiler; }()); exports.Profiler = Profiler; var Logger = (function () { function Logger() { } Logger.prototype.logKernelProfile = function (kernelName, result, vals, timeMs) { var time = util.rightPad(timeMs + "ms", 9); var paddedName = util.rightPad(kernelName, 25); var rank = result.rank; var size = result.size; var shape = util.rightPad(result.shape.toString(), 14); console.log("%c" + paddedName + "\t%c" + time + "\t%c" + rank + "D " + shape + "\t%c" + size, 'font-weight:bold', 'color:red', 'color:blue', 'color: orange'); }; return Logger; }()); exports.Logger = Logger;
{ "content_hash": "9c1d2b8a080ee7101c03807874bc9506", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 166, "avg_line_length": 36.333333333333336, "alnum_prop": 0.5891218872870249, "repo_name": "cdnjs/cdnjs", "id": "1375ac4aa333b7c576bc0bd52553a91c3405abf6", "size": "1526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/deeplearn/0.5.0/profiler.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
@protocol BSInjector; @interface InjectorProvider : NSObject + (id<BSInjector>)injector; @end
{ "content_hash": "394153bddc74410c3cd6a73bbf018529", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 38, "avg_line_length": 12.25, "alnum_prop": 0.7551020408163265, "repo_name": "imroopesh/TDDUsingCedar", "id": "f04488e751fb9ce1ca0e456507f4eb21c7f3c7bb", "size": "134", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TDDUsingCedar/Modules/InjectorProvider.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "18126" }, { "name": "Objective-C++", "bytes": "22026" } ], "symlink_target": "" }
// Copyright 2011 Google Inc. All rights reserved. // Use of this source code is governed by the Apache 2.0 // license that can be found in the LICENSE file. /* Package datastore provides a client for App Engine's datastore service. Basic Operations Entities are the unit of storage and are associated with a key. A key consists of an optional parent key, a string application ID, a string kind (also known as an entity type), and either a StringID or an IntID. A StringID is also known as an entity name or key name. It is valid to create a key with a zero StringID and a zero IntID; this is called an incomplete key, and does not refer to any saved entity. Putting an entity into the datastore under an incomplete key will cause a unique key to be generated for that entity, with a non-zero IntID. An entity's contents are a mapping from case-sensitive field names to values. Valid value types are: - signed integers (int, int8, int16, int32 and int64), - bool, - string, - float32 and float64, - []byte (up to 1 megabyte in length), - any type whose underlying type is one of the above predeclared types, - ByteString, - *Key, - time.Time (stored with microsecond precision), - appengine.BlobKey, - appengine.GeoPoint, - structs whose fields are all valid value types, - slices of any of the above. Slices of structs are valid, as are structs that contain slices. However, if one struct contains another, then at most one of those can be repeated. This disqualifies recursively defined struct types: any struct T that (directly or indirectly) contains a []T. The Get and Put functions load and save an entity's contents. An entity's contents are typically represented by a struct pointer. Example code: type Entity struct { Value string } func handle(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) k := datastore.NewKey(ctx, "Entity", "stringID", 0, nil) e := new(Entity) if err := datastore.Get(ctx, k, e); err != nil { http.Error(w, err.Error(), 500) return } old := e.Value e.Value = r.URL.Path if _, err := datastore.Put(ctx, k, e); err != nil { http.Error(w, err.Error(), 500) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "old=%q\nnew=%q\n", old, e.Value) } GetMulti, PutMulti and DeleteMulti are batch versions of the Get, Put and Delete functions. They take a []*Key instead of a *Key, and may return an appengine.MultiError when encountering partial failure. Properties An entity's contents can be represented by a variety of types. These are typically struct pointers, but can also be any type that implements the PropertyLoadSaver interface. If using a struct pointer, you do not have to explicitly implement the PropertyLoadSaver interface; the datastore will automatically convert via reflection. If a struct pointer does implement that interface then those methods will be used in preference to the default behavior for struct pointers. Struct pointers are more strongly typed and are easier to use; PropertyLoadSavers are more flexible. The actual types passed do not have to match between Get and Put calls or even across different App Engine requests. It is valid to put a *PropertyList and get that same entity as a *myStruct, or put a *myStruct0 and get a *myStruct1. Conceptually, any entity is saved as a sequence of properties, and is loaded into the destination value on a property-by-property basis. When loading into a struct pointer, an entity that cannot be completely represented (such as a missing field) will result in an ErrFieldMismatch error but it is up to the caller whether this error is fatal, recoverable or ignorable. By default, for struct pointers, all properties are potentially indexed, and the property name is the same as the field name (and hence must start with an upper case letter). Fields may have a `datastore:"name,options"` tag. The tag name is the property name, which must be one or more valid Go identifiers joined by ".", but may start with a lower case letter. An empty tag name means to just use the field name. A "-" tag name means that the datastore will ignore that field. If options is "noindex" then the field will not be indexed. If the options is "" then the comma may be omitted. There are no other recognized options. Fields (except for []byte) are indexed by default. Strings longer than 1500 bytes cannot be indexed; fields used to store long strings should be tagged with "noindex". Similarly, ByteStrings longer than 1500 bytes cannot be indexed. Example code: // A and B are renamed to a and b. // A, C and J are not indexed. // D's tag is equivalent to having no tag at all (E). // I is ignored entirely by the datastore. // J has tag information for both the datastore and json packages. type TaggedStruct struct { A int `datastore:"a,noindex"` B int `datastore:"b"` C int `datastore:",noindex"` D int `datastore:""` E int I int `datastore:"-"` J int `datastore:",noindex" json:"j"` } Structured Properties If the struct pointed to contains other structs, then the nested or embedded structs are flattened. For example, given these definitions: type Inner1 struct { W int32 X string } type Inner2 struct { Y float64 } type Inner3 struct { Z bool } type Outer struct { A int16 I []Inner1 J Inner2 Inner3 } then an Outer's properties would be equivalent to those of: type OuterEquivalent struct { A int16 IDotW []int32 `datastore:"I.W"` IDotX []string `datastore:"I.X"` JDotY float64 `datastore:"J.Y"` Z bool } If Outer's embedded Inner3 field was tagged as `datastore:"Foo"` then the equivalent field would instead be: FooDotZ bool `datastore:"Foo.Z"`. If an outer struct is tagged "noindex" then all of its implicit flattened fields are effectively "noindex". The PropertyLoadSaver Interface An entity's contents can also be represented by any type that implements the PropertyLoadSaver interface. This type may be a struct pointer, but it does not have to be. The datastore package will call Load when getting the entity's contents, and Save when putting the entity's contents. Possible uses include deriving non-stored fields, verifying fields, or indexing a field only if its value is positive. Example code: type CustomPropsExample struct { I, J int // Sum is not stored, but should always be equal to I + J. Sum int `datastore:"-"` } func (x *CustomPropsExample) Load(ps []datastore.Property) error { // Load I and J as usual. if err := datastore.LoadStruct(x, ps); err != nil { return err } // Derive the Sum field. x.Sum = x.I + x.J return nil } func (x *CustomPropsExample) Save() ([]datastore.Property, error) { // Validate the Sum field. if x.Sum != x.I + x.J { return errors.New("CustomPropsExample has inconsistent sum") } // Save I and J as usual. The code below is equivalent to calling // "return datastore.SaveStruct(x)", but is done manually for // demonstration purposes. return []datastore.Property{ { Name: "I", Value: int64(x.I), }, { Name: "J", Value: int64(x.J), }, } } The *PropertyList type implements PropertyLoadSaver, and can therefore hold an arbitrary entity's contents. Queries Queries retrieve entities based on their properties or key's ancestry. Running a query yields an iterator of results: either keys or (key, entity) pairs. Queries are re-usable and it is safe to call Query.Run from concurrent goroutines. Iterators are not safe for concurrent use. Queries are immutable, and are either created by calling NewQuery, or derived from an existing query by calling a method like Filter or Order that returns a new query value. A query is typically constructed by calling NewQuery followed by a chain of zero or more such methods. These methods are: - Ancestor and Filter constrain the entities returned by running a query. - Order affects the order in which they are returned. - Project constrains the fields returned. - Distinct de-duplicates projected entities. - KeysOnly makes the iterator return only keys, not (key, entity) pairs. - Start, End, Offset and Limit define which sub-sequence of matching entities to return. Start and End take cursors, Offset and Limit take integers. Start and Offset affect the first result, End and Limit affect the last result. If both Start and Offset are set, then the offset is relative to Start. If both End and Limit are set, then the earliest constraint wins. Limit is relative to Start+Offset, not relative to End. As a special case, a negative limit means unlimited. Example code: type Widget struct { Description string Price int } func handle(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) q := datastore.NewQuery("Widget"). Filter("Price <", 1000). Order("-Price") b := new(bytes.Buffer) for t := q.Run(ctx); ; { var x Widget key, err := t.Next(&x) if err == datastore.Done { break } if err != nil { serveError(ctx, w, err) return } fmt.Fprintf(b, "Key=%v\nWidget=%#v\n\n", key, x) } w.Header().Set("Content-Type", "text/plain; charset=utf-8") io.Copy(w, b) } Transactions RunInTransaction runs a function in a transaction. Example code: type Counter struct { Count int } func inc(ctx context.Context, key *datastore.Key) (int, error) { var x Counter if err := datastore.Get(ctx, key, &x); err != nil && err != datastore.ErrNoSuchEntity { return 0, err } x.Count++ if _, err := datastore.Put(ctx, key, &x); err != nil { return 0, err } return x.Count, nil } func handle(w http.ResponseWriter, r *http.Request) { ctx := appengine.NewContext(r) var count int err := datastore.RunInTransaction(ctx, func(ctx context.Context) error { var err1 error count, err1 = inc(ctx, datastore.NewKey(ctx, "Counter", "singleton", 0, nil)) return err1 }, nil) if err != nil { serveError(ctx, w, err) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") fmt.Fprintf(w, "Count=%d", count) } Metadata The datastore package provides access to some of App Engine's datastore metadata. This metadata includes information about the entity groups, namespaces, entity kinds, and properties in the datastore, as well as the property representations for each property. Example code: func handle(w http.ResponseWriter, r *http.Request) { // Print all the kinds in the datastore, with all the indexed // properties (and their representations) for each. ctx := appengine.NewContext(r) kinds, err := datastore.Kinds(ctx) if err != nil { serveError(ctx, w, err) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") for _, kind := range kinds { fmt.Fprintf(w, "%s:\n", kind) props, err := datastore.KindProperties(ctx, kind) if err != nil { fmt.Fprintln(w, "\t(unable to retrieve properties)") continue } for p, rep := range props { fmt.Fprintf(w, "\t-%s (%s)\n", p, strings.Join(", ", rep)) } } } */ package datastore
{ "content_hash": "7bf87d0bd11323133f9458fdb356980b", "timestamp": "", "source": "github", "line_count": 351, "max_line_length": 89, "avg_line_length": 31.797720797720796, "alnum_prop": 0.7194695815787115, "repo_name": "nildev/prj-tpl-basic-api", "id": "0d1cb5ccef6a88ccd1213d830b3821f0e9ae98d8", "size": "11161", "binary": false, "copies": "36", "ref": "refs/heads/master", "path": "vendor/google.golang.org/appengine/datastore/doc.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "2291" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OODBDemo.Repositories; using OODBDemo.Entities; namespace OODBDemo { public partial class FormDiem : Form { private DiemRepository _diem = new DiemRepository(); private Kiemtraquyen kq = new Kiemtraquyen(); public FormDiem() { InitializeComponent(); } private void loadDataTable() { DataTable table = _diem.getTable(txtKeyword.Text); dgvListData.Columns.Clear(); dgvListData.DataSource = table; dgvListData.Columns["Masv"].HeaderText = "Mã SV"; dgvListData.Columns["Mamh"].HeaderText = "Mã MH"; dgvListData.Columns["Diem"].HeaderText = "Điểm"; dgvListData.Columns["Lanthu"].HeaderText = "Lần thứ"; dgvListData.Columns["Ghichu"].HeaderText = "Ghi chú"; dgvListData.Columns["Hocki"].HeaderText = "Học kì"; } private void frmMonHoc_Load(object sender, EventArgs e) { loadDataTable(); } private void btnAdd_Click(object sender, EventArgs e) { if (kq.kiemtraquyenuser(FormDangnhap.loginUsename, "diemsinhvien", "add") == true) { double diem; int lanthu; if (!double.TryParse(txtDiem.Text, out diem) || (diem < 0) || (diem > 10)) { MessageBox.Show("Nhập \"Điểm\" không hợp lệ"); return; } if (!int.TryParse(textLanthu.Text, out lanthu)) { MessageBox.Show("Nhập \"Lần thứ\" không hợp lệ"); return; } if (_diem.isValid(txtMaSV.Text, txtMaMonHoc.Text, diem, lanthu, textGhichu.Text, textHocki.Text)) { if (_diem.isExist(txtMaMonHoc.Text, txtMaSV.Text)) { MessageBox.Show("Mã môn học đã tồn tại."); return; } _diem.add(txtMaSV.Text, txtMaMonHoc.Text, diem, lanthu, textGhichu.Text, textHocki.Text); loadDataTable(); } else { MessageBox.Show("Vui lòng nhập dữ liệu."); } } else { MessageBox.Show("Bạn không có quyền thực hiện lệnh này"); } } private void btnEdit_Click(object sender, EventArgs e) { if (kq.kiemtraquyenuser(FormDangnhap.loginUsename, "diemsinhvien", "up") == true) { double diem; int lanthu; if (!double.TryParse(txtDiem.Text, out diem) || (diem < 0) || (diem > 10)) { MessageBox.Show("Nhập \"Điểm\" không hợp lệ"); return; } if (!int.TryParse(textLanthu.Text, out lanthu)) { MessageBox.Show("Nhập \"Lần thứ\" không hợp lệ"); return; } _diem.update(txtMaSV.Text, txtMaMonHoc.Text, diem, lanthu, textGhichu.Text, textHocki.Text); loadDataTable(); } else { MessageBox.Show("Bạn không có quyền thực hiện lệnh này"); } } private void btnDelete_Click(object sender, EventArgs e) { if (kq.kiemtraquyenuser(FormDangnhap.loginUsename, "diemsinhvien", "del") == true) { _diem.delete(txtMaMonHoc.Text, txtMaSV.Text); loadDataTable(); } else { MessageBox.Show("Bạn không có quyền thực hiện lệnh này"); } } private void dgvListData_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0) { txtMaSV.Text = dgvListData.Rows[e.RowIndex].Cells["Masv"].Value.ToString(); txtMaMonHoc.Text = dgvListData.Rows[e.RowIndex].Cells["Mamh"].Value.ToString(); txtDiem.Text = dgvListData.Rows[e.RowIndex].Cells["Diem"].Value.ToString(); textLanthu.Text = dgvListData.Rows[e.RowIndex].Cells["Lanthu"].Value.ToString(); textGhichu.Text = dgvListData.Rows[e.RowIndex].Cells["Ghichu"].Value.ToString(); textHocki.Text = dgvListData.Rows[e.RowIndex].Cells["Hocki"].Value.ToString(); } } private void dgvListData_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { dgvListData_RowHeaderMouseClick(sender, e); } private void btnImportExcel_Click(object sender, EventArgs e) { if (kq.kiemtraquyenuser(FormDangnhap.loginUsename, "diemsinhvien", "add") == true) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Nhập từ tập tin Excel"; ofd.Filter = "Excel file (*.xls, *.xlsx)|*.xls;*.xlsx"; DialogResult re = ofd.ShowDialog(); if (re == DialogResult.OK) { if (_diem.importFromExcel(ofd.FileName)) { loadDataTable(); } else { MessageBox.Show("Nhập từ tập tin thất bại. Vui lòng kiểm tra lại."); } } } else { MessageBox.Show("Bạn không có quyền thực hiện lệnh này"); } } private void btnExportExcel_Click(object sender, EventArgs e) { if (kq.kiemtraquyenuser(FormDangnhap.loginUsename, "diemsinhvien", "view") == true) { SaveFileDialog ofd = new SaveFileDialog(); ofd.Title = "Xuất tập tin Excel"; ofd.Filter = "Excel file (*.xls, *.xlsx)|*.xls;*.xlsx"; DialogResult re = ofd.ShowDialog(); if (re == DialogResult.OK) { if (_diem.exportFromExcel(dgvListData, ofd.FileName)) { MessageBox.Show("Xuất thành công."); } else { MessageBox.Show("Xuất thất bại."); } } } else { MessageBox.Show("Bạn không có quyền thực hiện lệnh này"); } } private void btnSearch_Click(object sender, EventArgs e) { if (kq.kiemtraquyenuser(FormDangnhap.loginUsename, "diemsinhvien", "view") == true) { loadDataTable(); } else { MessageBox.Show("Bạn không có quyền thực hiện lệnh này"); } } } }
{ "content_hash": "b1a01a2b0679156c5b1fbdd55ac65c6c", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 113, "avg_line_length": 35.377450980392155, "alnum_prop": 0.4875987252320909, "repo_name": "bs135/adb_coursework_oodb", "id": "11f2af037fe12db119c36ace694670d679de445f", "size": "7404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/OODB_Demo/Forms/FormDiem.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "87" }, { "name": "C#", "bytes": "89233" } ], "symlink_target": "" }
//// [apparentTypeSubtyping.ts] // subtype checks use the apparent type of the target type // S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S: class Base<U extends String> { x: U; } // is String (S) a subtype of U extends String (T)? Would only be true if we used the apparent type of U (T) class Derived<U> extends Base<string> { // error x: String; } class Base2 { x: String; static s: String; } // is U extends String (S) a subtype of String (T)? Apparent type of U is String so it succeeds class Derived2<U extends String> extends Base2 { // error because of the prototype's not matching, not because of the instance side x: U; } //// [apparentTypeSubtyping.js] // subtype checks use the apparent type of the target type // S is a subtype of a type T, and T is a supertype of S, if one of the following is true, where S' denotes the apparent type (section 3.8.1) of S: var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var Base = /** @class */ (function () { function Base() { } return Base; }()); // is String (S) a subtype of U extends String (T)? Would only be true if we used the apparent type of U (T) var Derived = /** @class */ (function (_super) { __extends(Derived, _super); function Derived() { return _super !== null && _super.apply(this, arguments) || this; } return Derived; }(Base)); var Base2 = /** @class */ (function () { function Base2() { } return Base2; }()); // is U extends String (S) a subtype of String (T)? Apparent type of U is String so it succeeds var Derived2 = /** @class */ (function (_super) { __extends(Derived2, _super); function Derived2() { return _super !== null && _super.apply(this, arguments) || this; } return Derived2; }(Base2));
{ "content_hash": "27b8daf194961d56e9bc4df0891856c4", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 147, "avg_line_length": 37.69230769230769, "alnum_prop": 0.6, "repo_name": "alexeagle/TypeScript", "id": "2e9987f1e0d8d17f3864176c659169962a718974", "size": "2450", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tests/baselines/reference/apparentTypeSubtyping.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "3710" }, { "name": "JavaScript", "bytes": "175" }, { "name": "PowerShell", "bytes": "2855" }, { "name": "Shell", "bytes": "47" }, { "name": "TypeScript", "bytes": "91618587" } ], "symlink_target": "" }
namespace More.ComponentModel { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Windows.Input; /// <summary> /// Defines the behavior of a selectable item. /// </summary> /// <typeparam name="T">The <see cref="Type">type</see> of value associated with the item.</typeparam> [ContractClass( typeof( ISelectableItemContract<> ) )] public interface ISelectableItem<out T> : INotifyPropertyChanged { /// <summary> /// Gets or sets a value indicating whether the item is selected. /// </summary> /// <value>A <see cref="Nullable{T}"/> object.</value> bool? IsSelected { get; set; } /// <summary> /// Gets the value of the item. /// </summary> /// <value>The value of the item.</value> T Value { get; } /// <summary> /// Gets a command that can be used to select the item. /// </summary> /// <value>An <see cref="ICommand"/> object.</value> [SuppressMessage( "Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Select", Justification = "This will not cause a cross language issues." )] ICommand Select { get; } /// <summary> /// Gets a command that can be used to unselect the item. /// </summary> /// <value>An <see cref="ICommand"/> object.</value> ICommand Unselect { get; } /// <summary> /// Occurs when the item is selected. /// </summary> event EventHandler Selected; /// <summary> /// Occurs when the item is unselected. /// </summary> event EventHandler Unselected; /// <summary> /// Occurs when the selected state of the item is indeterminate. /// </summary> event EventHandler Indeterminate; } }
{ "content_hash": "28109ed8173db76aea031f5b24f89550", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 177, "avg_line_length": 34.482142857142854, "alnum_prop": 0.5867426204039358, "repo_name": "commonsensesoftware/More", "id": "9c27776f90e42a5bdf5a192655b7bdbb9c00323f", "size": "1933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/More.UI/ComponentModel/ISelectableItem{T}.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4062358" }, { "name": "Smalltalk", "bytes": "19010" } ], "symlink_target": "" }
package org.apache.ojb.broker.platforms; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.apache.ojb.broker.PersistenceBroker; import org.apache.ojb.broker.metadata.FieldDescriptor; import org.apache.ojb.broker.util.sequence.AbstractSequenceManager; import org.apache.ojb.broker.util.sequence.SequenceManagerException; public class KualiMySQLSequenceManagerImpl extends AbstractSequenceManager { public KualiMySQLSequenceManagerImpl(PersistenceBroker broker) { super(broker); } @Override protected long getUniqueLong(FieldDescriptor arg0) throws SequenceManagerException { PersistenceBroker broker = getBrokerForClass(); Statement stmt = null; Long seqNumber = null; final String sequenceName = arg0.getSequenceName(); try { //FIXME: should we be closing this connection in a finally block? Connection c = broker.serviceConnectionManager().getConnection(); stmt = c.createStatement(); String sql = "INSERT INTO " + sequenceName + " VALUES (NULL);"; stmt.executeUpdate(sql); sql = "SELECT LAST_INSERT_ID()"; //FIXME: should we be closing this result set in a finally block? ResultSet rs = stmt.executeQuery(sql); if (rs != null) { rs.first(); seqNumber = rs.getLong(1); } } catch (Exception e) { throw new RuntimeException("Unable to execute for sequence name: " + sequenceName, e); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception e) { throw new RuntimeException("Unable to close statement for sequence name: " + sequenceName, e); } } return seqNumber; } }
{ "content_hash": "bde7e0308d01182fc77259675d9e18e5", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 98, "avg_line_length": 28.666666666666668, "alnum_prop": 0.7252141982864138, "repo_name": "sbower/kuali-rice-1", "id": "05ea130a09d525caa693af072891919299b3be02", "size": "2381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/framework/src/main/java/org/apache/ojb/broker/platforms/KualiMySQLSequenceManagerImpl.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. #config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "cats_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false config.secret_key_base = ENV['SECRET_KEY_BASE'] end
{ "content_hash": "9ca9c4defdc16e6759e1e49065afa6a7", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 102, "avg_line_length": 39.46739130434783, "alnum_prop": 0.7411181492701735, "repo_name": "fmip/cats-web", "id": "b9ac84b77fd3eb25c690c71fe286e2e62339dabb", "size": "3631", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "config/environments/production.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1766057" }, { "name": "CoffeeScript", "bytes": "145" }, { "name": "HTML", "bytes": "311235" }, { "name": "JavaScript", "bytes": "1833419" }, { "name": "Ruby", "bytes": "343096" }, { "name": "Shell", "bytes": "292" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hive.benchmark.vectorization; import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector; import org.apache.hadoop.hive.ql.exec.vector.expressions.ColAndCol; import org.apache.hadoop.hive.ql.exec.vector.expressions.ColOrCol; import org.apache.hadoop.hive.ql.exec.vector.expressions.IfExprLongColumnLongColumn; import org.apache.hadoop.hive.ql.exec.vector.expressions.NotCol; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; /** * This test measures the performance for vectorization. * <p/> * This test uses JMH framework for benchmarking. * You may execute this benchmark tool using JMH command line in different ways: * <p/> * To use the settings shown in the main() function, use: * $ java -cp target/benchmarks.jar org.apache.hive.benchmark.vectorization.VectorizedLogicBench * <p/> * To use the default settings used by JMH, use: * $ java -jar target/benchmarks.jar org.apache.hive.benchmark.vectorization.VectorizedLogicBench * <p/> * To specify different parameters, use: * - This command will use 10 warm-up iterations, 5 test iterations, and 2 forks. And it will * display the Average Time (avgt) in Microseconds (us) * - Benchmark mode. Available modes are: * [Throughput/thrpt, AverageTime/avgt, SampleTime/sample, SingleShotTime/ss, All/all] * - Output time unit. Available time units are: [m, s, ms, us, ns]. * <p/> * $ java -jar target/benchmarks.jar org.apache.hive.benchmark.vectorization.VectorizedLogicBench * -wi 10 -i 5 -f 2 -bm avgt -tu us */ @State(Scope.Benchmark) public class VectorizedLogicBench { public static class ColAndColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 2, getBooleanLongColumnVector(), getBooleanLongColumnVector()); expression = new ColAndCol(0, 1, 2); } } public static class ColAndRepeatingColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 2, getBooleanLongColumnVector(), getBooleanRepeatingLongColumnVector()); expression = new ColAndCol(0, 1, 2); } } public static class RepeatingColAndColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 2, getBooleanRepeatingLongColumnVector(), getBooleanLongColumnVector()); expression = new ColAndCol(0, 1, 2); } } public static class ColOrColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 2, getBooleanLongColumnVector(), getBooleanLongColumnVector()); expression = new ColOrCol(0, 1, 2); } } public static class ColOrRepeatingColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 2, getBooleanLongColumnVector(), getBooleanRepeatingLongColumnVector()); expression = new ColOrCol(0, 1, 2); } } public static class RepeatingColOrColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 2, getBooleanRepeatingLongColumnVector(), getBooleanLongColumnVector()); expression = new ColOrCol(0, 1, 2); } } public static class NotColBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 1, getBooleanLongColumnVector()); expression = new NotCol(0, 1); } } public static class IfExprLongColumnLongColumnBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 3, getBooleanLongColumnVector(), getLongColumnVector(), getLongColumnVector()); expression = new IfExprLongColumnLongColumn(0, 1, 2, 3); } } public static class IfExprRepeatingLongColumnLongColumnBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 3, getBooleanLongColumnVector(), getRepeatingLongColumnVector(), getLongColumnVector()); expression = new IfExprLongColumnLongColumn(0, 1, 2, 3); } } public static class IfExprLongColumnRepeatingLongColumnBench extends AbstractExpression { @Override public void setup() { rowBatch = buildRowBatch(new LongColumnVector(), 3, getBooleanLongColumnVector(), getLongColumnVector(), getRepeatingLongColumnVector()); expression = new IfExprLongColumnLongColumn(0, 1, 2, 3); } } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder().include(".*" + VectorizedLogicBench.class.getSimpleName() + ".*").build(); new Runner(opt).run(); } }
{ "content_hash": "2abcadd8186aac0b618ca639cf90c5b4", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 98, "avg_line_length": 38.57823129251701, "alnum_prop": 0.7270322694410157, "repo_name": "anishek/hive", "id": "bf2f4b4e53f5fb889f483c7652261ca81c4f0682", "size": "5671", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "itests/hive-jmh/src/main/java/org/apache/hive/benchmark/vectorization/VectorizedLogicBench.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "54376" }, { "name": "Batchfile", "bytes": "845" }, { "name": "C", "bytes": "28218" }, { "name": "C++", "bytes": "45308" }, { "name": "CSS", "bytes": "5157" }, { "name": "GAP", "bytes": "179697" }, { "name": "HTML", "bytes": "58711" }, { "name": "HiveQL", "bytes": "7603599" }, { "name": "Java", "bytes": "53025308" }, { "name": "JavaScript", "bytes": "43855" }, { "name": "M4", "bytes": "2276" }, { "name": "PHP", "bytes": "148097" }, { "name": "PLSQL", "bytes": "5261" }, { "name": "PLpgSQL", "bytes": "302587" }, { "name": "Perl", "bytes": "319842" }, { "name": "PigLatin", "bytes": "12333" }, { "name": "Python", "bytes": "408661" }, { "name": "Roff", "bytes": "5379" }, { "name": "SQLPL", "bytes": "409" }, { "name": "Shell", "bytes": "299497" }, { "name": "TSQL", "bytes": "2560163" }, { "name": "Thrift", "bytes": "144783" }, { "name": "XSLT", "bytes": "20199" }, { "name": "q", "bytes": "320552" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; namespace Ragyaiddo.Ef.BulkInsert.Extensions { internal static class TypeExtensions { public static object GetNonPublicFieldValue(this object obj, string propertyName) { if (obj == null) throw new ArgumentNullException(nameof(obj)); Type type = obj.GetType(); BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.NonPublic; while (type != null) { FieldInfo fieldInfo = type.GetField(propertyName, bindingAttr); if (fieldInfo != null) return fieldInfo.GetValue(obj); PropertyInfo propertyInfo = type.GetProperty(propertyName, bindingAttr); if (propertyInfo != null) return propertyInfo.GetValue(obj); type = type.BaseType; } throw new ArgumentOutOfRangeException($"Field {propertyName} not found in Type {obj.GetType().FullName}"); } public static string GetPrimaryKeyByConvention(this Type dataType) { return dataType.GetProperties().FirstOrDefault(p => { if (!p.Name.Equals("ID", StringComparison.OrdinalIgnoreCase)) return p.Name.Equals(dataType.Name + "ID", StringComparison.OrdinalIgnoreCase); return true; }).Name; } public static IEnumerable<string> GetPrimaryKeysByKeyAttribute(this Type dataType) { return dataType.GetProperties() .Where(p => p.CustomAttributes.Any(attr => attr.AttributeType == typeof(KeyAttribute))) .Select(x => x.Name); } } }
{ "content_hash": "1849a9289eed6c599c47e3d719ded8ba", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 118, "avg_line_length": 36.21568627450981, "alnum_prop": 0.6004331348132106, "repo_name": "ragyaiddo/Ef.BulkInsert", "id": "5543799ce275ad767bce302184b349d64c65a4a1", "size": "1849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ragyaiddo.Ef.BulkInsert/Extensions/TypeExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "39155" } ], "symlink_target": "" }
<?php namespace Anax\Comment; /** * To attach comments-flow to a page or some content. * */ class CommentsInSession implements \Anax\DI\IInjectionAware { use \Anax\DI\TInjectable; /** * Add a new comment. * * @param array $comment with all details. * * @return void */ public function add($comment, $pageKey) { $comments = $this->session->get("comments-{$pageKey}", []); $comments[] = $comment; $this->session->set("comments-{$pageKey}", $comments); } /** * Edit an existing comment. * * @param integer $id of the comment * @param array $comment with the edited comment (Timestamp and Ip will not be edited) * * @return void */ public function edit($id, $comment, $pageKey){ //Get the comment from the session $existingComments = $this->session->get("comments-{$pageKey}", []); //Edit the existing comment $existingComments[$id]['content'] = $comment['content']; $existingComments[$id]['name'] = $comment['name']; $existingComments[$id]['web'] = $comment['web']; $existingComments[$id]['mail'] = $comment['mail']; $this->session->set("comments-{$pageKey}", $existingComments); } /** * Delete an existing comment. * * @param integer $id of the comment to be deleted * @return void */ public function remove($id, $pageKey){ $existingComments = $this->session->get("comments-{$pageKey}", []); unset($existingComments[$id]); $existingComments = array_values($existingComments); $this->session->set("comments-{$pageKey}", $existingComments); } /** * Find and return all comments. * * @return array with all comments. */ public function findAll($pageKey) { return $this->session->get("comments-{$pageKey}", []); } /** * Find comment with id * * @return Array containing all fields of the comment */ public function findComment($id, $pageKey){ return $this->session->get("comments-{$pageKey}", [])[$id]; } /** * Delete all comments. * * @return void */ public function deleteAll($pageKey) { $this->session->set("comments-{$pageKey}", []); } }
{ "content_hash": "6ec6bef9dd114768c8b6c04da7e1c811", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 90, "avg_line_length": 25.02247191011236, "alnum_prop": 0.5958688819039066, "repo_name": "Lillfilly/moppetrim", "id": "8354cd8616a851671fde01a71194d7f8c4ccabbc", "size": "2227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Comment/CommentsInSession.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "488" }, { "name": "CSS", "bytes": "7416" }, { "name": "JavaScript", "bytes": "2718" }, { "name": "PHP", "bytes": "275859" }, { "name": "Shell", "bytes": "70" } ], "symlink_target": "" }
Public Class Negocios_PlanoPB Inherits System.Web.UI.Page #Region " Web Form Designer Generated Code " 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Protected WithEvents lblTitulo As System.Web.UI.WebControls.Label Protected WithEvents Label1 As System.Web.UI.WebControls.Label Protected WithEvents Label2 As System.Web.UI.WebControls.Label 'NOTE: The following placeholder declaration is required by the Web Form Designer. 'Do not delete or move it. Private designerPlaceholderDeclaration As System.Object Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here End Sub End Class
{ "content_hash": "f96910b50781cbf1a7b8c57be6df208c", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 105, "avg_line_length": 36.766666666666666, "alnum_prop": 0.7479601087941976, "repo_name": "mpeyrotc/govector", "id": "3fd140acec3d8b9a728d72bc354aff3c0d223a6a", "size": "1103", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "templates/Negocios_PlanoPB.aspx.vb", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "231345" }, { "name": "CSS", "bytes": "11873" }, { "name": "HTML", "bytes": "91490" }, { "name": "JavaScript", "bytes": "3168" }, { "name": "Python", "bytes": "24909" }, { "name": "Visual Basic", "bytes": "20448" } ], "symlink_target": "" }
package hyweb.jo.convert; import hyweb.jo.log.JOLogger; /** * @author William */ public class FConvertInt extends FConvert<Integer,Object,Integer> { @Override public Integer exec(Object o,Integer dv ) throws Exception { try { if (o instanceof Number) { return ((Number) o).intValue(); } else if (o instanceof String) { String str = ((String) o).trim(); return str.length() > 0 ? Integer.parseInt(str) : null; } } catch (Exception e) { //log.warn("Can't check value : " + o); JOLogger.warn("Can't convert " + o + " to int."); } return dv; } }
{ "content_hash": "3b4276a7d4a656eff5d170e763c34d83", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 71, "avg_line_length": 27.96153846153846, "alnum_prop": 0.5075653370013755, "repo_name": "williamyyj/mjo2", "id": "e01dd8b13f6b6e4d612aad7851b551be664dad46", "size": "727", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/hyweb/jo/convert/FConvertInt.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1120312" } ], "symlink_target": "" }
package org.assertj.core.internal.classes; import static org.assertj.core.error.ShouldHaveAnnotations.shouldHaveAnnotations; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.util.FailureMessages.actualIsNull; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.ClassesBaseTest; import org.assertj.core.util.Sets; import org.junit.Test; /** * Tests for * <code>{@link org.assertj.core.internal.Classes#assertContainsAnnotations(org.assertj.core.api.AssertionInfo, Class, Class[])}</code> * . * * @author William Delanoue */ public class Classes_assertContainsAnnotation_Test extends ClassesBaseTest { @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) private static @interface MyAnnotation { } @MyAnnotation private static class AnnotatedClass { } @SuppressWarnings("unchecked") @Test public void should_fail_if_actual_is_null() { actual = null; thrown.expectAssertionError(actualIsNull()); classes.assertContainsAnnotations(someInfo(), actual, Override.class); } @SuppressWarnings("unchecked") @Test public void should_fail_if_expected_has_null_value() { actual = AssertionInfo.class; thrown.expectNullPointerException("The class to compare actual with should not be null"); classes.assertContainsAnnotations(someInfo(), actual, Override.class, null, Deprecated.class); } @SuppressWarnings("unchecked") @Test public void should_pass_if_expected_is_empty() { actual = AssertionInfo.class; classes.assertContainsAnnotations(someInfo(), actual); } @SuppressWarnings("unchecked") @Test public void should_pass_if_actual_have_annotation() { actual = AnnotatedClass.class; classes.assertContainsAnnotations(someInfo(), actual, MyAnnotation.class); } @SuppressWarnings("unchecked") @Test() public void should_fail_if_actual_does_not_contains_an_annotation() { actual = AnnotatedClass.class; Class<Annotation> expected[] = new Class[] { Override.class, Deprecated.class, MyAnnotation.class }; thrown.expectAssertionError(shouldHaveAnnotations(actual, Sets.<Class<? extends Annotation>> newLinkedHashSet(expected), Sets.<Class<? extends Annotation>> newLinkedHashSet(Override.class, Deprecated.class))); classes.assertContainsAnnotations(someInfo(), actual, expected); } }
{ "content_hash": "dd684d55963db58e8c9fd3a1ed8a6729", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 135, "avg_line_length": 35.21518987341772, "alnum_prop": 0.7063263838964774, "repo_name": "ChrisA89/assertj-core", "id": "2d38051b80d4e9e4dfd378b9fe11d4df5afa2506", "size": "3389", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/assertj/core/internal/classes/Classes_assertContainsAnnotation_Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9353819" }, { "name": "Shell", "bytes": "40820" } ], "symlink_target": "" }
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { NgDaterangepickerComponent } from './ng-daterangepicker.component'; describe('NgDaterangepickerComponent', () => { let component: NgDaterangepickerComponent; let fixture: ComponentFixture<NgDaterangepickerComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ NgDaterangepickerComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(NgDaterangepickerComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "content_hash": "d2d0512a23077546586e4245c0be4c2b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 76, "avg_line_length": 28.24, "alnum_prop": 0.7053824362606232, "repo_name": "jkuri/ng-daterangepicker", "id": "5e3c810ff28debe22c46ca32f534337d54a1dba5", "size": "706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/ng-daterangepicker/ng-daterangepicker.component.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9413" }, { "name": "HTML", "bytes": "11964" }, { "name": "JavaScript", "bytes": "1645" }, { "name": "TypeScript", "bytes": "15275" } ], "symlink_target": "" }
package srp.db.model; import java.util.List; import java.util.Map; import net.sf.json.JSONException; import net.sf.json.JSONObject; public class Product extends CommonModel { private String id; private String name; private String brand; private String category; private List<String> imgurls; private Map<String, String> attributes; private int favourcount; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public List<String> getImgurls() { return imgurls; } public void setImgurls(List<String> imgurls) { this.imgurls = imgurls; } public Map<String, String> getAttributes() { return attributes; } public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; } public int getFavourcount() { return favourcount; } public void setFavourcount(int favourcount) { this.favourcount = favourcount; } public static Product parseFromJson(String jsonStr) { try { JSONObject object = JSONObject.fromObject(jsonStr); return parseFromJson(object); } catch (JSONException e) { return null; } } public static Product parseFromJson(JSONObject object) { if (object.containsKey("_id")) { Product product = new Product(); product.setId(parseString(object, "_id")); product.setName(parseString(object, "name")); product.setBrand(parseString(object, "brand")); product.setCategory(parseString(object, "category")); product.setImgurls(parseList(object, "imgurls")); product.setAttributes(parseMap(object, "attributes")); product.setFavourcount(parseInt(object, "favourcount")); return product; } else { return null; } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("id:"); builder.append(getId()); builder.append("name:"); builder.append(getName()); builder.append("brand:"); builder.append(getBrand()); return builder.toString(); } }
{ "content_hash": "b1fba721bb675d4e0a4f9b4692799e23", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 60, "avg_line_length": 20.765765765765767, "alnum_prop": 0.7084598698481562, "repo_name": "newpasung/srpdb", "id": "b49aad57b6d8f731e413828c1a43749d0d3f404b", "size": "2305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/srp/db/model/Product.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "53924" } ], "symlink_target": "" }
<!doctype html> <title>Animating opacity, transform, filter, backdrop-filter should establish a stacking context.</title> <link rel="help" href="https://drafts.csswg.org/web-animations-1/#side-effects-section"> <style> .shouldStack { position: absolute; width: 150px; height: 50px; background-color: red; } .shouldNotStack { position: absolute; width: 150px; height: 50px; background-color: green; } .child { position: relative; top: 0px; left: 0px; width: 150px; height: 50px; background-color: green; z-index: -1; } .shouldNotStack .child { background-color: red; } #animatedOpacity { /* Use a large duration so animation is effectively invisible. */ animation-duration: 100000s; animation-name: opacity_frames; top: 0px; } @keyframes opacity_frames { to { opacity: 0; } } #animatedTransform { animation-duration: 100000s; animation-name: transform_frames; top: 100px; } @keyframes transform_frames { to { transform: translateX(10px); } } #animatedFilter { animation-duration: 100000s; animation-name: filter_frames; top: 200px; } @keyframes filter_frames { to { filter: grayscale(50%); } } #animatedBackdrop { animation-duration: 100000s; animation-name: backdrop_frames; top: 300px; } @keyframes backdrop_frames { to { backdrop-filter: grayscale(50%); } } #animatedLeft { animation-duration: 100000s; animation-name: left_frames; top: 400px; } @keyframes left_frames { to { left: 10px; } } </style> <div id="animatedOpacity" class="shouldStack"> <div class="child">animated opacity</div> </div> <div id="animatedTransform" class="shouldStack"> <div class="child">animated transform</div> </div> <div id="animatedFilter" class="shouldStack"> <div class="child">animated filter</div> </div> <div id="animatedBackdrop" class="shouldStack"> <div class="child">animated backdrop-filter</div> </div> <div id="animatedLeft" class="shouldNotStack"> <div class="child">animated left</div> </div>
{ "content_hash": "2d7469660f9cf7d3d51259a37900e6b6", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 105, "avg_line_length": 17.46551724137931, "alnum_prop": 0.6880552813425469, "repo_name": "ric2b/Vivaldi-browser", "id": "a94cde4069cfc04eb7b0a715d4c19b8b1dcd8e9f", "size": "2026", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "chromium/third_party/blink/web_tests/compositing/animation/animations-establish-stacking-context.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
from oslo.serialization import jsonutils from nova import db from nova import objects from nova.objects import base from nova.objects import fields from nova.openstack.common import log as logging from nova import utils LOG = logging.getLogger(__name__) # TODO(berrange): Remove NovaObjectDictCompat class PciDevice(base.NovaPersistentObject, base.NovaObject, base.NovaObjectDictCompat): """Object to represent a PCI device on a compute node. PCI devices are managed by the compute resource tracker, which discovers the devices from the hardware platform, claims, allocates and frees devices for instances. The PCI device information is permanently maintained in a database. This makes it convenient to get PCI device information, like physical function for a VF device, adjacent switch IP address for a NIC, hypervisor identification for a PCI device, etc. It also provides a convenient way to check device allocation information for administrator purposes. A device can be in available/claimed/allocated/deleted/removed state. A device is available when it is discovered.. A device is claimed prior to being allocated to an instance. Normally the transition from claimed to allocated is quick. However, during a resize operation the transition can take longer, because devices are claimed in prep_resize and allocated in finish_resize. A device becomes removed when hot removed from a node (i.e. not found in the next auto-discover) but not yet synced with the DB. A removed device should not be allocated to any instance, and once deleted from the DB, the device object is changed to deleted state and no longer synced with the DB. Filed notes:: | 'dev_id': | Hypervisor's identification for the device, the string format | is hypervisor specific | 'extra_info': | Device-specific properties like PF address, switch ip address etc. """ # Version 1.0: Initial version # Version 1.1: String attributes updated to support unicode # Version 1.2: added request_id field VERSION = '1.2' fields = { 'id': fields.IntegerField(), # Note(yjiang5): the compute_node_id may be None because the pci # device objects are created before the compute node is created in DB 'compute_node_id': fields.IntegerField(nullable=True), 'address': fields.StringField(), 'vendor_id': fields.StringField(), 'product_id': fields.StringField(), 'dev_type': fields.StringField(), 'status': fields.StringField(), 'dev_id': fields.StringField(nullable=True), 'label': fields.StringField(nullable=True), 'instance_uuid': fields.StringField(nullable=True), 'request_id': fields.StringField(nullable=True), 'extra_info': fields.DictOfStringsField(), } def obj_make_compatible(self, primitive, target_version): target_version = utils.convert_version_to_tuple(target_version) if target_version < (1, 2) and 'request_id' in primitive: del primitive['request_id'] def update_device(self, dev_dict): """Sync the content from device dictionary to device object. The resource tracker updates the available devices periodically. To avoid meaningless syncs with the database, we update the device object only if a value changed. """ # Note(yjiang5): status/instance_uuid should only be updated by # functions like claim/allocate etc. The id is allocated by # database. The extra_info is created by the object. no_changes = ('status', 'instance_uuid', 'id', 'extra_info') map(lambda x: dev_dict.pop(x, None), [key for key in no_changes]) for k, v in dev_dict.items(): if k in self.fields.keys(): self[k] = v else: # Note (yjiang5) extra_info.update does not update # obj_what_changed, set it explicitely extra_info = self.extra_info extra_info.update({k: v}) self.extra_info = extra_info def __init__(self, *args, **kwargs): super(PciDevice, self).__init__(*args, **kwargs) self.obj_reset_changes() self.extra_info = {} @staticmethod def _from_db_object(context, pci_device, db_dev): for key in pci_device.fields: if key != 'extra_info': pci_device[key] = db_dev[key] else: extra_info = db_dev.get("extra_info") pci_device.extra_info = jsonutils.loads(extra_info) pci_device._context = context pci_device.obj_reset_changes() return pci_device @base.remotable_classmethod def get_by_dev_addr(cls, context, compute_node_id, dev_addr): db_dev = db.pci_device_get_by_addr( context, compute_node_id, dev_addr) return cls._from_db_object(context, cls(), db_dev) @base.remotable_classmethod def get_by_dev_id(cls, context, id): db_dev = db.pci_device_get_by_id(context, id) return cls._from_db_object(context, cls(), db_dev) @classmethod def create(cls, dev_dict): """Create a PCI device based on hypervisor information. As the device object is just created and is not synced with db yet thus we should not reset changes here for fields from dict. """ pci_device = cls() pci_device.update_device(dev_dict) pci_device.status = 'available' return pci_device @base.remotable def save(self, context): if self.status == 'removed': self.status = 'deleted' db.pci_device_destroy(context, self.compute_node_id, self.address) elif self.status != 'deleted': updates = self.obj_get_changes() if 'extra_info' in updates: updates['extra_info'] = jsonutils.dumps(updates['extra_info']) if updates: db_pci = db.pci_device_update(context, self.compute_node_id, self.address, updates) self._from_db_object(context, self, db_pci) class PciDeviceList(base.ObjectListBase, base.NovaObject): # Version 1.0: Initial version # PciDevice <= 1.1 # Version 1.1: PciDevice 1.2 VERSION = '1.1' fields = { 'objects': fields.ListOfObjectsField('PciDevice'), } child_versions = { '1.0': '1.1', # NOTE(danms): PciDevice was at 1.1 before we added this '1.1': '1.2', } def __init__(self, *args, **kwargs): super(PciDeviceList, self).__init__(*args, **kwargs) self.objects = [] self.obj_reset_changes() @base.remotable_classmethod def get_by_compute_node(cls, context, node_id): db_dev_list = db.pci_device_get_all_by_node(context, node_id) return base.obj_make_list(context, cls(context), objects.PciDevice, db_dev_list) @base.remotable_classmethod def get_by_instance_uuid(cls, context, uuid): db_dev_list = db.pci_device_get_all_by_instance_uuid(context, uuid) return base.obj_make_list(context, cls(context), objects.PciDevice, db_dev_list)
{ "content_hash": "3821577addf20e79398d4a2c11e5bd9a", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 78, "avg_line_length": 38.45077720207254, "alnum_prop": 0.6292952432286754, "repo_name": "silenceli/nova", "id": "53e0a840cdd47badc43846e7fb0dc3710782a689", "size": "8054", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "nova/objects/pci_device.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "15235414" }, { "name": "Shell", "bytes": "21613" } ], "symlink_target": "" }
<p>安装Redis</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code>http://www.redis.NET.cn/download $ wget http://download.redis.io/releases/redis-3.0.6.tar.gz $ tar xzf redis-3.0.6.tar.gz $ cd redis-3.0.6 $ make #如果make失败,请安装gcc yum install gcc 重新解压安装 </code></pre> </div> <p>使用:</p> <p>二进制文件是编译完成后在src目录下. 运行如下:</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code> $ src/redis-server </code></pre> </div> <p>你能使用Redis的内置客户端进行进行redis代码的编写:</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code> $ src/redis-cli redis&gt; set foo bar OK redis&gt; get foo "bar" </code></pre> </div> <p>PHP 使用 redis</p> <p>下载地址:https://github.com/phpredis/phpredis/releases (最高版本)</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code> $ wget https://github.com/phpredis/phpredis/archive/2.2.7.tar.gz $ tar zxvf 2.2.7.tar.gz $ cd phpredis-2.2.7 # 进入 phpredis 目录 $ /usr/bin/phpize # php安装后的路径 (如果不成功,请安装php-devel yum install php-devel ) $ ./configure --with-php-config=/usr/bin/php-config $ make <span class="err">&amp;&amp;</span> make install </code></pre> </div> <p>修改php.ini文件</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code>vi /etc/php.ini </code></pre> </div> <p>添加</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code>extension=redis.so </code></pre> </div> <p>重启apache</p> <div class="language-php highlighter-rouge"><pre class="highlight"><code>systemctl restart httpd.service #重启apache </code></pre> </div>
{ "content_hash": "903f12074d4c2a81d0ecb92a8bf71cc1", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 138, "avg_line_length": 32.03921568627451, "alnum_prop": 0.6676866585067319, "repo_name": "1097630296/1097630296.github.io", "id": "6ce3be77d4db8e7921f2b3f429ab48bc3f6f0db0", "size": "1828", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/_site/2012-06-11-centos.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29971" }, { "name": "HTML", "bytes": "1219530" }, { "name": "JavaScript", "bytes": "3554" }, { "name": "Ruby", "bytes": "2083" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html ng-app="BBAdminEventsMockE2E"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="/bookingbug-angular.css" media="screen" /> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"> <script src="/bookingbug-angular.js"></script> <title>BookingBug</title> </head> <body event-group-table admin_email="[email protected]" admin_password="oNSOJh" company_id="123" api_url="http://www.bookingbug.com"> </body> </html>
{ "content_hash": "5340831675c0155e993260bdad1b6c84", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 98, "avg_line_length": 43, "alnum_prop": 0.6905187835420393, "repo_name": "Bogdan-p/bookingbug-angular", "id": "01b72ad36cc280710abc5dbd54bd074e85336c43", "size": "559", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/event_group_table.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "337629" }, { "name": "CoffeeScript", "bytes": "907989" }, { "name": "HTML", "bytes": "144966" }, { "name": "JavaScript", "bytes": "41762" } ], "symlink_target": "" }
http://ian-kinner.github.io ## How to create a repository on github, and clone it to your local machine To create a new repository, click the repository tab, then click the "new" button. Here you will enter a name for your new repository, choose whether it will be public or private, and set a license type (pick MIT by default if you want one). Then click "create repository," and it is created. To then clone it to your local machine, go to that repository on github, copy the URL in the header section, and from your local machine (assuming everything is setup and working), run the command "git clone [URL]" - this will pull a copy of the guthub repository onto the local computer so that files can be easily modified. ## What open source means Open source means that the source code for a software package is available to view or modify. Open source software usually is provided under the terms of a certain license. This license specifies what can legally be done with the source code, and is typically pretty liberal. ## What I think about open source I have been a fan of open source software since I knew what it was, beginning with my first Slackware Linux install in 1995. I have also actively contributed to open source projects over the years. I think it is the logical evolution of software development, where people with ideas for improvement are able to implement those ideas and contribute to the advancement of the code. I think it's brilliant for most purposes. ## Assess the importance of using licenses Using a license might be important. If you want your code to be open source, and remain open source, you need to choose an appropriate license. Without a license, you leave your code as public domain code which allows someone to take your code and do anything with it that they please, including turning it into a closed-source project and profitting from it, giving you no credit or share. Ultimately, the code you create it yours to do with as you please, so license it in a manner in which you see fit. ## What concepts were solidified in the challenge? Did you have any "aha" ## moments? What did you struggle with? I'm still not 100% with the merging process from my working repository to the master to the origin. I can fumble around with the commands a couple times and get it working properly. I learned that the ability to delete the working branch is a good indicator that all my changes have made it up to the github repository. Considering I just started using git this afternoon, I'm feeling pretty good about it though. # Did you find any resources on your own that helped you better understand a # topic? If so, please list it. I noticed that I spelled "reflections" incorrectly as "relfections" for the filename in the previous section. I used google to figure out how to rename a file in a repository using the "git mv" command. It did what I needed it to do, but I think when it renamed the file, the commit log for the original got wiped. I'll pay closer attention next time I run into the situation. The URL that told me about "git mv" was: http://www.patrick-wied.at/blog/rename-files-and-folders-with-git
{ "content_hash": "c336bb9ef011199500a5298fceb196d8", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 82, "avg_line_length": 51.62903225806452, "alnum_prop": 0.7747578881599501, "repo_name": "ian-kinner/phase-0", "id": "1aaf873b82b8c83d01e3a249c0a93c658f92e0f2", "size": "3312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "week-1/my-website-1-reflection.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5048" }, { "name": "HTML", "bytes": "24798" }, { "name": "JavaScript", "bytes": "40646" }, { "name": "Ruby", "bytes": "131033" } ], "symlink_target": "" }
@class AutocompleteTextField; class CommandUpdater; class ContentSettingDecoration; class EVBubbleDecoration; class KeywordHintDecoration; class LocationBarDecoration; class LocationBarViewMacBrowserTest; class LocationIconDecoration; class PageActionDecoration; class PlusDecoration; class Profile; class SearchTokenDecoration; class SelectedKeywordDecoration; class SeparatorDecoration; class StarDecoration; class ToolbarModel; class ZoomDecoration; class ZoomDecorationTest; // A C++ bridge class that represents the location bar UI element to // the portable code. Wires up an OmniboxViewMac instance to // the location bar text field, which handles most of the work. class LocationBarViewMac : public LocationBar, public LocationBarTesting, public OmniboxEditController, public content::NotificationObserver { public: LocationBarViewMac(AutocompleteTextField* field, CommandUpdater* command_updater, ToolbarModel* toolbar_model, Profile* profile, Browser* browser); virtual ~LocationBarViewMac(); // Overridden from LocationBar: virtual void ShowFirstRunBubble() OVERRIDE; virtual void SetInstantSuggestion( const InstantSuggestion& suggestion) OVERRIDE; virtual string16 GetInputString() const OVERRIDE; virtual WindowOpenDisposition GetWindowOpenDisposition() const OVERRIDE; virtual content::PageTransition GetPageTransition() const OVERRIDE; virtual void AcceptInput() OVERRIDE; virtual void FocusLocation(bool select_all) OVERRIDE; virtual void FocusSearch() OVERRIDE; virtual void UpdateContentSettingsIcons() OVERRIDE; virtual void UpdatePageActions() OVERRIDE; virtual void InvalidatePageActions() OVERRIDE; virtual void UpdateOpenPDFInReaderPrompt() OVERRIDE; virtual void SaveStateToContents(content::WebContents* contents) OVERRIDE; virtual void Revert() OVERRIDE; virtual const OmniboxView* GetLocationEntry() const OVERRIDE; virtual OmniboxView* GetLocationEntry() OVERRIDE; virtual LocationBarTesting* GetLocationBarForTesting() OVERRIDE; // Overridden from LocationBarTesting: virtual int PageActionCount() OVERRIDE; virtual int PageActionVisibleCount() OVERRIDE; virtual ExtensionAction* GetPageAction(size_t index) OVERRIDE; virtual ExtensionAction* GetVisiblePageAction(size_t index) OVERRIDE; virtual void TestPageActionPressed(size_t index) OVERRIDE; virtual void TestActionBoxMenuItemSelected(int command_id) OVERRIDE; virtual bool GetBookmarkStarVisibility() OVERRIDE; // Set/Get the editable state of the field. void SetEditable(bool editable); bool IsEditable(); // Set the starred state of the bookmark star. void SetStarred(bool starred); // Set (or resets) the icon image resource for the action box plus decoration. void ResetActionBoxIcon(); void SetActionBoxIcon(int image_id); // Happens when the zoom changes for the active tab. |can_show_bubble| is // false when the change in zoom for the active tab wasn't an explicit user // action (e.g. switching tabs, creating a new tab, creating a new browser). // Additionally, |can_show_bubble| will only be true when the bubble wouldn't // be obscured by other UI (wrench menu) or redundant (+/- from wrench). void ZoomChangedForActiveTab(bool can_show_bubble); // Get the point in window coordinates on the star for the bookmark bubble to // aim at. NSPoint GetBookmarkBubblePoint() const; // Get the point in window coordinates on the Action Box icon for // anchoring its bubbles. NSPoint GetActionBoxAnchorPoint() const; // Get the point in window coordinates in the security icon at which the page // info bubble aims. NSPoint GetPageInfoBubblePoint() const; // When any image decorations change, call this to ensure everything is // redrawn and laid out if necessary. void OnDecorationsChanged(); // Updates the location bar. Resets the bar's permanent text and // security style, and if |should_restore_state| is true, restores // saved state from the tab (for tab switching). void Update(const content::WebContents* tab, bool should_restore_state); // Layout the various decorations which live in the field. void Layout(); // Re-draws |decoration| if it's already being displayed. void RedrawDecoration(LocationBarDecoration* decoration); // Sets preview_enabled_ for the PageActionImageView associated with this // |page_action|. If |preview_enabled|, the location bar will display the // PageAction icon even if it has not been activated by the extension. // This is used by the ExtensionInstalledBubble to preview what the icon // will look like for the user upon installation of the extension. void SetPreviewEnabledPageAction(ExtensionAction* page_action, bool preview_enabled); // Retrieve the frame for the given |page_action|. NSRect GetPageActionFrame(ExtensionAction* page_action); // Return |page_action|'s info-bubble point in window coordinates. // This function should always be called with a visible page action. // If |page_action| is not a page action or not visible, NOTREACHED() // is called and this function returns |NSZeroPoint|. NSPoint GetPageActionBubblePoint(ExtensionAction* page_action); // Get the blocked-popup content setting's frame in window // coordinates. Used by the blocked-popup animation. Returns // |NSZeroRect| if the relevant content setting decoration is not // visible. NSRect GetBlockedPopupRect() const; // OmniboxEditController: virtual void OnAutocompleteAccept( const GURL& url, WindowOpenDisposition disposition, content::PageTransition transition, const GURL& alternate_nav_url) OVERRIDE; virtual void OnChanged() OVERRIDE; virtual void OnSelectionBoundsChanged() OVERRIDE; virtual void OnInputInProgress(bool in_progress) OVERRIDE; virtual void OnKillFocus() OVERRIDE; virtual void OnSetFocus() OVERRIDE; virtual gfx::Image GetFavicon() const OVERRIDE; virtual string16 GetTitle() const OVERRIDE; virtual InstantController* GetInstant() OVERRIDE; virtual content::WebContents* GetWebContents() const OVERRIDE; NSImage* GetKeywordImage(const string16& keyword); AutocompleteTextField* GetAutocompleteTextField() { return field_; } // content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; Browser* browser() const { return browser_; } ToolbarModel* toolbar_model() const { return toolbar_model_; } private: friend LocationBarViewMacBrowserTest; friend ZoomDecorationTest; // Posts |notification| to the default notification center. void PostNotification(NSString* notification); // Return the decoration for |page_action|. PageActionDecoration* GetPageActionDecoration(ExtensionAction* page_action); // Clear the page-action decorations. void DeletePageActionDecorations(); void OnEditBookmarksEnabledChanged(); // Re-generate the page-action decorations from the profile's // extension service. void RefreshPageActionDecorations(); // Updates visibility of the content settings icons based on the current // tab contents state. bool RefreshContentSettingsDecorations(); void ShowFirstRunBubbleInternal(); // Checks if the bookmark star should be enabled or not. bool IsStarEnabled(); // Updates the zoom decoration in the omnibox with the current zoom level. void UpdateZoomDecoration(); // Ensures the star decoration is visible or hidden, as required. void UpdateStarDecorationVisibility(); // Ensures the plus decoration is visible or hidden, as required. void UpdatePlusDecorationVisibility(); // Gets the current search provider name. string16 GetSearchProviderName() const; scoped_ptr<OmniboxViewMac> omnibox_view_; CommandUpdater* command_updater_; // Weak, owned by Browser. AutocompleteTextField* field_; // owned by tab controller // When we get an OnAutocompleteAccept notification from the autocomplete // edit, we save the input string so we can give it back to the browser on // the LocationBar interface via GetInputString(). string16 location_input_; // The user's desired disposition for how their input should be opened. WindowOpenDisposition disposition_; // A decoration that shows an icon to the left of the address. scoped_ptr<LocationIconDecoration> location_icon_decoration_; // A decoration that shows the search provider being used. scoped_ptr<SearchTokenDecoration> search_token_decoration_; // A decoration that shows the keyword-search bubble on the left. scoped_ptr<SelectedKeywordDecoration> selected_keyword_decoration_; // A decoration used to draw a separator between other decorations. scoped_ptr<SeparatorDecoration> separator_decoration_; // A decoration that shows a lock icon and ev-cert label in a bubble // on the left. scoped_ptr<EVBubbleDecoration> ev_bubble_decoration_; // Action "plus" button right of bookmark star. scoped_ptr<PlusDecoration> plus_decoration_; // Bookmark star right of page actions. scoped_ptr<StarDecoration> star_decoration_; // A zoom icon at the end of the omnibox, which shows at non-standard zoom // levels. scoped_ptr<ZoomDecoration> zoom_decoration_; // The installed page actions. std::vector<ExtensionAction*> page_actions_; // Decorations for the installed Page Actions. ScopedVector<PageActionDecoration> page_action_decorations_; // The content blocked decorations. ScopedVector<ContentSettingDecoration> content_setting_decorations_; // Keyword hint decoration displayed on the right-hand side. scoped_ptr<KeywordHintDecoration> keyword_hint_decoration_; Profile* profile_; Browser* browser_; ToolbarModel* toolbar_model_; // Weak, owned by Browser. // The transition type to use for the navigation. content::PageTransition transition_; // Used to register for notifications received by NotificationObserver. content::NotificationRegistrar registrar_; // Used to schedule a task for the first run info bubble. base::WeakPtrFactory<LocationBarViewMac> weak_ptr_factory_; // Used to change the visibility of the star decoration. BooleanPrefMember edit_bookmarks_enabled_; DISALLOW_COPY_AND_ASSIGN(LocationBarViewMac); }; #endif // CHROME_BROWSER_UI_COCOA_LOCATION_BAR_LOCATION_BAR_VIEW_MAC_H_
{ "content_hash": "4ae56d578c251b82c6400ffb47d19c04", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 80, "avg_line_length": 38.56727272727273, "alnum_prop": 0.7549500282858759, "repo_name": "plxaye/chromium", "id": "edf73133b326148c06166f7a834e5b4b4dc75641", "size": "11467", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/chrome/browser/ui/cocoa/location_bar/location_bar_view_mac.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1176633" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "75195981" }, { "name": "C#", "bytes": "36335" }, { "name": "C++", "bytes": "172360762" }, { "name": "CSS", "bytes": "740648" }, { "name": "Dart", "bytes": "12620" }, { "name": "Emacs Lisp", "bytes": "12454" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "3671513" }, { "name": "JavaScript", "bytes": "16204541" }, { "name": "Max", "bytes": "39069" }, { "name": "Mercury", "bytes": "10299" }, { "name": "Objective-C", "bytes": "1133728" }, { "name": "Objective-C++", "bytes": "5771619" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "166372" }, { "name": "Python", "bytes": "11650532" }, { "name": "Ragel in Ruby Host", "bytes": "3641" }, { "name": "Rebol", "bytes": "262" }, { "name": "Ruby", "bytes": "14575" }, { "name": "Shell", "bytes": "1426780" }, { "name": "Tcl", "bytes": "277077" }, { "name": "TeX", "bytes": "43554" }, { "name": "VimL", "bytes": "4953" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "14650" } ], "symlink_target": "" }
'use strict'; const TaskClass = require('./-base'); class DevicesTask extends TaskClass { thermostatTable(thermostats) { var table = this.ui.createTable({ head: ['ID', 'Name', 'State', 'Mode', 'Humidity', 'Target Temp.', 'Target Temp. Low', 'Target Temp. High'].map(function(heading) { return this.ui.color('blue', heading); }, this) }); Object.keys(thermostats).map(function(key) { return thermostats[key]; }).map(function(thermostat) { return [ thermostat.device_id, thermostat.name, thermostat.hvac_state, thermostat.hvac_mode, thermostat.humidity, thermostat.target_temperature_f, thermostat.target_temperature_low_f, thermostat.target_temperature_high_f ]; }).forEach(function(thermostat) { table.push(thermostat); }); this.ui.writeLine(table.toString()); } alarmTable(alarms) { var table = this.ui.createTable({ head: ['ID', 'Name', 'Battery Health', 'Smoke State', 'CO State', 'Online'].map(function(heading) { return this.ui.color('blue', heading); }, this) }); Object.keys(alarms).map(function(key) { return alarms[key]; }).map(function(alarm) { return [ alarm.device_id, alarm.name, alarm.battery_health, alarm.smoke_alarm_state, alarm.co_alarm_state, alarm.is_online ]; }).forEach(function(alarm) { table.push(alarm); }); this.ui.writeLine(table.toString()); } run(options) { const ui = this.ui; return this.app.api.device.index().then(function(res) { if (options.verbose) { return ui.writeLine(res); } if (res.thermostats) { this.thermostatTable(res.thermostats); } if (res.smoke_co_alarms) { this.alarmTable(res.smoke_co_alarms); } }.bind(this)); } } module.exports = DevicesTask;
{ "content_hash": "46c6ad8adb7f380bf563244a5ba068a7", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 136, "avg_line_length": 25.272727272727273, "alnum_prop": 0.5904419321685509, "repo_name": "cwarden/nest-cli", "id": "29db0f4cc641ea3936f32cc7e1ba384df79d77f8", "size": "1946", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tasks/devices.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26183" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.kie.workbench</groupId> <artifactId>kie-wb-common-cli-tools</artifactId> <version>7.54.0-SNAPSHOT</version> </parent> <artifactId>kie-wb-common-cli-project-migration</artifactId> <name>KIE Workbench Common CLI Project Migration</name> <dependencies> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-project-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-project-backend</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.services</groupId> <artifactId>kie-wb-common-services-backend</artifactId> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-security-server</artifactId> </dependency> <dependency> <groupId>org.jboss.errai</groupId> <artifactId>errai-bus</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-metadata-backend-lucene</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-metadata-commons-io</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-jgit</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-structure-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-backend-server</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-metadata-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-server</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-io</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-commons</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-structure-backend</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-security-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-nio2-model</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.screens</groupId> <artifactId>kie-wb-common-library-api</artifactId> </dependency> <dependency> <groupId>org.kie.workbench.services</groupId> <artifactId>kie-wb-common-refactoring-backend</artifactId> </dependency> <dependency> <groupId>org.kie.soup</groupId> <artifactId>kie-soup-project-datamodel-commons</artifactId> </dependency> <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-core</artifactId> <exclusions> <!-- collides with javax.inject:javax.inject:jar:1:compile --> <exclusion> <groupId>jakarta.enterprise</groupId> <artifactId>jakarta.enterprise.cdi-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.1_spec</artifactId> </dependency> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> </dependency> <dependency> <groupId>org.kie.workbench</groupId> <artifactId>kie-wb-common-cli-api</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-security-management-api</artifactId> <exclusions> <exclusion> <groupId>org.uberfire</groupId> <artifactId>uberfire-servlet-security</artifactId> </exclusion> </exclusions> </dependency> <!-- XXX maybe enable logging to a file for troubleshooting? --> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> </dependency> <dependency> <groupId>org.uberfire</groupId> <artifactId>uberfire-testing-utils</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "7c87f1cbe25ee3e4b55dafcb00d5104d", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 204, "avg_line_length": 32.791666666666664, "alnum_prop": 0.6625521873298239, "repo_name": "romartin/kie-wb-common", "id": "700624f9fa2a5cd6e3f81ec089aec21d1aff0219", "size": "5509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kie-wb-common-cli/kie-wb-common-cli-tools/kie-wb-common-cli-project-migration/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2591" }, { "name": "CSS", "bytes": "171885" }, { "name": "Dockerfile", "bytes": "210" }, { "name": "FreeMarker", "bytes": "38625" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "448966" }, { "name": "Java", "bytes": "51118150" }, { "name": "JavaScript", "bytes": "34587" }, { "name": "Shell", "bytes": "905" }, { "name": "TypeScript", "bytes": "26851" }, { "name": "VBA", "bytes": "86549" }, { "name": "XSLT", "bytes": "2327" } ], "symlink_target": "" }
#region License #endregion using System.Globalization; using System.Threading; namespace System { static partial class CoreExtensions { public static void TimeoutInvoke(this Action source, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TimeoutInvoke<T1>(this Action<T1> source, T1 arg1, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TimeoutInvoke<T1, T2>(this Action<T1, T2> source, T1 arg1, T2 arg2, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TimeoutInvoke<T1, T2, T3>(this Action<T1, T2, T3> source, T1 arg1, T2 arg2, T3 arg3, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TimeoutInvoke<T1, T2, T3, T4>(this Action<T1, T2, T3, T4> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } #if CLR4 public static void TryTimeout<T1, T2, T3, T4, T5>(this Action<T1, T2, T3, T4, T5> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TryTimeout<T1, T2, T3, T4, T5, T6>(this Action<T1, T2, T3, T4, T5, T6> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5, arg6); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TryTimeout<T1, T2, T3, T4, T5, T6, T7>(this Action<T1, T2, T3, T4, T5, T6, T7> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5, arg6, arg7); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } public static void TryTimeout<T1, T2, T3, T4, T5, T6, T7, T8>(this Action<T1, T2, T3, T4, T5, T6, T7, T8> source, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, int timeoutMilliseconds) { Thread threadToKill = null; Action action = () => { threadToKill = Thread.CurrentThread; source(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); }; var result = action.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { action.EndInvoke(result); return; } threadToKill.Abort(); throw new TimeoutException(); } #endif } }
{ "content_hash": "b057e939cb83a95b17393d128c5bba23", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 218, "avg_line_length": 45.00769230769231, "alnum_prop": 0.5498205434968382, "repo_name": "Grimace1975/bclcontrib-extend", "id": "f28bc46e81c5615485c7258635cba2b4c1bd3d06", "size": "6948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/System.CoreEx/CoreExtensions+Action.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "4209" }, { "name": "C", "bytes": "27776" }, { "name": "C#", "bytes": "2385027" }, { "name": "JavaScript", "bytes": "27776" }, { "name": "PowerShell", "bytes": "31958" }, { "name": "Shell", "bytes": "5208" } ], "symlink_target": "" }
/** * \file chacha20.h * * \brief This file contains ChaCha20 definitions and functions. * * ChaCha20 is a stream cipher that can encrypt and decrypt * information. ChaCha was created by Daniel Bernstein as a variant of * its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf * ChaCha20 is the variant with 20 rounds, that was also standardized * in RFC 7539. * * \author Daniel King <[email protected]> */ /* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of Mbed TLS (https://tls.mbed.org) */ #ifndef MBEDTLS_CHACHA20_H #define MBEDTLS_CHACHA20_H #if !defined(MBEDTLS_CONFIG_FILE) #include "config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stdint.h> #include <stddef.h> #define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051 /**< Invalid input parameter(s). */ /* MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE is deprecated and should not be * used. */ #define MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE -0x0053 /**< Feature not available. For example, s part of the API is not implemented. */ /* MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED -0x0055 /**< Chacha20 hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_CHACHA20_ALT) typedef struct mbedtls_chacha20_context { uint32_t state[16]; /*! The state (before round operations). */ uint8_t keystream8[64]; /*! Leftover keystream bytes. */ size_t keystream_bytes_used; /*! Number of keystream bytes already used. */ } mbedtls_chacha20_context; #else /* MBEDTLS_CHACHA20_ALT */ #include "chacha20_alt.h" #endif /* MBEDTLS_CHACHA20_ALT */ /** * \brief This function initializes the specified ChaCha20 context. * * It must be the first API called before using * the context. * * It is usually followed by calls to * \c mbedtls_chacha20_setkey() and * \c mbedtls_chacha20_starts(), then one or more calls to * to \c mbedtls_chacha20_update(), and finally to * \c mbedtls_chacha20_free(). * * \param ctx The ChaCha20 context to initialize. */ void mbedtls_chacha20_init( mbedtls_chacha20_context *ctx ); /** * \brief This function releases and clears the specified ChaCha20 context. * * \param ctx The ChaCha20 context to clear. */ void mbedtls_chacha20_free( mbedtls_chacha20_context *ctx ); /** * \brief This function sets the encryption/decryption key. * * \note After using this function, you must also call * \c mbedtls_chacha20_starts() to set a nonce before you * start encrypting/decrypting data with * \c mbedtls_chacha_update(). * * \param ctx The ChaCha20 context to which the key should be bound. * \param key The encryption/decryption key. Must be 32 bytes in length. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL. */ int mbedtls_chacha20_setkey( mbedtls_chacha20_context *ctx, const unsigned char key[32] ); /** * \brief This function sets the nonce and initial counter value. * * \note A ChaCha20 context can be re-used with the same key by * calling this function to change the nonce. * * \warning You must never use the same nonce twice with the same key. * This would void any confidentiality guarantees for the * messages encrypted with the same nonce and key. * * \param ctx The ChaCha20 context to which the nonce should be bound. * \param nonce The nonce. Must be 12 bytes in size. * \param counter The initial counter value. This is usually 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is * NULL. */ int mbedtls_chacha20_starts( mbedtls_chacha20_context* ctx, const unsigned char nonce[12], uint32_t counter ); /** * \brief This function encrypts or decrypts data. * * Since ChaCha20 is a stream cipher, the same operation is * used for encrypting and decrypting data. * * \note The \p input and \p output pointers must either be equal or * point to non-overlapping buffers. * * \note \c mbedtls_chacha20_setkey() and * \c mbedtls_chacha20_starts() must be called at least once * to setup the context before this function can be called. * * \note This function can be called multiple times in a row in * order to encrypt of decrypt data piecewise with the same * key and nonce. * * \param ctx The ChaCha20 context to use for encryption or decryption. * \param size The length of the input data in bytes. * \param input The buffer holding the input data. * This pointer can be NULL if size == 0. * \param output The buffer holding the output data. * Must be able to hold \p size bytes. * This pointer can be NULL if size == 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if the ctx, input, or * output pointers are NULL. */ int mbedtls_chacha20_update( mbedtls_chacha20_context *ctx, size_t size, const unsigned char *input, unsigned char *output ); /** * \brief This function encrypts or decrypts data with ChaCha20 and * the given key and nonce. * * Since ChaCha20 is a stream cipher, the same operation is * used for encrypting and decrypting data. * * \warning You must never use the same (key, nonce) pair more than * once. This would void any confidentiality guarantees for * the messages encrypted with the same nonce and key. * * \note The \p input and \p output pointers must either be equal or * point to non-overlapping buffers. * * \param key The encryption/decryption key. Must be 32 bytes in length. * \param nonce The nonce. Must be 12 bytes in size. * \param counter The initial counter value. This is usually 0. * \param size The length of the input data in bytes. * \param input The buffer holding the input data. * This pointer can be NULL if size == 0. * \param output The buffer holding the output data. * Must be able to hold \p size bytes. * This pointer can be NULL if size == 0. * * \return \c 0 on success. * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if key, nonce, input, * or output is NULL. */ int mbedtls_chacha20_crypt( const unsigned char key[32], const unsigned char nonce[12], uint32_t counter, size_t size, const unsigned char* input, unsigned char* output ); #if defined(MBEDTLS_SELF_TEST) /** * \brief The ChaCha20 checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_chacha20_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* MBEDTLS_CHACHA20_H */
{ "content_hash": "b8c6598cb6d864ff51cafda05007da2a", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 141, "avg_line_length": 38.669724770642205, "alnum_prop": 0.6088967971530249, "repo_name": "librasungirl/openthread", "id": "529f22d9c953bc65c4b4162dd642ffd85dd3b7a9", "size": "8430", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "third_party/mbedtls/repo/include/mbedtls/chacha20.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "50" }, { "name": "C", "bytes": "1097261" }, { "name": "C++", "bytes": "5055434" }, { "name": "CMake", "bytes": "71815" }, { "name": "Dockerfile", "bytes": "10705" }, { "name": "M4", "bytes": "36363" }, { "name": "Makefile", "bytes": "154858" }, { "name": "Python", "bytes": "2672448" }, { "name": "Shell", "bytes": "110491" } ], "symlink_target": "" }
#include <QtGui/QApplication> #include "qmlapplicationviewer.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QmlApplicationViewer viewer; viewer.setOrientation(QmlApplicationViewer::ScreenOrientationLockLandscape); viewer.setMainQmlFile(QLatin1String("qml/focus/focus.qml")); viewer.showExpanded(); return app.exec(); }
{ "content_hash": "08ca5df768fc6f332bb75f879d6b8c36", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 80, "avg_line_length": 23.0625, "alnum_prop": 0.7398373983739838, "repo_name": "stephaneAG/PengPod700", "id": "0f2a9ba321c18afde81768794fea986021eb7096", "size": "2367", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "QtEsrc/qt-everywhere-opensource-src-4.8.5/examples/declarative/keyinteraction/focus/main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "167426" }, { "name": "Batchfile", "bytes": "25368" }, { "name": "C", "bytes": "3755463" }, { "name": "C#", "bytes": "9282" }, { "name": "C++", "bytes": "177871700" }, { "name": "CSS", "bytes": "600936" }, { "name": "GAP", "bytes": "758872" }, { "name": "GLSL", "bytes": "32226" }, { "name": "Groff", "bytes": "106542" }, { "name": "HTML", "bytes": "273585110" }, { "name": "IDL", "bytes": "1194" }, { "name": "JavaScript", "bytes": "435912" }, { "name": "Makefile", "bytes": "289373" }, { "name": "Objective-C", "bytes": "1898658" }, { "name": "Objective-C++", "bytes": "3222428" }, { "name": "PHP", "bytes": "6074" }, { "name": "Perl", "bytes": "291672" }, { "name": "Prolog", "bytes": "102468" }, { "name": "Python", "bytes": "22546" }, { "name": "QML", "bytes": "3580408" }, { "name": "QMake", "bytes": "2191574" }, { "name": "Scilab", "bytes": "2390" }, { "name": "Shell", "bytes": "116533" }, { "name": "TypeScript", "bytes": "42452" }, { "name": "Visual Basic", "bytes": "8370" }, { "name": "XQuery", "bytes": "25094" }, { "name": "XSLT", "bytes": "252382" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>HR management</title> <meta name="description" content="<%= htmlWebpackPlugin.options.metadata.description %>"> <% if (webpackConfig.htmlElements.headTags) { %> <!-- Configured Head Tags --> <%= webpackConfig.htmlElements.headTags %> <% } %> <!-- base url --> <base href="<%= htmlWebpackPlugin.options.metadata.baseUrl %>"> </head> <body> <app> </app> <div id="preloader"> <div></div> </div> <% if (htmlWebpackPlugin.options.metadata.isDevServer && htmlWebpackPlugin.options.metadata.HMR !== true) { %> <!-- Webpack Dev Server reload --> <script src="/webpack-dev-server.js"></script> <% } %> <link href='https://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,400italic,500,500italic,700,700italic,900italic,900&subset=latin,greek,greek-ext,vietnamese,cyrillic-ext,latin-ext,cyrillic' rel='stylesheet' type='text/css'> </body> </html>
{ "content_hash": "97136c8c17606d5c3c781e11024c8a05", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 211, "avg_line_length": 27.275, "alnum_prop": 0.6865261228230981, "repo_name": "TigerDevGit/angular2-HR_management", "id": "2c86164276891a0bd2a8310df58bed3248cedca8", "size": "1091", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "83250" }, { "name": "HTML", "bytes": "27932" }, { "name": "JavaScript", "bytes": "38679" }, { "name": "Shell", "bytes": "153" }, { "name": "TypeScript", "bytes": "74192" } ], "symlink_target": "" }
using namespace std; //--------------------------------------------------------------------------- TSequenceGenerator SequenceGenerator; //--------------------------------------------------------------------------- string TSequenceGenerator::GetString(const string& key,int width) { unsigned int seq=Get(key); int w=1; for(unsigned int num=seq;num>=10;num=num/10) w++; if(width<w) width=w; ostrstream buffer; buffer << key; buffer.fill('0'); buffer.width(width); buffer << seq; buffer << ends; string retstr(buffer.str()); buffer.freeze(false); return(retstr); } //---------------------------------------------------------------------------
{ "content_hash": "46d0e57d552775a2f707a9c570a0acb3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 77, "avg_line_length": 27.375, "alnum_prop": 0.4581430745814307, "repo_name": "kawari/kawari7", "id": "17ef5ce863c3ca18a33279a4e5a946621bdea89e", "size": "1283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/libkawari/sequence_gen.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "6957" }, { "name": "C++", "bytes": "295433" }, { "name": "HTML", "bytes": "80378" }, { "name": "JavaScript", "bytes": "315" }, { "name": "Makefile", "bytes": "17454" }, { "name": "Ruby", "bytes": "2079" } ], "symlink_target": "" }
<?php /** * <%= themeName %> template for displaying the Loop for the Status-Post-Format * * @package WordPress * @subpackage <%= themeName %> * @since <%= themeName %> 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="post-title"> <?php the_content(); ?> </h1> <?php get_template_part( 'template-part', 'byline' ); ?> </article>
{ "content_hash": "1fe9f9cfef21b14cff896d915a6b50d2", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 79, "avg_line_length": 20.63157894736842, "alnum_prop": 0.5612244897959183, "repo_name": "danielauener/generator-wp-grunted-theme", "id": "3111a30b625b53c38a23930534426c370a6f8c98", "size": "392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templates/theme/loop-status.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "80672" }, { "name": "JavaScript", "bytes": "8468" }, { "name": "PHP", "bytes": "19891" } ], "symlink_target": "" }
using System; namespace CGO.Domain { public class Concert { public int Id { get; private set; } public string Title { get; private set; } public DateTime DateAndStartTime { get; private set; } public string Location { get; private set; } public bool IsPublished { get; private set; } public string Description { get; set; } public static readonly DateTime DateOfFirstConcert = new DateTime(2005, 03, 07); public Concert(int id, string title, DateTime dateAndStartTime, string location) { Id = id; Title = title; DateAndStartTime = dateAndStartTime; Location = location; } public void ChangeTitle(string newTitle) { Title = newTitle; } public void ChangeDateAndStartTime(DateTime newDateAndStartTime) { DateAndStartTime = newDateAndStartTime; } public void ChangeLocation(string newLocation) { Location = newLocation; } public void Publish() { IsPublished = true; } } }
{ "content_hash": "5758c539d7ceb7209ed5fdb7ad206107", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 88, "avg_line_length": 25.630434782608695, "alnum_prop": 0.5665818490245971, "repo_name": "alastairs/cgowebsite", "id": "27eb201becc815fd04292d26ffabf7cd72cf8d40", "size": "1181", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/CGO.Domain/Concert.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "150540" }, { "name": "CSS", "bytes": "280754" }, { "name": "JavaScript", "bytes": "765973" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <careServicesFunction xmlns:ev="http://www.w3.org/2001/xml-events" xmlns="urn:ihe:iti:csd:2013" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:csd="urn:ihe:iti:csd:2013" urn="urn:openhie.org:openinfoman-hwr:stored-function:facility_delete_address"> <description>facility_delete_address</description> <definition method="csd_hwru:facility_delete_address"><xi:include parse="text" href="facility_delete_address.xq"/></definition> <xforms:instance> <careServicesRequest> <!-- FILL ME IN--> </careServicesRequest> </xforms:instance> </careServicesFunction>
{ "content_hash": "bbea04d8d64eebb8dd98ffdc894454f7", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 459, "avg_line_length": 74.9090909090909, "alnum_prop": 0.7427184466019418, "repo_name": "openhie/openinfoman-hwr", "id": "c7fe6e88504a7f3ef61bb8a32cfea769f3e85572", "size": "824", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/stored_updating_query_definitions/facility_delete_address.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "3048" }, { "name": "PHP", "bytes": "476" }, { "name": "Shell", "bytes": "35800" }, { "name": "XQuery", "bytes": "165120" } ], "symlink_target": "" }
//------------------------------------------------------------------------------- // Annotations //------------------------------------------------------------------------------- //@Export('bugwork.CreateWorkerProcessCommand') //@Require('Bug') //@Require('Class') //@Require('bugwork.WorkerCommand') //@Require('bugwork.WorkerDefines') //@Require('bugwork.WorkerProcess') //------------------------------------------------------------------------------- // Context //------------------------------------------------------------------------------- require('bugpack').context("*", function(bugpack) { //------------------------------------------------------------------------------- // BugPack //------------------------------------------------------------------------------- var Bug = bugpack.require('Bug'); var Class = bugpack.require('Class'); var WorkerCommand = bugpack.require('bugwork.WorkerCommand'); var WorkerDefines = bugpack.require('bugwork.WorkerDefines'); var WorkerProcess = bugpack.require('bugwork.WorkerProcess'); //------------------------------------------------------------------------------- // Declare Class //------------------------------------------------------------------------------- /** * @class * @extends {WorkerCommand} */ var CreateWorkerProcessCommand = Class.extend(WorkerCommand, { _name: "bugwork.CreateWorkerProcessCommand", //------------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------------- /** * @constructs * @param {WorkerContext} workerContext * @param {WorkerProcessFactory} workerProcessFactory */ _constructor: function(workerContext, workerProcessFactory) { this._super(workerContext); //------------------------------------------------------------------------------- // Private Properties //------------------------------------------------------------------------------- /** * @private * @type {function(Throwable=)} */ this.callback = null; /** * @private * @type {boolean} */ this.completed = false; /** * @private * @type {WorkerProcessFactory} */ this.workerProcessFactory = workerProcessFactory; }, //------------------------------------------------------------------------------- // Getters and Setters //------------------------------------------------------------------------------- /** * @return {function(Throwable, WorkerProcess=)} */ getCallback: function() { return this.callback; }, /** * @return {boolean} */ getCompleted: function() { return this.completed; }, /** * @return {WorkerProcessFactory} */ getWorkerProcessFactory: function() { return this.workerProcessFactory; }, //------------------------------------------------------------------------------- // Command Methods //------------------------------------------------------------------------------- /** * @protected * @param {function(Throwable, WorkerProcess=)} callback */ executeCommand: function(callback) { this.callback = callback; if (!this.getWorkerContext().hasWorkerProcess()) { this.createWorkerProcess(); } else { this.complete(); } }, //------------------------------------------------------------------------------- // Private Methods //------------------------------------------------------------------------------- /** * @private * @param {WorkerProcess} workerProcess */ addProcessListeners: function(workerProcess) { workerProcess.addEventListener(WorkerProcess.EventTypes.CLOSED, this.hearProcessClosed, this); workerProcess.addEventListener(WorkerProcess.EventTypes.READY, this.hearProcessReady, this); workerProcess.addEventListener(WorkerProcess.EventTypes.THROWABLE, this.hearProcessThrowable, this); }, /** * @private * @param {Throwable=} throwable */ complete: function(throwable) { if (!this.completed) { this.completed = true; this.removeProcessListeners(this.getWorkerContext().getWorkerProcess()); this.workerContext = null; if (!throwable) { this.callback(); } else { this.callback(throwable); } } else { throw new Bug("IllegalState", {}, "Creator already complete"); } }, /** * @private */ createWorkerProcess: function() { var workerProcess = this.workerProcessFactory.factoryWorkerProcess(this.getWorkerContext().getProcessConfig()); this.getWorkerContext().updateWorkerProcess(workerProcess); this.addProcessListeners(workerProcess); workerProcess.createProcess(); }, /** * @private * @param {WorkerProcess} workerProcess */ removeProcessListeners: function(workerProcess) { workerProcess.removeEventListener(WorkerProcess.EventTypes.CLOSED, this.hearProcessClosed, this); workerProcess.removeEventListener(WorkerProcess.EventTypes.READY, this.hearProcessReady, this); workerProcess.removeEventListener(WorkerProcess.EventTypes.THROWABLE, this.hearProcessThrowable, this); }, //------------------------------------------------------------------------------- // Event Listeners //------------------------------------------------------------------------------- /** * @private * @param {Event} event */ hearProcessClosed: function(event) { this.complete(new Bug("Worker closed before ready event")); }, /** * @private * @param {Event} event */ hearProcessThrowable: function(event) { this.complete(event.getData().throwable); }, /** * @private * @param {Event} event */ hearProcessReady: function(event) { this.getWorkerContext().updateWorkerState(WorkerDefines.State.READY); this.complete(); } }); //------------------------------------------------------------------------------- // Exports //------------------------------------------------------------------------------- bugpack.export('bugwork.CreateWorkerProcessCommand', CreateWorkerProcessCommand); });
{ "content_hash": "6d1349ad6c722230b02ea30d642d730e", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 124, "avg_line_length": 33.15068493150685, "alnum_prop": 0.39889807162534435, "repo_name": "airbug/bugwork", "id": "81265e0a5298b6b35e2058e821de41aafcd6c667", "size": "7682", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libraries/bugwork/js/src/commands/CreateWorkerProcessCommand.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "156507" } ], "symlink_target": "" }
package com.google.dogecoin.examples; import com.google.dogecoin.core.*; import com.google.dogecoin.params.TestNet3Params; import com.google.dogecoin.store.BlockStore; import com.google.dogecoin.store.MemoryBlockStore; import java.io.File; import java.math.BigInteger; import java.net.InetAddress; /** * RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it. */ public class RefreshWallet { public static void main(String[] args) throws Exception { File file = new File(args[0]); Wallet wallet = Wallet.loadFromFile(file); System.out.println(wallet.toString()); // Set up the components and link them together. final NetworkParameters params = TestNet3Params.get(); BlockStore blockStore = new MemoryBlockStore(params); BlockChain chain = new BlockChain(params, wallet, blockStore); final PeerGroup peerGroup = new PeerGroup(params, chain); peerGroup.addAddress(new PeerAddress(InetAddress.getLocalHost())); peerGroup.start(); wallet.addEventListener(new AbstractWalletEventListener() { @Override public synchronized void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { System.out.println("\nReceived tx " + tx.getHashAsString()); System.out.println(tx.toString()); } }); // Now download and process the block chain. peerGroup.downloadBlockChain(); peerGroup.stop(); //wallet.saveToFile(file); System.out.println("\nDone!\n"); System.out.println(wallet.toString()); } }
{ "content_hash": "dc2dc07d9726fa8168b64ffd86b7067f", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 127, "avg_line_length": 36.02127659574468, "alnum_prop": 0.6816302421736562, "repo_name": "langerhans/dogecoinj-alice", "id": "fe77a1e4687847887c21a3c493f85ac390a975d5", "size": "2286", "binary": false, "copies": "1", "ref": "refs/heads/bcj-0.10.3-mb-alice", "path": "examples/src/main/java/com/google/dogecoin/examples/RefreshWallet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2193637" }, { "name": "Protocol Buffer", "bytes": "25811" } ], "symlink_target": "" }
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { if (products[i].containsNuts === false) { hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(1); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; var anyElible = _(products).any(function (obj,elem) { return products[elem].containsNuts==false; }); if (anyElible){ productsICanEat = _(products).filter(function(pizza){ return pizza.containsNuts==false && !_.contains(pizza.ingredients,"mushrooms"); }); } /* solve using filter() & all() / any() */ expect(productsICanEat.length).toBe(1); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(233168); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var multiples = _(_.range(5,1000,5).concat(_.range(3,1000,3))).uniq(); var sum = _(multiples).reduce(function(seed,num){ return seed + num; },0); /* try chaining range() and reduce() */ expect(233168).toBe(sum); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(2); }); it("should count the ingredient occurrence (functional)", function () { var ingredientCount = { "{ingredient name}": 0 }; var ingredientCount = _(products).chain() .map(function(pizza) { return pizza.ingredients } ) .flatten() .reduce(function (ingCount, x) { ingCount[x] = (ingCount[x] || 0) + 1; return ingCount; }, {}) .value() /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(2); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ /* it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); */ });
{ "content_hash": "370cfaa58d5a3bc1a4ad748e6c5bd740", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 128, "avg_line_length": 33.87313432835821, "alnum_prop": 0.523683630755673, "repo_name": "sarchila/javascript-koans", "id": "c2e8a17a5663b743820345d50ea502f60e4508ea", "size": "4539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "koans/AboutApplyingWhatWeHaveLearnt.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4998" }, { "name": "JavaScript", "bytes": "153824" }, { "name": "Shell", "bytes": "169" } ], "symlink_target": "" }
<fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/section_list" android:name="com.grilledmonkey.grilleduisherlock.fragments.SectionListFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" tools:context=".SectionListActivity" tools:layout="@android:layout/list_content" />
{ "content_hash": "d8d7fde13a479ec84be52124da24c2a4", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 81, "avg_line_length": 43, "alnum_prop": 0.7695560253699789, "repo_name": "Auxx/grilledui", "id": "69e02a559fa9a4e55f51937f88d3da8b5dac7f43", "size": "473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "grilledui-sherlock/res/layout/gui__activity_section_list.xml", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "Groovy", "bytes": "3129" }, { "name": "Java", "bytes": "44495" }, { "name": "Perl", "bytes": "1328" } ], "symlink_target": "" }
<!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> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.1.97: Namespace Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.1.97 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="namespaces.html"><span>Namespace&#160;List</span></a></li> <li class="current"><a href="namespacemembers.html"><span>Namespace&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="namespacemembers.html"><span>All</span></a></li> <li><a href="namespacemembers_func.html"><span>Functions</span></a></li> <li><a href="namespacemembers_type.html"><span>Typedefs</span></a></li> <li><a href="namespacemembers_enum.html"><span>Enumerations</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented namespace members with links to the namespaces they belong to:</div><ul> <li>AccessControl : <a class="el" href="namespacev8.html#a31d8355cb043d7d2dda3f4a52760b64e">v8</a> </li> <li>AccessorGetter : <a class="el" href="namespacev8.html#a3016fe071826349d1370a700e71be094">v8</a> </li> <li>AccessType : <a class="el" href="namespacev8.html#add8bef6469c5b94706584124e610046c">v8</a> </li> <li>ContextGenerator : <a class="el" href="namespacev8.html#a7218225c425a91cdcff3ec9130fb4ed4">v8</a> </li> <li>GCType : <a class="el" href="namespacev8.html#ac109d6f27e0c0f9ef4e98bcf7a806cf2">v8</a> </li> <li>IndexedPropertyDeleter : <a class="el" href="namespacev8.html#a3a7c18d62a0d1f2d12845051920be592">v8</a> </li> <li>IndexedPropertyEnumerator : <a class="el" href="namespacev8.html#a15ab299eff53946ab483b762a4cb20dc">v8</a> </li> <li>IndexedPropertyGetter : <a class="el" href="namespacev8.html#abf3be19b5157493da3859987cc50c6ab">v8</a> </li> <li>IndexedPropertyQuery : <a class="el" href="namespacev8.html#a4b360e915c7c5c1591e946f701d7cc28">v8</a> </li> <li>IndexedPropertySetter : <a class="el" href="namespacev8.html#a3ca53e294b9b695b3777af904ca942b6">v8</a> </li> <li>IndexedSecurityCallback : <a class="el" href="namespacev8.html#aebbcc7837753e51112d944ad96520da1">v8</a> </li> <li>NamedPropertyDeleter : <a class="el" href="namespacev8.html#a7899471fae82b252750b81f41d5c1e26">v8</a> </li> <li>NamedPropertyEnumerator : <a class="el" href="namespacev8.html#acbd04b83708cb5a80e73e0396f176e58">v8</a> </li> <li>NamedPropertyGetter : <a class="el" href="namespacev8.html#ab9effde41da1c073eddbd4a11a62bd0b">v8</a> </li> <li>NamedPropertyQuery : <a class="el" href="namespacev8.html#a57686a4cebfd2ecbe3a333e7f05463ee">v8</a> </li> <li>NamedPropertySetter : <a class="el" href="namespacev8.html#a682b1fc46feab32605c4905612ffe870">v8</a> </li> <li>NamedSecurityCallback : <a class="el" href="namespacev8.html#ab5cafda0c556bba990c660ce9c904e0d">v8</a> </li> <li>ProfilerModules : <a class="el" href="namespacev8.html#af7db93f0cafe64397fd7fdd1bccae9e5">v8</a> </li> <li>ThrowException() : <a class="el" href="namespacev8.html#a2469af0ac719d39f77f20cf68dd9200e">v8</a> </li> <li>WeakReferenceCallback : <a class="el" href="namespacev8.html#a4d5db775dbc002b23f1b55ec7ce80ea5">v8</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:44:49 for V8 API Reference Guide for node.js v0.1.97 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "120a51608eaefb35a072b490d6f95252", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 154, "avg_line_length": 40.190184049079754, "alnum_prop": 0.688291863837582, "repo_name": "v8-dox/v8-dox.github.io", "id": "f4614e43458c66e3cd8e5a24a338bc6c4cd8d0f3", "size": "6551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "31854c7/html/namespacemembers.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
from arelle import PluginManager from arelle.ModelValue import qname from arelle import XbrlConst try: import regex as re except ImportError: import re from collections import defaultdict def compile(list, traceRows): if traceRows: # compile so each row can be traced by separate expression (slow) return [(rowNbr, re.compile("(^|\s)" + pattern + "($|\W+)", re.IGNORECASE)) for rowNbr, pattern in list] else: # compile single expression for fast execution return re.compile("(^|\s)" + # always be sure first word starts at start or after space "($|\W+)|(^|\s)".join(pattern for rowNbr, pattern in list) .replace(r" ",r"\W+") + "($|\W+)", re.IGNORECASE) def setup(val, traceRows=False, *args, **kwargs): if not val.validateLoggingSemantic: # all checks herein are SEMANTIC return # determiniation of two way concept label based on pattern # definitions (from documentation label) are used if present, otherwise standard label for these tests val.twoWayPriItemDefLabelPattern = compile([ # from http://www.sec.gov/spotlight/xbrl/staff-review-observations-061511.shtml # Cash Flow (4, r"increase (\w+ )?decrease"), (5, r"provided by (\w+ )?used in"), (7, r"net cash inflow or outflow"), (6, r"net"), (8, r"change in"), (9, r"proceeds from (\w+ )?payments (for|to)"), # Income statement (13, r"(gain|profit) loss"), (16, r"income (expense|loss)"), (18, r"per share"), # Statement of Stockholders Equity (22, r"equity"), (23, r"retained earnings"), # removed? r"conversion of units", ], traceRows) # standard label tests, indicate two-way label val.twoWayPriItemStdLabelPattern = compile([ # from Eric Cohen (4, r"Increase \(Decrease\)"), (5, r"Provided by \(Used in\)"), (6, r"Net"), (8, r"Change in"), (9, r"Proceeds from \(Payments for\)"), (10, r"Proceeds from \(Payments to\)"), (11, r"Payments for \(Proceeds from\)"), (12, r"Proceeds from \(Repayments of\)"), (13, r"Gain \(Loss\)"), (14, r"Profit \(Loss\)"), (15, r"Loss \(Gain\)"), (16, r"Income \(Loss\)"), (17, r"Income \(Expense\)"), (18, r"Per Share"), (19, r"Per Basic Share"), (20, r"Per Diluted Share"), (21, r"Per Basic and Diluted"), (24, r"Appreciation \(Depreciation\)"), (25, r"Asset \(Liability\)"), (26, r"Assets Acquired \(Liabilities Assumed\)"), (27, r"Benefit \(Expense\)"), (28, r"Expense \(Benefit\)"), (29, r"Cost[s] \(Credit[s]\)"), (30, r"Deductions \(Charges\)"), (31, r"Discount \(Premium\)"), (32, r"Due from \(to\)"), (33, r"Earnings \(Losses\)"), (34, r"Earnings \(Deficit\)"), (35, r"Excess \(Shortage\)"), (36, r"Gains \(Losses\)"), (37, r"Impairment \(Recovery\)"), (38, r"Income \(Loss\)"), (39, r"Liability \(Refund\)"), (40, r"Loss \(Recovery\)"), (41, r"Obligation[s] \(Asset[s]\)"), (42, r"Proceeds from \(Repayments of\)"), (43, r"Proceeds from \(Repurchase of\)"), (44, r"Provided by \(Used in\)"), (45, r"Provisions \(Recoveries\)"), (46, r"Retained Earnings \(Accumulated Deficit\)"), (47, r"per (\w+ )+"), (70, r"Conversion of Units"), (71, r"Effective (\w+ )?Rate"), ], traceRows) # determination of a one-way concept based on standard label val.oneWayPriItemDefLabelPattern = compile([ (49, r"dividend (\w+ )*(paid|received)"), ], traceRows) val.oneWayPriItemStdLabelPattern = compile([ (48, r"Payments of (\w+ )*\((Dividends|Capital)\)"), (49, r"Dividends (\w+ )*\((Pay(ment)?|Receive|Outstanding)\)"), (50, r"(Stock|Shares) Issued"), (51, r"Stock (\w+ )*Repurchased"), (52, r"(Stock|Shares) (\w+ )*Repurchase[d]?"), (53, r"Treasury Stock (\w+ )*(Beginning (\w+ )*Balance[s]?|Ending (\w+ )*Balance[s]?)"), (54, r"Treasury Stock (\w+ )*Acquired"), (55, r"Treasury Stock (\w+ )*Reissued"), (56, r"Treasury Stock (\w+ )*Retired"), (57, r"Accumulated Depreciation (\w+ )*Amortization"), (58, r"Accumulated Other Than Temporary Impairments"), (59, r"Allowance (\w+ )*Doubtful Accounts"), (60, r"Amortization (\w+ )*Pension Costs"), (61, r"Available for Sale Securities (\w+ )*Continuous Loss Position"), (62, r"Available for Sale Securities Bross Unrealized Losses"), (63, r"Accounts"), ], traceRows) # determination of a two way fact based on any of fact's dimension member label val.twoWayMemberStdLabelPattern = compile([ # per Eric Cohen (64, r"Change (in|during) \w+"), # don't match word with change in it like exchange (65, r"\w+ Elimination \w+"), (66, r"Adjustment"), (67, r"Effect\s"), (68, r"Gain(s)? (\w+ )*Loss(es)?"), (69, r"Income \(Loss\)"), (70, r"Net(ting)?"), # don't want to match word with net in it like internet ], traceRows) val.schedules = {} val.elrMatches = (("1statement", re.compile(r"-\s+Statement\s+-\s+", re.IGNORECASE)), ("2disclosure", re.compile(r"-\s+Disclosure\s+-\s+", re.IGNORECASE)), ("3schedule", re.compile(r"-\s+Schedule\s+-\s+", re.IGNORECASE))) def schedules(val, concept): try: return val.schedules[concept.qname] except KeyError: schedules = defaultdict(int) for rel in val.modelXbrl.relationshipSet(XbrlConst.parentChild).toModelObject(concept): for roleType in val.modelXbrl.roleTypes.get(rel.linkrole,()): for elrType, elrPattern in val.elrMatches: if elrPattern.search(roleType.definition): schedules[elrType] += 1 scheduleStr = "" for elrType, num in sorted(schedules.items()): scheduleStr += ", {0} {1}{2}".format(num, elrType[1:], "s" if num > 1 else "") val.schedules[concept.qname] = scheduleStr return scheduleStr def factCheck(val, fact, *args, **kwargs): if not val.validateLoggingSemantic: # all checks herein are SEMANTIC return concept = fact.concept context = fact.context stdLabel = concept.label(lang="en-US", fallbackToQname=False) defLabel = concept.label(preferredLabel=XbrlConst.documentationLabel, lang="en-US", fallbackToQname=False) try: if fact.isNumeric and not fact.isNil and fact.xValue is not None and fact.xValue < 0: # is fact an explicit non neg if ((defLabel is not None and val.oneWayPriItemDefLabelPattern.search(defLabel)) or (stdLabel is not None and val.oneWayPriItemStdLabelPattern.search(stdLabel))): if context.qnameDims: # if fact has a member if any((val.twoWayMemberStdLabelPattern.search(dim.member.label(lang="en-US", fallbackToQname=False)) for dim in context.qnameDims.values() if dim.isExplicit)): # any two way exception member val.modelXbrl.log('INFO-SEMANTIC', "secStaffObservation.nonNegativeFact.info.A", _("Negative fact of an explicit non-negative concept is tagged with a member expected to allow negative values: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) else: val.modelXbrl.log('WARNING-SEMANTIC', "secStaffObservation.nonNegativeFact.warning.B", _("Negative fact of an explicit non-negative concept, member may or not justify a negative value: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) else: # no member val.modelXbrl.log('INCONSISTENCY', "secStaffObservation.nonNegativeFact.inconsistency.C", _("Negative fact of an explicit non-negative concept: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s %(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) # else test if fact meets two way rules elif ((defLabel is not None and val.twoWayPriItemDefLabelPattern.search(defLabel)) or (stdLabel is not None and val.twoWayPriItemStdLabelPattern.search(stdLabel))): val.modelXbrl.log('INFO-SEMANTIC', "secStaffObservation.nonNegativeFact.info.D", _("Negative fact of concept expected to have positive and negative values: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) else: if context.qnameDims: # if fact has a member if any((val.twoWayMemberStdLabelPattern.search(dim.member.label(lang="en-US", fallbackToQname=False)) for dim in context.qnameDims.values() if dim.isExplicit)): # any two way exception member val.modelXbrl.log('INFO-SEMANTIC', "secStaffObservation.nonNegativeFact.info.E", _("Negative fact for typically non-negative concept, but tagged with a member expected to allow negative values: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) else: val.modelXbrl.log('WARNING-SEMANTIC', "secStaffObservation.nonNegativeFact.warning.F", _("Negative fact of a typically non-negative concept, member may or not justify a negative value: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) else: # no member val.modelXbrl.log('INCONSISTENCY', "secStaffObservation.nonNegativeFact.inconsistency.G", _("Negative fact of a \"presumed by default\" non-negative concept: %(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,concept)) except Exception as ex: val.modelXbrl.log('WARNING-SEMANTIC', "arelle:nonNegFactTestException", _("%(fact)s in context %(contextID)s unit %(unitID)s value %(value)s%(elrTypes)s cannot be tested nonnegative"), modelObject=fact, fact=fact.qname, contextID=fact.contextID, unitID=fact.unitID, value=fact.effectiveValue, elrTypes=schedules(val,fact)) def final(val, conceptsUsed, *args, **kwargs): if not val.validateLoggingSemantic: # all checks herein are SEMANTIC return del val.twoWayPriItemDefLabelPattern del val.twoWayPriItemStdLabelPattern del val.oneWayPriItemStdLabelPattern del val.twoWayMemberStdLabelPattern del val.schedules def saveDtsMatches(dts, secDtsTagMatchesFile): setup(dts, True) import sys, csv if sys.version[0] >= '3': csvOpenMode = 'w' csvOpenNewline = '' else: csvOpenMode = 'wb' # for 2.7 csvOpenNewline = None csvFile = open(secDtsTagMatchesFile, csvOpenMode, newline=csvOpenNewline) csvWriter = csv.writer(csvFile, dialect="excel") csvWriter.writerow(("Concept", "Rule", "Row", "Pattern", "Label", "Documentation")) num1wayConcepts = 0 num2wayConcepts = 0 num2wayMembers = 0 for qname, concept in sorted(dts.qnameConcepts.items(), key=lambda item: item[0]): if concept.isItem and concept.isPrimaryItem: # both pri item and domain members stdLabel = concept.label(lang="en-US", fallbackToQname=False) defLabel = concept.label(preferredLabel=XbrlConst.documentationLabel, lang="en-US", fallbackToQname=False) if concept.type is not None and concept.type.isDomainItemType: if stdLabel is not None: for rowNbr, pattern in dts.twoWayMemberStdLabelPattern: if pattern.search(stdLabel): csvWriter.writerow((str(qname), "member-2-way", rowNbr, pattern.pattern[6:-7], stdLabel, defLabel)) num2wayMembers += 1 elif concept.isNumeric and not concept.isAbstract: # not dimension domain/member if defLabel is not None: for rowNbr, pattern in dts.twoWayPriItemDefLabelPattern: if pattern.search(defLabel): csvWriter.writerow((str(qname), "concept-2-way-doc", rowNbr, pattern.pattern[6:-7], stdLabel, defLabel)) num2wayConcepts += 1 for rowNbr, pattern in dts.oneWayPriItemDefLabelPattern: if pattern.search(defLabel): csvWriter.writerow((str(qname), "concept-1-way-doc", rowNbr, pattern.pattern[6:-7], stdLabel, defLabel)) num1wayConcepts += 1 if stdLabel is not None: for rowNbr, pattern in dts.twoWayPriItemStdLabelPattern: if pattern.search(stdLabel): csvWriter.writerow((str(qname), "concept-2-way-lbl", rowNbr, pattern.pattern[6:-7], stdLabel, defLabel)) num2wayConcepts += 1 for rowNbr, pattern in dts.oneWayPriItemStdLabelPattern: if pattern.search(stdLabel): csvWriter.writerow((str(qname), "concept-1-way-lbl", rowNbr, pattern.pattern[6:-7], stdLabel, defLabel)) num1wayConcepts += 1 csvFile.close() dts.log('INFO-SEMANTIC', "info:saveSecDtsTagMatches", _("SecDtsTagMatches entry %(entryFile)s has %(numberOfTwoWayPriItems)s two way primary items, %(numberOfOneWayPriItems)s one way primary items, %(numberOfTwoWayMembers)s two way members in output file %(secDtsTagMatchesFile)s."), modelObject=dts, entryFile=dts.uri, numberOfTwoWayPriItems=num2wayConcepts, numberOfOneWayPriItems=num1wayConcepts, numberOfTwoWayMembers=num2wayMembers, secDtsTagMatchesFile=secDtsTagMatchesFile) final(dts) def saveDtsMatchesMenuEntender(cntlr, menu, *args, **kwargs): # Extend menu with an item for the savedts plugin menu.add_command(label="Save SEC tag matches", underline=0, command=lambda: saveDtsMatchesMenuCommand(cntlr) ) def saveDtsMatchesMenuCommand(cntlr): # save DTS menu item has been invoked if cntlr.modelManager is None or cntlr.modelManager.modelXbrl is None: cntlr.addToLog("No taxonomy loaded.") return # get file name into which to save log file while in foreground thread secDtsTagMatchesFile = cntlr.uiFileDialog("save", title=_("Save SEC DTS tag matches file"), filetypes=[(_("DTS tag matches .csv file"), "*.csv")], defaultextension=".txt") if not secDtsTagMatchesFile: return False try: saveDtsMatches(cntlr.modelManager.modelXbrl, secDtsTagMatchesFile) except Exception as ex: dts = cntlr.modelManager.modelXbrl dts.error("exception", _("SEC DTS Tags Matches exception: %(error)s"), error=ex, modelXbrl=dts, exc_info=True) def saveDtsMatchesCommandLineOptionExtender(parser, *args, **kwargs): # extend command line options with a save DTS option parser.add_option("--save-sec-tag-dts-matches", action="store", dest="secDtsTagMatchesFile", help=_("Save SEC DTS tag matches CSV file.")) def saveDtsMatchesCommandLineXbrlRun(cntlr, options, modelXbrl, *args, **kwargs): # extend XBRL-loaded run processing for this option if getattr(options, "secDtsTagMatchesFile", False): if cntlr.modelManager is None or cntlr.modelManager.modelXbrl is None: cntlr.addToLog("No taxonomy loaded.") return saveDtsMatches(cntlr.modelManager.modelXbrl, options.secDtsTagMatchesFile) __pluginInfo__ = { # Do not use _( ) in pluginInfo itself (it is applied later, after loading 'name': 'Validate US SEC Tagging', 'version': '0.9', 'description': '''US SEC Tagging Validation. Includes non-negative rules.''', 'license': 'Apache-2', 'author': 'Ewe S. Gap', 'copyright': '(c) Copyright 2012 Mark V Systems Limited, All rights reserved.', # classes of mount points (required) 'Validate.EFM.Start': setup, 'Validate.EFM.Fact': factCheck, 'Validate.EFM.Finally': final, 'CntlrWinMain.Menu.Tools': saveDtsMatchesMenuEntender, 'CntlrCmdLine.Options': saveDtsMatchesCommandLineOptionExtender, 'CntlrCmdLine.Xbrl.Run': saveDtsMatchesCommandLineXbrlRun, }
{ "content_hash": "b8b3421db68b06c99c03e17f7b9a8d83", "timestamp": "", "source": "github", "line_count": 341, "max_line_length": 242, "avg_line_length": 54.882697947214076, "alnum_prop": 0.591023243387657, "repo_name": "sternshus/Arelle", "id": "97ff6efe0baf81402f019f92b53acf70be03b596", "size": "18715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "arelle/plugin/validate/USSecTagging.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "31873" }, { "name": "C#", "bytes": "850" }, { "name": "HTML", "bytes": "8640" }, { "name": "Java", "bytes": "4663" }, { "name": "Makefile", "bytes": "5565" }, { "name": "NSIS", "bytes": "9050" }, { "name": "PLSQL", "bytes": "1056360" }, { "name": "Python", "bytes": "5523072" }, { "name": "Shell", "bytes": "13921" } ], "symlink_target": "" }
<mat-card> <mat-card-title>Your app has been updated</mat-card-title> <p> You're now using the latest version of Meditation+. </p> <p> <a href="https://github.com/Sirimangalo/meditation-plus-angular/blob/master/CHANGELOG.md" target="blank"> See the latest changes </a> </p> <p> <a [routerLink]="['']"> Go to Home </a> </p> </mat-card>
{ "content_hash": "778bd25852beb8bdb3621bacb1939ebb", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 109, "avg_line_length": 20.157894736842106, "alnum_prop": 0.597911227154047, "repo_name": "Sirimangalo/meditation-plus-angular", "id": "8d398597414a8d1e07e167a5251b0fb5212f160a", "size": "383", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/update/update.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24916" }, { "name": "HTML", "bytes": "230145" }, { "name": "JavaScript", "bytes": "7456" }, { "name": "Shell", "bytes": "1477" }, { "name": "TypeScript", "bytes": "282392" } ], "symlink_target": "" }
package com.johnsnowlabs.nlp.annotators.ner.dl import com.johnsnowlabs.nlp._ import com.johnsnowlabs.nlp.annotator.{SentenceDetector, Tokenizer} import com.johnsnowlabs.nlp.embeddings.{BertEmbeddings, WordEmbeddingsModel} import com.johnsnowlabs.nlp.training.CoNLL import com.johnsnowlabs.nlp.util.io.ResourceHelper import com.johnsnowlabs.tags.{FastTest, SlowTest} import com.johnsnowlabs.util.{Benchmark, FileHelper} import org.apache.spark.ml.Pipeline import org.scalatest.flatspec.AnyFlatSpec import scala.io.Source class NerDLSpec extends AnyFlatSpec { "NER DL Approach" should "train and annotate with perf" taggedAs SlowTest in { val smallCustomDataset = "src/test/resources/conll2003/eng.testa" SparkAccessor.spark.conf.getAll.foreach(println) for (samples <- Array(512, 1024, 2048, 4096, 8192)) { val trainData = CoNLL(conllLabelIndex = 1) .readDatasetFromLines( Source.fromFile(smallCustomDataset).getLines.toArray, SparkAccessor.spark) .toDF .limit(samples) println(s"TRAIN DATASET COUNT: ${trainData.count}") val document = new DocumentAssembler().setInputCol("text").setOutputCol("document") val sentence = new SentenceDetector().setInputCols(Array("document")).setOutputCol("sentence") val token = new Tokenizer().setInputCols(Array("sentence")).setOutputCol("token") val bert = BertEmbeddings .pretrained("bert_base_cased", "en") .setInputCols(Array("sentence", "token")) .setOutputCol("bert") val testDataset = trainData println(s"TEST DATASET COUNT: ${testDataset.count}") val testDataParquetPath = "src/test/resources/conll2003/testDataParquet" bert.transform(testDataset).write.mode("overwrite").parquet(testDataParquetPath) val nerTagger = new NerDLApproach() .setInputCols(Array("sentence", "token", "bert")) .setLabelColumn("label") .setOutputCol("ner") .setMaxEpochs(10) .setLr(0.001f) .setPo(0.005f) .setBatchSize(8) .setRandomSeed(0) .setVerbose(0) .setValidationSplit(0.2f) .setEvaluationLogExtended(false) .setEnableOutputLogs(false) .setIncludeConfidence(true) .setTestDataset(testDataParquetPath) val pipeline = new Pipeline() .setStages(Array(document, sentence, token, bert, nerTagger)) val fitted = Benchmark.time(s"$samples fit ner dl time", forcePrint = true) { pipeline.fit(trainData) } val transformed = Benchmark.time(s"$samples transform ner dl time", forcePrint = true) { fitted.transform(testDataset) } println(s"transformed.count: ${transformed.count}") transformed.write .mode("overwrite") .parquet(s"src/test/resources/conll2003/out/transformedParquet${samples}") } } "NerDLApproach" should "correctly annotate" taggedAs SlowTest in { val nerSentence = DataBuilder.buildNerDataset(ContentProvider.nerCorpus) // System.out.println(s"number of sentences in dataset ${nerSentence.count()}") // Dataset ready for NER tagger val nerInputDataset = AnnotatorBuilder.withGlove(nerSentence) // System.out.println(s"number of sentences in dataset ${nerInputDataset.count()}") val nerModel = AnnotatorBuilder.getNerDLModel(nerSentence) val tagged = nerModel.transform(nerInputDataset) val annotations = Annotation.collect(tagged, "ner").flatten.toSeq val labels = Annotation.collect(tagged, "label").flatten.toSeq assert(annotations.length == labels.length) for ((annotation, label) <- annotations.zip(labels)) { assert(annotation.begin == label.begin) assert(annotation.end == label.end) assert(annotation.annotatorType == AnnotatorType.NAMED_ENTITY) assert(annotation.result == label.result) assert(annotation.metadata.contains("word")) } } "NerDLApproach" should "correctly tag sentences" taggedAs SlowTest in { val nerSentence = DataBuilder.buildNerDataset(ContentProvider.nerCorpus) System.out.println(s"number of sentences in dataset ${nerSentence.count()}") // Dataset ready for NER tagger val nerInputDataset = AnnotatorBuilder.withGlove(nerSentence) System.out.println(s"number of sentences in dataset ${nerInputDataset.count()}") val nerModel = AnnotatorBuilder.getNerDLModel(nerSentence) val tagged = nerModel.transform(nerInputDataset) val annotations = Annotation.collect(tagged, "ner").flatten val tags = annotations.map(a => a.result).toSeq assert(tags.toList == Seq("PER", "PER", "O", "O", "ORG", "LOC", "O")) } "NerDLModel" should "correctly train using dataset from file" taggedAs SlowTest in { val nerSentence = DataBuilder.buildNerDataset(ContentProvider.nerCorpus) System.out.println(s"number of sentences in dataset ${nerSentence.count()}") // Dataset ready for NER tagger val nerInputDataset = AnnotatorBuilder.withGlove(nerSentence) System.out.println(s"number of sentences in dataset ${nerInputDataset.count()}") val tagged = AnnotatorBuilder.withNerDLTagger(nerInputDataset) val annotations = Annotation.collect(tagged, "ner").flatten val tags = annotations.map(a => a.result).toSeq assert(tags.toList == Seq("PER", "PER", "O", "O", "ORG", "LOC", "O")) } "NerDLApproach" should "be serializable and deserializable correctly" taggedAs SlowTest in { val nerSentence = DataBuilder.buildNerDataset(ContentProvider.nerCorpus) System.out.println(s"number of sentences in dataset ${nerSentence.count()}") // Dataset ready for NER tagger val nerInputDataset = AnnotatorBuilder.withGlove(nerSentence) System.out.println(s"number of sentences in dataset ${nerInputDataset.count()}") val nerModel = AnnotatorBuilder.getNerDLModel(nerSentence) nerModel.write.overwrite.save("./test_ner_dl") val loadedNer = NerDLModel.read.load("./test_ner_dl") FileHelper.delete("./test_ner_dl") // Test that params of loaded model are the same assert(loadedNer.datasetParams.getOrDefault == nerModel.datasetParams.getOrDefault) // Test that loaded model do the same predictions val tokenized = AnnotatorBuilder.withTokenizer(nerInputDataset) val tagged = loadedNer.transform(tokenized) val annotations = Annotation.collect(tagged, "ner").flatten val tags = annotations.map(a => a.result).toSeq assert(tags.toList == Seq("PER", "PER", "O", "O", "ORG", "LOC", "O")) } "NerDLApproach" should "correct search for suitable graphs" taggedAs FastTest in { val smallGraphFile = NerDLApproach.searchForSuitableGraph(10, 100, 120) assert(smallGraphFile.endsWith("blstm_10_100_128_120.pb")) val bigGraphFile = NerDLApproach.searchForSuitableGraph(25, 300, 120) assert(bigGraphFile.endsWith("blstm_38_300_128_200.pb")) assertThrows[IllegalArgumentException](NerDLApproach.searchForSuitableGraph(31, 101, 100)) assertThrows[IllegalArgumentException](NerDLApproach.searchForSuitableGraph(50, 300, 601)) assertThrows[IllegalArgumentException](NerDLApproach.searchForSuitableGraph(40, 512, 101)) } "NerDLApproach" should "validate against part of the training dataset" taggedAs FastTest in { val conll = CoNLL() val training_data = conll.readDataset( ResourceHelper.spark, "src/test/resources/ner-corpus/test_ner_dataset.txt") val embeddings = AnnotatorBuilder.getGLoveEmbeddings(training_data.toDF()) val trainData = embeddings.transform(training_data) val ner = new NerDLApproach() .setInputCols("sentence", "token", "embeddings") .setOutputCol("ner") .setLabelColumn("label") .setOutputCol("ner") .setLr(1e-1f) // 0.1 .setPo(5e-3f) // 0.005 .setDropout(5e-1f) // 0.5 .setMaxEpochs(1) .setRandomSeed(0) .setVerbose(0) .setEvaluationLogExtended(true) .setEnableOutputLogs(true) .setGraphFolder("src/test/resources/graph/") .setUseBestModel(true) .fit(trainData) ner.write.overwrite() save ("./tmp_ner_dl_tf115") } "NerDLModel" should "successfully load saved model" taggedAs FastTest in { val conll = CoNLL() val test_data = conll.readDataset(ResourceHelper.spark, "src/test/resources/conll2003/eng.testb") val embeddings = AnnotatorBuilder.getGLoveEmbeddings(test_data.toDF()) val testData = embeddings.transform(test_data) NerDLModel .load("./tmp_ner_dl_tf115") .setInputCols("sentence", "token", "embeddings") .setOutputCol("ner") .transform(testData) } "NerDLModel" should "successfully download a pretrained model" taggedAs FastTest in { val nerModel = NerDLModel .pretrained() .setInputCols("sentence", "token", "embeddings") .setOutputCol("ner") nerModel.getClasses.foreach(x => println(x)) } "NerDLApproach" should "benchmark test" taggedAs SlowTest in { val conll = CoNLL(explodeSentences = false) val trainingData = conll.readDataset(ResourceHelper.spark, "src/test/resources/conll2003/eng.train") val testingData = conll.readDataset(ResourceHelper.spark, "src/test/resources/conll2003/eng.testa") val embeddings = WordEmbeddingsModel.pretrained() val trainDF = embeddings.transform(trainingData) embeddings.transform(testingData).write.mode("overwrite").parquet("./tmp_test_coll") val nerModel = new NerDLApproach() .setInputCols("sentence", "token", "embeddings") .setOutputCol("ner") .setLabelColumn("label") .setOutputCol("ner") .setLr(1e-3f) // 0.001 .setPo(5e-3f) // 0.005 .setDropout(5e-1f) // 0.5 .setMaxEpochs(5) .setRandomSeed(0) .setVerbose(0) .setBatchSize(8) .setEvaluationLogExtended(true) .setGraphFolder("src/test/resources/graph/") .setTestDataset("./tmp_test_coll") .setUseBestModel(true) .fit(trainDF) nerModel.write.overwrite() save ("./tmp_ner_dl_glove_conll03_100d") } "NerDLModel" should "benchmark test" taggedAs SlowTest in { val conll = CoNLL(explodeSentences = false) val training_data = conll.readDataset(ResourceHelper.spark, "src/test/resources/conll2003/eng.train") val embeddings = WordEmbeddingsModel.pretrained() val nerModel = NerDLModel .pretrained() .setInputCols("sentence", "token", "embeddings") .setOutputCol("ner") .setBatchSize(8) val pipeline = new Pipeline() .setStages(Array(embeddings, nerModel)) val pipelineDF = pipeline.fit(training_data).transform(training_data) Benchmark.time("Time to save BertEmbeddings results") { pipelineDF.select("ner.result").write.mode("overwrite").parquet("./tmp_nerdl") } } "NerDLModel" should "work with confidence scores enabled" taggedAs SlowTest in { val conll = CoNLL(explodeSentences = false) val training_data = conll.readDataset(ResourceHelper.spark, "src/test/resources/conll2003/eng.train") val embeddings = WordEmbeddingsModel.pretrained() val nerModel = NerDLModel .pretrained() .setInputCols("sentence", "token", "embeddings") .setOutputCol("ner") .setIncludeConfidence(true) val pipeline = new Pipeline() .setStages(Array(embeddings, nerModel)) val pipelineDF = pipeline.fit(training_data).transform(training_data) pipelineDF.select("ner").show(1, truncate = false) } // AWS keys need to be set up for this test ignore should "correct search for suitable graphs on S3" taggedAs SlowTest in { val awsAccessKeyId = sys.env("AWS_ACCESS_KEY_ID") val awsSecretAccessKey = sys.env("AWS_SECRET_ACCESS_KEY") val awsSessionToken = sys.env("AWS_SESSION_TOKEN") ResourceHelper.getSparkSessionWithS3( awsAccessKeyId, awsSecretAccessKey, awsSessionToken = Some(awsSessionToken)) val s3FolderPath = "s3://sparknlp-test/ner-dl/" // identical to the one in repository val smallGraphFile = NerDLApproach.searchForSuitableGraph(10, 100, 120, Some(s3FolderPath)) assert(smallGraphFile.endsWith("blstm_10_100_128_120.pb")) val bigGraphFile = NerDLApproach.searchForSuitableGraph(25, 300, 120, Some(s3FolderPath)) assert(bigGraphFile.endsWith("blstm_38_300_128_200.pb")) } }
{ "content_hash": "3d0c2ccc1f5fd00c6c67881cae1cbc0a", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 95, "avg_line_length": 36.47941176470588, "alnum_prop": 0.699508183503991, "repo_name": "JohnSnowLabs/spark-nlp", "id": "a4d41b68f914da103a05644e7797189b8d5f820b", "size": "13004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scala/com/johnsnowlabs/nlp/annotators/ner/dl/NerDLSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "14452" }, { "name": "Java", "bytes": "223289" }, { "name": "Makefile", "bytes": "819" }, { "name": "Python", "bytes": "1694517" }, { "name": "Scala", "bytes": "4116435" }, { "name": "Shell", "bytes": "5286" } ], "symlink_target": "" }
Presenting ========== Before first meeting -------------------- Send the following email before class:: Hi all, In tomorrow's class I will give an example 15 minute presentation. After the presentation and any question you might have we will discuss the following principles of presetionat: https://vknight.org/pop/ Note that as part of my presentation I will give you another example of an entire project (the other examples having been discussed in class and in the notes). Please get in touch if I can assist with anything, Vince In class meeting ---------------- Give a presentation. Specifically present `ertai` version `0.0.2` (a library specifically built for this purpose). After the presentation, if there are any questions about the tpic answer them. After that, give an overview of the principles of presentation: https://vknight.org/pop/ Use breakout rooms of about 4 students to ask them to discuss the presentation and the principles. Bring back for a group discussion. After class email ----------------- Send the following email after class:: Hi all, A recording of today's class is available at <>. In this class I gave you a presentation of a similar format to what you will be doing during your coursework assessment. We also discussed principles of presentation: https://vknight.org/pop/ You can find the paper that corresponds to the presentation here: https://vknight.org/cfm/assets/pdf/ertai_paper/main.pdf (the tex source code is available here: https://vknight.org/cfm/assets/pdf/ertai_paper/main.tex). Please get in touch if I can assist with anything, Vince
{ "content_hash": "4da0c3c17f2e1eb19a022d88df5c8570", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 83, "avg_line_length": 27.60655737704918, "alnum_prop": 0.7191211401425178, "repo_name": "drvinceknight/cfm", "id": "58d301d857fb8c23d16412985dc08776a8f5feaf", "size": "1684", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/meetings/16/index.rst", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2992" }, { "name": "Jupyter Notebook", "bytes": "130263" }, { "name": "Python", "bytes": "15410" }, { "name": "TeX", "bytes": "35411" } ], "symlink_target": "" }
<?php require_once("models/config.php"); if (!securePage($_SERVER['PHP_SELF'])){die();} $device = $_GET['id']; $note = $_GET['note']; function IsNullOrEmptyString($str){ return (!isset($str) || trim($str)===''); } //Send PUT to checkin api $ch = curl_init(); $api = '/rest/v1/device/'; $url = $dc_base_url . $api . $device . '/checkin'; $credentials = $loggedInUser->username . ":" . $loggedInUser->hash_pw; $headers = array( "Content-type: application/xml;charset=\"utf-8\"", "Authorization: " . $credentials ); // Set curl options to POST curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Add in message data if it exists if (!IsNullOrEmptyString($note)) { $xml_data = "<message>" . $note . "</message>"; curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data); } $server_output = curl_exec($ch); $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $deviceurl = 'device.php?id='. $device; $redirect_message = "Redirecting to device details in 5 seconds or click <a href='".$deviceurl."'>here</a>."; if ($status_code === 200) { $header = "Success!"; $message = "Device '".$device."' was checked in."; } else { $header = "Oh boy..."; $message = "There was an error. The server returned '".$status_code." - ".$server_output."'"; } // Redirect to the device details page header("Refresh: 5;url=$deviceurl"); ?> <!DOCTYPE html> <html> <head> <title>DeviceGenie - Checkin</title> <link rel="stylesheet" type="text/css" href="genie.css"> </head> <body> <?php include 'navbar.php'; ?> <div id="margin-top-medium"></div> <div id="content-medium"> <div class="colored-bg-round"> <div class="padding-top-medium"></div> <div style="text-align: center;"> <h1><?= $header ?></h1> <h2><?= $message; ?></h2> <br/><br/> <?= $redirect_message; ?> <br/><br/> </div> </div> </div> <?php include 'footer.php'; ?> </body> </html>
{ "content_hash": "af84ae0ac00d53addfcf88cfec877152", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 109, "avg_line_length": 25.807692307692307, "alnum_prop": 0.6194734227521113, "repo_name": "markperdue/device-genie", "id": "5f9a7d48b05f52af9c6dba419e308660b0ad133b", "size": "2013", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "checkin.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14559" }, { "name": "JavaScript", "bytes": "269" }, { "name": "PHP", "bytes": "166728" } ], "symlink_target": "" }
<?php class Kwc_Shop_Cart_Checkout_Payment_None_Component extends Kwc_Shop_Cart_Checkout_Payment_Abstract_Component { public static function getSettings() { $ret = parent::getSettings(); $ret['componentName'] = trlKwfStatic('None'); return $ret; } }
{ "content_hash": "1fd39c6fee1ab76edb36b7fe05dda482", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 109, "avg_line_length": 26.09090909090909, "alnum_prop": 0.6585365853658537, "repo_name": "yacon/koala-framework", "id": "4db21add7ed11556643b5d576abcd10facb9995c", "size": "287", "binary": false, "copies": "8", "ref": "refs/heads/3.8", "path": "Kwc/Shop/Cart/Checkout/Payment/None/Component.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "140" }, { "name": "CSS", "bytes": "136629" }, { "name": "HTML", "bytes": "10021" }, { "name": "JavaScript", "bytes": "1149122" }, { "name": "PHP", "bytes": "6825225" }, { "name": "Smarty", "bytes": "195797" } ], "symlink_target": "" }
<h1> Privacy Policy for AnotherBit</h1> <p>If you require any more information or have any questions about our privacy policy, please feel free to contact us by email at <a href="mailto:[email protected]">[email protected]</a>.</p> <p>At AnotherBit we consider the privacy of our visitors to be extremely important. This privacy policy describes in detail the types of personal information that is collected and recorded by AnotherBit and how we use it.</p> <p><b>Log Files</b><br> Like many other web sites, anotherbit.com makes use of log files. These files merely log visitors to the site - usually a standard procedure for hosting companies and a part of hosting services's analytics. The information inside the log files includes internet protocol (IP) addresses, browser type, Internet Service Provider (ISP), date/time stamp, referring/exit pages, and clicks. This information is used to analyze trends, administer the site, track user's movement around the site, and gather demographic information. IP addresses, and other such information are not linked to any information that is personally identifiable.</p> <p><b>Cookies and Web Beacons</b><br> anotherbit.com does not use cookies.</p> <p><b>Mobile App Data Collection</b><br> AnotherBit does not collect any information from our mobile apps.</p> <p><strong>Children's Information</strong><br> We believe it is important to provide added protection for children online. We encourage parents and guardians to spend time online with their children to observe, participate in and/or monitor and guide their online activity. anotherbit.com does not knowingly collect any personally identifiable information from children under the age of 13. If a parent or guardian believes that anotherbit.com has in its database the personally-identifiable information of a child under the age of 13, please contact us immediately (using the contact in the first paragraph) and we will use our best efforts to promptly remove such information from our records.</p> <p><b>Consent</b><br> By using our website and/or mobile apps, you hereby consent to our privacy policy and agree to its terms.</p> <br/> <p><b>Update</b><br/>This Privacy Policy was last updated on: Friday, August 19th, 2016.<br/> <em>Should we update, amend or make any changes to our privacy policy, those changes will be posted here.</em> <br/><br/></p>
{ "content_hash": "44687c5267cdfd495fb5e9c9026b6c82", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 654, "avg_line_length": 95.48, "alnum_prop": 0.7821533305404273, "repo_name": "anotherbit/anotherbit.github.io", "id": "12707451dd1e354215677e5d6a24b4fa75bdc6c3", "size": "2387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "privacy.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "17847" }, { "name": "HTML", "bytes": "25496" }, { "name": "JavaScript", "bytes": "42688" }, { "name": "PHP", "bytes": "1017" }, { "name": "Ruby", "bytes": "715" } ], "symlink_target": "" }
from json import loads, dumps from winload import Winload from linload import Linload from network import Network from sys import platform class LocalController: def __init__(self): self.platform = '' self.data = {} self.dataGetter = None self.networkWorker = None self.config = {} def setup(self): if platform.startswith('linux'): self.platform = 'linux' self.dataGetter = Linload() elif platform.startswith('win'): self.platform = 'win' self.dataGetter = Winload() self.config = self.loadJsonFile('./data/config.json') self.networkWorker = Network(self.config) def loadJsonFile(self, filename): with open(filename) as json_file: data = loads(json_file.read()) return data def saveJsonFile(self, filename, variable): with open(filename, "w") as json_file: data = json_file.write(dumps(variable, indent=4)) return data def main(self): self.setup() self.networkWorker.startHeartBeat() self.data = self.dataGetter.main() self.saveJsonFile('./data/data.json', self.data) self.networkWorker.sendFile() if __name__ == '__main__': LocalController().main()
{ "content_hash": "523c57836f88ac03a77ed6baedb399c8", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 61, "avg_line_length": 28.23913043478261, "alnum_prop": 0.6058506543494996, "repo_name": "arseniypetrikor/lc-client", "id": "dc6cf5b9b0376f948b77320a3947555d4401cad7", "size": "1299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "5744" } ], "symlink_target": "" }
def space_out_camel_case(camel): """ Converts a "CamelCasedName" to "Camel Case Name". """ chars = [] for char in camel: if len(chars) >= 2 and chars[-1] != ' ': if char.isupper() and chars[-1].islower(): chars.append(' ') elif char.islower() and chars[-1].isupper() and chars[-2].isupper(): chars.insert(len(chars) - 1, ' ') chars.append(char) return ''.join(chars)
{ "content_hash": "6d3fc23e81052c8398a5ead9e2dc547e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 80, "avg_line_length": 29.125, "alnum_prop": 0.5128755364806867, "repo_name": "servee/servee", "id": "498394b734eeec12aed9463097d99bdd52ab95cd", "size": "466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "servee/utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "68505" }, { "name": "HTML", "bytes": "46896" }, { "name": "JavaScript", "bytes": "5602" }, { "name": "Python", "bytes": "56014" } ], "symlink_target": "" }
// // DDQWebPageController.m // DDQProjectEdit // // Copyright © 2017年 DDQ. All rights reserved. #import "DDQWebPageController.h" #import "DDQAlertController.h" #import "DDQAlertItem.h" #import "DDQWebPagePlaceholderView.h" @interface DDQWebPageController ()<DDQWebPagePlaceholderDelegate> @end @implementation DDQWebPageController - (void)viewDidLoad { [super viewDidLoad]; //WebView WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init]; self.web_WKWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfig]; [self.view addSubview:self.web_WKWebView]; self.web_WKWebView.UIDelegate = self; //Progress self.web_rateProgress = [[UIProgressView alloc] initWithFrame:CGRectZero]; self.web_rateProgress.progressViewStyle = UIProgressViewStyleDefault; self.web_rateProgress.trackTintColor = kSetColor(235.0, 235.0, 235.0, 1.0); [self.view addSubview:self.web_rateProgress]; [self.web_rateProgress setProgressTintColor:[UIColor blackColor]]; //PlaceholderView self.web_placeholderView = [DDQWebPagePlaceholderView placeholderWithTitle:@"当前网络异常!" subTitle:@"加载失败"]; [self.view addSubview:self.web_placeholderView]; self.web_placeholderView.hidden = YES; self.web_placeholderView.delegate = self; //KVO [self.web_WKWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];//进度条 //iOS 11.0 if (@available(iOS 11.0, *)) { self.web_WKWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; } else { self.automaticallyAdjustsScrollViewInsets = NO; } self.web_showWebTitle = YES; self.web_webAutoLayout = YES; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:YES]; //PS:我这么写的原因是因为防止bridge的base对页面的强引用,造成页面的不被释放。释放我写在了viewDidDisappear; //大致就是 self -> bridge -> bridgeBase -> self if (!self.web_jsBridge) { //重新注册一次JS self.web_jsBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.web_WKWebView webViewDelegate:self handler:nil]; } } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:YES]; if (self.navigationController.viewControllers.firstObject != self) {//不是根视图控制器就销毁 //销毁bridge防止循环引用 self.web_jsBridge = nil; } } - (void)viewWillLayoutSubviews { [super viewWillLayoutSubviews]; if (self.web_webAutoLayout) { self.web_WKWebView.frame = self.view.bounds; } self.web_rateProgress.frame = CGRectMake(CGRectGetMinX(self.web_WKWebView.frame), CGRectGetMinY(self.web_WKWebView.frame), CGRectGetWidth(self.web_WKWebView.frame), 2.0); self.web_placeholderView.frame = self.view.bounds; } - (void)dealloc { [self.web_WKWebView removeObserver:self forKeyPath:@"estimatedProgress"]; if (self.web_jsBridge) self.web_jsBridge = nil; if (self.web_WKWebView.UIDelegate) self.web_WKWebView.UIDelegate = nil; } #pragma mark - Custom Method /** 创建一个bridge PS:这里重点说明下,我将pod的WebViewJavascriptBridge指定到了4.1.5版本。因为5.0以后的版本我截获不到js,原因排查中。 */ - (WKWebViewJavascriptBridge *)web_jsBridge { if (!_web_jsBridge) { _web_jsBridge = [WKWebViewJavascriptBridge bridgeForWebView:self.web_WKWebView webViewDelegate:self handler:nil]; } return _web_jsBridge; } - (void)setWeb_requestUrl:(NSString *)web_requestUrl { _web_requestUrl = web_requestUrl; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_web_requestUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:25.0]; [self.web_WKWebView loadRequest:request]; } #pragma mark - WKWebView Delegate - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation { [self.web_rateProgress setHidden:NO]; if (self.view.subviews.lastObject != self.web_rateProgress) [self.view bringSubviewToFront:self.web_rateProgress]; } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { if (self.web_showWebTitle && webView.title.length > 0) self.navigationItem.title = webView.title;//显示标题并且标题不为空 [self.web_rateProgress setHidden:YES]; self.web_placeholderView.hidden = YES; } - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { self.web_placeholderView.hidden = NO; [self.view bringSubviewToFront:self.web_placeholderView]; self.web_placeholderView.placeholder_titleLabel.text = @"当前网络异常!"; self.web_placeholderView.placeholder_subTitleLabel.text = @"加载失败"; } #pragma mark - WKWebView UIDelegate - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(nonnull NSString *)message initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void (^)(void))completionHandler { DDQAlertController *alerController = [DDQAlertController alertControllerWithTitle:@"提示" message:message alertStyle:DDQAlertControllerStyleAlert]; [alerController alert_addAlertItem:^__kindof DDQAlertItem * _Nullable{ DDQAlertItem *item = [DDQAlertItem alertItemWithStyle:DDQAlertItemStyleDefault]; item.item_attrTitle = [[NSAttributedString alloc] initWithString:@"确定" attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}]; return item; } handler:nil]; [self presentViewController:alerController animated:YES completion:nil]; completionHandler(); } #pragma mark - KVO - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context { if (change[NSKeyValueChangeNewKey]) { float progress = [change[NSKeyValueChangeNewKey] floatValue]; [self.web_rateProgress setProgress:progress animated:YES]; if (progress >= 1.0) {//加载完成 [self.web_rateProgress setHidden:YES]; [self.web_rateProgress setProgress:0.0]; } } } #pragma mark - PlaceholderView Delegate - (void)placeholder_didSelectAlertWithView:(DDQWebPagePlaceholderView *)placeholderView { placeholderView.placeholder_titleLabel.text = @"重新加载中..."; placeholderView.placeholder_subTitleLabel.text = @"请稍候"; DDQWeakObject(self); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //webview没有数据,reload后不会重走代理方法 weakObjc.web_requestUrl = weakObjc.web_requestUrl; [weakObjc.web_WKWebView reload]; }); } @end
{ "content_hash": "d63db594a41aa3b246fa57d0a2f403a7", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 207, "avg_line_length": 35.712765957446805, "alnum_prop": 0.7204349121239202, "repo_name": "MyNameDDQ/DDQProjectFoundation", "id": "536f37b4caa17df35aa5c704211b44b6360be414", "size": "7061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DDQProjectFoundation/DDQControllerFoundation/DDQWebPageController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "228745" }, { "name": "Ruby", "bytes": "2369" } ], "symlink_target": "" }
@class RACTuple; // A private category of methods to handle wrapping and unwrapping of values. @interface NSInvocation (RACTypeParsing) // Sets the argument for the invocation at the given index by unboxing the given // object based on the type signature of the argument. // // This does not support C arrays or unions. // // Note that calling this on a char * or const char * argument can cause all // arguments to be retained. // // object - The object to unbox and set as the argument. // index - The index of the argument to set. - (void)rac_setArgument:(id)object atIndex:(NSUInteger)index; // Gets the argument for the invocation at the given index based on the // invocation's method signature. The value is then wrapped in the appropriate // object type. // // This does not support C arrays or unions. // // index - The index of the argument to get. // // Returns the argument of the invocation, wrapped in an object. - (id)rac_argumentAtIndex:(NSUInteger)index; // Arguments tuple for the invocation. // // The arguments tuple excludes implicit variables `self` and `_cmd`. // // See -rac_argumentAtIndex: and -rac_setArgumentAtIndex: for further // description of the underlying behavior. @property (nonatomic, copy) RACTuple *rac_argumentsTuple; // Gets the return value from the invocation based on the invocation's method // signature. The value is then wrapped in the appropriate object type. // // This does not support C arrays or unions. // // Returns the return value of the invocation, wrapped in an object. Void // returns will be represented by an unspecified, possibly nil, object. - (id)rac_returnValue; @end
{ "content_hash": "80da62c144bd1a8c888bf8c65e70e833", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 80, "avg_line_length": 35.67391304347826, "alnum_prop": 0.7458866544789763, "repo_name": "SpruceHealth/ReactiveCocoa", "id": "96e7a68dc96018f3b79678af910b20a19d05688a", "size": "1838", "binary": false, "copies": "1", "ref": "refs/heads/3.0-development", "path": "ReactiveCocoaFramework/ReactiveCocoa/NSInvocation+RACTypeParsing.h", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
require 'spec_helper' require 'pstore' describe SortedArray::ReverseSorter do let(:sorter) { SortedArray::ReverseSorter.new(:foo) } let(:items) { [ OpenStruct.new(foo: 1), OpenStruct.new(foo: 3), OpenStruct.new(foo: 2) ] } let(:reversed) { items.sort{|a,b|a.foo <=> b.foo}.reverse } let(:store) { PStore.new(SORTER_TEST_STORE) } it 'sorts and reverse an array by a given sort-method' do expect(sorter.sort(items)).to eq(reversed) end it 'stores the method-name to a PStore' do sorter.should_receive(:marshal_dump) store.transaction do |s| s[:sorter] = sorter end end it 'loads the method-name and propper class from a PStore' do _s = nil store.transaction(true) { |r| _s = r[:sorter] } expect(_s).to be_a SortedArray::ReverseSorter expect(_s.method).to eq(:to_s) end end
{ "content_hash": "6b76317147d7346a7b3385d0018f37ad", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 63, "avg_line_length": 26.53125, "alnum_prop": 0.6525323910482921, "repo_name": "iboard/sorted_array", "id": "02d32022e564ee603b6596b688788cf2f57f4026", "size": "849", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/reversed_sorter_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "10326" } ], "symlink_target": "" }
package org.quattor.pan.output; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.zip.GZIPOutputStream; public class JsonGzipFormatter extends JsonFormatter { private static final JsonGzipFormatter instance = new JsonGzipFormatter(); private JsonGzipFormatter() { super("json.gz", "json.gz"); } public static JsonGzipFormatter getInstance() { return instance; } @Override protected PrintWriter getPrintWriter(File file) throws Exception { OutputStream os = new FileOutputStream(file); OutputStream gzip = new GZIPOutputStream(os); return new PrintWriter(gzip); } }
{ "content_hash": "9cdf163f6c4b0b7f7d8ad648789b2b9b", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 75, "avg_line_length": 23.333333333333332, "alnum_prop": 0.7414285714285714, "repo_name": "quattor/pan", "id": "071c9f246597bf6d40753075e8bda1ac31489881", "size": "1534", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "panc/src/main/java/org/quattor/pan/output/JsonGzipFormatter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "27791" }, { "name": "HTML", "bytes": "17882" }, { "name": "Java", "bytes": "1672415" }, { "name": "Pan", "bytes": "26581489" }, { "name": "Perl", "bytes": "25023" }, { "name": "PostScript", "bytes": "59921" }, { "name": "Python", "bytes": "52540" }, { "name": "Shell", "bytes": "1513" }, { "name": "Vim script", "bytes": "12427" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>socketio test</title> </head> <body> <div id="qrcode"></div> Test </body> <script src="http://s4.qhimg.com/static/535dde855bc726e2/socket.io-1.2.0.js"></script> <script src="/static/js/remote-server.js"></script> <script> var rs = new RemoteServer({ eventList: ['keydown', 'swipeleft'] }); /*rs.on('orientationchange', function f(data){ console.log(data); //rs.off('keydown', f); }); rs.on('motionchange', function f(data){ console.log(data); //rs.off('keydown', f); });*/ rs.on('keydown', function f(data){ console.log(data); //rs.off('keydown', f); }); rs.on('client_connected', function f(data){ console.log('client', data); //rs.off('keydown', f); }); rs.on('swipeleft', function f(data){ console.log(data); //rs.off('keydown', f); }); rs.on('pinchout', function f(data){ console.log(data); //rs.off('keydown', f); }); rs.on('left', function f(data){ console.log(data); }); rs.drawQRCode(); </script> </html>
{ "content_hash": "257fec0a9fca5d382d2d4e9d43649b37", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 86, "avg_line_length": 20.44, "alnum_prop": 0.6252446183953033, "repo_name": "akira-cn/remote", "id": "749cac739e8ba3ef9c86dcee75ee5160e52cd0b9", "size": "1022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "socketio/server/view/home/socketio_test.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "199548" }, { "name": "HTML", "bytes": "228855" }, { "name": "JavaScript", "bytes": "633118" }, { "name": "Nginx", "bytes": "822" } ], "symlink_target": "" }
module Ebay # :nodoc: module Types # :nodoc: # == Attributes # boolean_node :unsuccessful_bidder_notice_include_my_items, 'UnsuccessfulBidderNoticeIncludeMyItems', 'true', 'false', :optional => true class BidderNoticePreferences include XML::Mapping include Initializer root_element_name 'BidderNoticePreferences' boolean_node :unsuccessful_bidder_notice_include_my_items, 'UnsuccessfulBidderNoticeIncludeMyItems', 'true', 'false', :optional => true end end end
{ "content_hash": "f15273e30cd3d20d98c0ae35117f013a", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 142, "avg_line_length": 36.357142857142854, "alnum_prop": 0.7210216110019646, "repo_name": "Sellbrite/ebay", "id": "71b698e55921d40fb0b230c004081697be06efd6", "size": "510", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "lib/ebay/types/bidder_notice_preferences.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1809" }, { "name": "Ruby", "bytes": "1265650" } ], "symlink_target": "" }
class Libdc1394GrabberFramerateHelper { public: static dc1394framerate_t numToDcLibFramerate( int rateNum ); static const char* DcLibFramerateToString( dc1394framerate_t _framerate ); }; #endif
{ "content_hash": "917cb539104f16fb041c76153ca0cb1b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 75, "avg_line_length": 20, "alnum_prop": 0.8, "repo_name": "HellicarAndLewis/DivideByZero", "id": "113fc89270f54f1358890fe6699fe06b00e09d00", "size": "364", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "addons/ofxVideoGrabberFromTheoNoGUI/src/Libdc1394Grabber/Libdc1394GrabberFramerateHelper.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "109500" }, { "name": "C++", "bytes": "459126" } ], "symlink_target": "" }
package com.prometheus.controller; import static org.springframework.web.bind.annotation.RequestMethod.GET; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.prometheus.domain.JwtApplication; import com.prometheus.domain.repo.JwtApplicationRepo; @RestController @RequestMapping("/application") @PreAuthorize("hasRole('ADMIN')") public class ApplicationController { @Autowired private JwtApplicationRepo jwtApplicationRepo; @RequestMapping(value = "/all", method = GET) public ResponseEntity<List<JwtApplication>> getAllApplications() { return ResponseEntity.ok(jwtApplicationRepo.findAll()); } @RequestMapping(value = "/{name}", method = GET) public ResponseEntity<JwtApplication> getApplicationByName(@PathVariable String name) { return ResponseEntity.ok(jwtApplicationRepo.findByName(name).get()); } }
{ "content_hash": "39b09e0f0a957d95761b491d0236f213", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 88, "avg_line_length": 33.48571428571429, "alnum_prop": 0.8191126279863481, "repo_name": "wellingWilliam/prometheus", "id": "b2db127d8c4851df6e0a18285beea18187594a4f", "size": "1172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "admin/src/main/java/com/prometheus/controller/ApplicationController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "147794" } ], "symlink_target": "" }
module Chewy class Strategy # The strategy works the same way as atomic, but performs # async index update driven by sidekiq # # Chewy.strategy(:sidekiq) do # User.all.map(&:save) # Does nothing here # Post.all.map(&:save) # And here # # It imports all the changed users and posts right here # end # class Sidekiq < Atomic class Worker include ::Sidekiq::Worker def perform(type, ids, options = {}) options[:refresh] = !Chewy.disable_refresh_async if Chewy.disable_refresh_async type.constantize.import!(ids, options) end end def leave @stash.each do |type, ids| next if ids.empty? ::Sidekiq::Client.push( 'queue' => sidekiq_queue, 'class' => Chewy::Strategy::Sidekiq::Worker, 'args' => [type.name, ids] ) end end private def sidekiq_queue Chewy.settings.fetch(:sidekiq, {})[:queue] || 'chewy' end end end end
{ "content_hash": "ee697cdfdade60e0f84e3eab7396b17c", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 89, "avg_line_length": 26.325, "alnum_prop": 0.5584045584045584, "repo_name": "zenedge/chewy", "id": "198a6eb2ab2757b88006a1c140ff5964066442d9", "size": "1053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/chewy/strategy/sidekiq.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "736008" } ], "symlink_target": "" }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:layout_centerInParent="true" tools:context="ch.isageek.tyderion.habittracker.item.AddItemActivity"> <fragment android:layout_width="wrap_content" android:layout_height="wrap_content" android:name="ch.isageek.tyderion.habittracker.item.AddItemFragment" android:id="@+id/add_item_fragment" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" tools:layout="@layout/fragment_add_item" /> </RelativeLayout>
{ "content_hash": "1c24765e4d05ed4f21013bc35ab31758", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 76, "avg_line_length": 45.30434782608695, "alnum_prop": 0.7284069097888676, "repo_name": "Tyderion/habit-tracker", "id": "9a5d80dcb31cab2b4aca298e0d5aed6a054155a7", "size": "1042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tracker/src/main/res/layout/activity_add_item.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "2349" }, { "name": "Java", "bytes": "773977" } ], "symlink_target": "" }
using Nest.Resolvers.Converters; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nest { [JsonConverter(typeof(ReadAsTypeConverter<TriggerEventContainer>))] public interface ITriggerEventContainer : INestSerializable { [JsonProperty("schedule")] IScheduleTriggerEvent Schedule { get; set; } } [JsonObject] public class TriggerEventContainer : ITriggerEventContainer { public TriggerEventContainer() { } public TriggerEventContainer(TriggerEventBase trigger) { trigger.ContainIn(this); } IScheduleTriggerEvent ITriggerEventContainer.Schedule { get; set; } } public class TriggerEventDescriptor : TriggerEventContainer { private ITriggerEventContainer Self { get { return this; } } public TriggerEventDescriptor Schedule(Func<ScheduleTriggerEventDescriptor, IScheduleTriggerEvent> selector) { Self.Schedule = selector(new ScheduleTriggerEventDescriptor()); return this; } } }
{ "content_hash": "9b360c03122221abd9c7047d15915e1e", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 110, "avg_line_length": 23.209302325581394, "alnum_prop": 0.779559118236473, "repo_name": "CSGOpenSource/elasticsearch-watcher-net", "id": "721da400986a2f3ef55f9292d897ad63a7d3f0d5", "size": "1000", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Nest.Watcher/Domain/Trigger/TriggerEventContainer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2239" }, { "name": "C#", "bytes": "392385" }, { "name": "F#", "bytes": "15612" }, { "name": "PowerShell", "bytes": "3797" }, { "name": "Shell", "bytes": "1869" } ], "symlink_target": "" }
@interface MMAppDelegate () @property NSMutableArray *windowControllers; @end //------------------------------------------------------------------------------ @implementation MMAppDelegate //------------------------------------------------------------------------------ #pragma mark - NSApplicationDelegate //------------------------------------------------------------------------------ - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/%@", NSHomeDirectory(), [[NSProcessInfo processInfo] processName]]]; [NSURLCache setSharedURLCache:URLCache]; [MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@ "MyDatabase.sqlite"]; [[AFHTTPRequestOperationLogger sharedLogger] setLevel:AFLoggerLevelDebug]; // [[AFHTTPRequestOperationLogger sharedLogger] startLogging]; _windowControllers = [NSMutableArray new]; [self newWindow:self]; } - (void)applicationWillTerminate:(NSNotification *)notification { [MagicalRecord cleanUp]; } - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return NO; } - (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag { NSWindowController *controller = [self.windowControllers lastObject]; if (controller) { [controller showWindow:self]; } else { [self newWindow:self]; } return YES; } //------------------------------------------------------------------------------ #pragma mark - IBActions //------------------------------------------------------------------------------ - (IBAction)newWindow:(id)sender { MMMainWindowController *controller = [MMMainWindowController new]; [self.windowControllers addObject:controller]; [controller showWindow:self]; } - (IBAction)openPreferences:(id)sender; { [self.preferencesWindowController showWindow:self]; } - (IBAction)reloadData:(id)sender; { id controller = [self currentWindowController]; if ([controller respondsToSelector:@selector(reloadData:)]) { [controller reloadData:sender]; } } //------------------------------------------------------------------------------ #pragma mark - Menu Validation //------------------------------------------------------------------------------ -(BOOL)validateMenuItem:(NSMenuItem*)theMenuItem { BOOL enable = [self respondsToSelector:[theMenuItem action]]; if ([theMenuItem action] == @selector(newDocument:)) { enable = NO; } return enable; } //------------------------------------------------------------------------------ #pragma mark - Window Controllers //------------------------------------------------------------------------------ @synthesize preferencesWindowController = _preferencesWindowController; - (NSWindowController *)preferencesWindowController { if (_preferencesWindowController == nil) { NSViewController *generalViewController = [[MMGeneralPreferencesViewController alloc] initWithNibName:@"MMGeneralPreferencesViewController" bundle:nil]; NSArray *controllers = @[generalViewController]; NSString *title = NSLocalizedString(@"Preferences", @"Common title for Preferences window"); _preferencesWindowController = [[MASPreferencesWindowController alloc] initWithViewControllers:controllers title:title]; } return _preferencesWindowController; } - (id)currentWindowController { return [[NSApp keyWindow] windowController]; } @end
{ "content_hash": "e9c51db2229877d9eea1082583456568", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 183, "avg_line_length": 31.059322033898304, "alnum_prop": 0.5939972714870395, "repo_name": "holgersindbaek/Marshmallow", "id": "12b0b66be075ea429f686dd2f7526786e588f3ec", "size": "4151", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Marshmallow/MMAppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "4151" }, { "name": "Objective-C", "bytes": "76922" }, { "name": "Ruby", "bytes": "1364" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint</artifactId> <version>2.5.0-SNAPSHOT</version> </parent> <artifactId>pinpoint-profiler-logging</artifactId> <packaging>jar</packaging> <description>pinpoint profiler logging system</description> <properties> <jdk.version>1.8</jdk.version> <jdk.home>${env.JAVA_8_HOME}</jdk.home> </properties> <dependencies> <dependency> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint-annotations</artifactId> </dependency> <dependency> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint-commons</artifactId> </dependency> <dependency> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint-bootstrap-core</artifactId> </dependency> <dependency> <groupId>com.navercorp.pinpoint</groupId> <artifactId>pinpoint-bootstrap</artifactId> </dependency> <!-- Logging depedencies --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> </plugins> </build> </project>
{ "content_hash": "d6a117d3a6eee60e00ae6ff9b8ccefd8", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 108, "avg_line_length": 32.65079365079365, "alnum_prop": 0.5984443364122508, "repo_name": "jaehong-kim/pinpoint", "id": "0dcdb664aed96e209dfe6d7731fff5e10c08801f", "size": "2057", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "profiler-logging/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "200" }, { "name": "CSS", "bytes": "213428" }, { "name": "Groovy", "bytes": "1423" }, { "name": "HTML", "bytes": "201094" }, { "name": "Java", "bytes": "19678613" }, { "name": "JavaScript", "bytes": "6008" }, { "name": "Kotlin", "bytes": "1327" }, { "name": "Shell", "bytes": "9993" }, { "name": "TSQL", "bytes": "978" }, { "name": "Thrift", "bytes": "15920" }, { "name": "TypeScript", "bytes": "1672276" } ], "symlink_target": "" }