repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
sinnwerkstatt/common-good-online-balance
static/css/main.css
7145
/* Colors */ /* Font Sizes */ /* Borders */ /* Buttons */ /* Distances */ /* @import must be at top of file, otherwise CSS will not work */ /* @font-face { font-family: 'deliusregular'; src: url('../fonts/delius-regular-webfont.eot'); src: url('../fonts/delius-regular-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/delius-regular-webfont.woff') format('woff'), url('../fonts/delius-regular-webfont.ttf') format('truetype'), url('../fonts/delius-regular-webfont.svg#deliusregular') format('svg'); font-weight: normal; font-style: normal; } */ /* Colors */ /* Font Sizes */ /* Borders */ /* Buttons */ /* Distances */ /* Sticky footer styles -------------------------------------------------- */ html { position: relative; min-height: 100%; } body { /* Margin bottom by footer height */ margin-bottom: 40px; } #footer { position: absolute; bottom: 0; width: 100%; left: 0; /* Set the fixed height of the footer here */ /*height: 40px;*/ padding-top: 10px; padding-bottom: .75em; border-top: 1px solid #EEEEEE; font-size: 0.9em; background-color: white; color: #a2a2a2; } #footer li { display: inline; margin-right: 1.5em; } /* Font-Sizes -------------------------------------------------- */ html { font-size: 14px; } @media (max-width: 900px) { html { font-size: 12px; } } @media (max-width: 400px) { html { font-size: 10px; } } /* Type will scale with modules */ h1 { font-size: 3em; } h2 { font-size: 2.5em; } h3 { font-size: 2em; } /* Bootstrap Adjustments */ .breadcrumb { padding: 0; } .navbar a.navbar-brand { padding: 5px; } /* * Fixes showing dropdown menu when slowly hovering it. */ .breadcrumb > li { display: inline-block; } .breadcrumb > li + li:before { padding: 0 5px; color: #a2a2a2; content: "\003E"; } .breadcrumb > .active { color: #a2a2a2; } .breadcrumb a { color: #a2a2a2; } /* GENERAL */ img { border: 0 none; height: auto; max-width: 100%; vertical-align: middle; } img.left { float: left; margin-right: 40px; } img.right { float: right; margin-left: 40px; } .img-center { display: block; margin-left: auto; margin-right: auto; } .img-link { /* remove outline for Firefox */ outline: none; -moz-outline-style: none; } .img-link:focus { /* remove outline for Firefox */ outline: none; -moz-outline-style: none; } .displaynone { display: none; } .display-none { display: none; } .clearfix:before, .clearfix:after { content: " "; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } .clearboth { clear: both; } .pointer { cursor: pointer; } .header-end { clear: both; } .center { text-align: center; } .text-right { text-align: right; } .word-wrap { -moz-hyphens: auto; word-wrap: break-word; } .no-decoration { text-decoration: none; color: inherit; } .no-decoration:hover { text-decoration: none; } .unselectable { -webkit-user-select: none; /* Chrome all / Safari all */ -moz-user-select: none; /* Firefox all */ -ms-user-select: none; /* IE 10+ */ /* No support for these yet, use at own risk */ -o-user-select: none; user-select: none; } .centered-text-to-img { position: relative; top: 5px; font-size: 2em; } .centered-text-to-img--smaller { position: relative; top: 2px; font-size: 1.2em; } .centered-text-to-no-img { position: relative; top: 25px; font-size: 2em; } .space-left { margin-left: 15px; } /* FORMS */ .page-form { padding-top: 20px; } .form-group { padding-bottom: 10px; } .form-group .controls { margin-bottom: 10px; } .control-label { padding-top: 8px; } .control-label .asteriskField { padding-left: 2px; } .asteriskField { color: #bd2c00; } .glyphicon.glyphicon-grey { color: #cccccc; } .glyphicon.glyphicon-grey:hover { color: #a2a2a2; } .glyphicon.glyphicon-grey__no_hover { color: #cccccc; cursor: default; } .glyphicon.glyphicon-greyer { color: #a2a2a2; } .last-form-element { padding-bottom: 15px; } .p-top { padding-top: 10px; } .m-top { margin-top: 10px; } .m-bottom { margin-bottom: 10px; } .width-half { width: 49%; } .django-select2.form-control { padding: 0; border: 0; } /* Colors */ /* Font Sizes */ /* Borders */ /* Buttons */ /* Distances */ .ecg-violet { background-color: #c54d94; color: white; } .ecg-green { color: #cccb98; } .ecg-green-bg { background-color: #cccb98; color: white; } .ecg-green-b { color: #cccb98; font-weight: bold; } .ecg-blue { color: #99cccc; } .ecg-blue-b { color: #99cccc; font-weight: bold; } .negative-color { color: #de6b3c; } .negative-color-b { color: #de6b3c; font-weight: bold; } /* Colors */ /* Font Sizes */ /* Borders */ /* Buttons */ /* Distances */ .button { display: inline-block; position: relative; padding: 7px 15px; font-size: 13px; font-weight: bold; vertical-align: middle; white-space: nowrap; cursor: pointer; background-color: #eaeaea; background-image: linear-gradient(white, #eaeaea); background-repeat: repeat-x; border-color: #e5e5e5; border-image: none; border-radius: 3px; border-style: solid; border-width: 1px; outline: medium none; color: #333333; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.898); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); } .button:hover { background-color: #e0e0e0; background-image: linear-gradient(white, #e0e0e0); background-repeat: repeat-x; border-color: #dbdbdb; color: #333333; text-decoration: none; } .button:active, .button.selected { background-color: #e0e0e0; background-image: none; border-color: #d1d1d1; text-decoration: none; } .button:disabled, .button:disabled:hover, .button.disabled, .button.disabled:hover { background-color: #eaeaea; background-image: none; border-color: #C5C5C5; box-shadow: none; color: #666666; opacity: 0.5; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.898); cursor: default; } .button.primary { background-color: #60b044; background-image: linear-gradient(#9cd189, #60b044); background-repeat: repeat-x; border-color: #5ca941; color: white; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .button.primary:hover { background-color: #58a13e; background-image: linear-gradient(#8fcc7a, #58a13e); background-repeat: repeat-x; border-color: #549a3b; color: white; } .button.primary:active, .button.primary.selected { background-color: #58a13e; background-image: none; border-color: #4c8b36; } .button.primary:disabled, .button.primary:disabled:hover, .button.primary.disabled, .button.primary.disabled:hover { background-color: #60b044; background-image: linear-gradient(#9cd189, #60b044); background-repeat: repeat-x; border-color: #70bd55 #70bd55 #509339; color: white; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } /* pesticide v0.1.0 . @mrmrs . MIT */ #wrap { padding-bottom: 60px; } .button > .glyphicon { margin-right: 5px; } .panel-group .panel { border: none; } .panel-group .panel + .panel { margin-top: 0; } .cke_editable { border: 1px solid #e3e3e3; border-radius: 4px; }
mit
GuanLee1990/DotMaysWind.Data
DotMaysWind.Data.Test/Program.cs
465
using System; using System.Collections.Generic; using System.Windows.Forms; namespace DotMaysWind.Data.Test { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
mit
tsteinholz/CPP-SRHS
Libraries/allegro5-5.1/demos/skater/src/level_file.h
403
#ifndef __LVLFILE_H #define __LVLFILE_H #include "level.h" void LoadMaterials(struct Level *NewLev); void LoadVertices(struct Level *NewLev); void LoadTriangles(struct Level *NewLev, int radius); void LoadObjectTypes(struct Level *NewLev, int radius); void LoadObjects(struct Level *NewLev); void LoadStats(struct Level *NewLev); extern int GetNormal(struct Edge *e, double *v1, double *v2); #endif
mit
michaeljbaird/Fluky
src/Fluky/Randomizer.Distribution.cs
6560
using System; using Fluky.Extensions; using Fluky.Types; namespace Fluky { public partial class Randomizer { public float DistributionNormal(float mean, float standardDeviation) { // Get random normal from Standard Normal Distribution var randomNormalNumber = DistributionStandardNormal(); // Stretch distribution to the requested sigma variance randomNormalNumber *= standardDeviation; // Shift mean to requested mean: randomNormalNumber += mean; // now you have a number selected from a normal distribution with requested mean and sigma! return randomNormalNumber; } public float DistributionStandardNormal() { // This code follows the polar form of the muller transform: // https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Polar_form // also known as Marsaglia polar method // https://en.wikipedia.org/wiki/Marsaglia_polar_method // calculate points on a circle float u, v; float s; // this is the hypotenuse squared. do { u = Float(-1, 1); v = Float(-1, 1); s = (u * u) + (v * v); } while (!(Math.Abs(s) > 0.001f && s < 1)); // keep going until s is nonzero and less than one // TODO: allow a user to specify how many random numbers they want! // choose between u and v for seed (z0 vs z1) var seed = Integer(0, 2) == 0 ? u : v; // create normally distributed number. var z = (seed * Math.Sqrt(-2.0f * Math.Log(s) / s)); var result = z.ToFloat(); return result; } //-------------------------------------------------------------------------------------------- // Sloped Distribution //-------------------------------------------------------------------------------------------- public float DistributionRangeSlope(float min, float max, float skew, DistributionDirection direction) { return min + DistributionSloped(skew, direction) * (max - min); } public float DistributionSloped(float skew, DistributionDirection direction) { // the difference in scale is just the same as the max y-value.. var maxY = skew; // our curve will go from 0 to max_x. var maxX = Inverse_Sec_Sqrd(maxY); var maxCdf = Sec_Sqrd_CumulativeDistributionFunction(maxX); var u = Float(0, maxCdf); var xVal = Sec_Sqrd_InverseCumulativeDistributionFunction(u); // scale to [0,1] var value = xVal / maxX; if (direction == DistributionDirection.Left) value = 1.0f - value; return value; } //-------------------------------------------------------------------------------------------- // Linear Distribution //-------------------------------------------------------------------------------------------- // Returns random in range [min, max] with linear distribution of given slope. public float DistributionRangeLinear(float min, float max, float slope) { var val = DistributionRandomLinear(slope); return min + (max - min) * val; } // Returns random in range [0,1] with linear distribution of given slope. public float DistributionRandomLinear(float slope) { var absValue = DistributionLinearWithPositiveSlope(Math.Abs(slope)); if (slope < 0) return 1 - absValue; return absValue; } private float DistributionLinearWithPositiveSlope(float slope) { if (Math.Abs(slope) < 0.001f) return Float(0.0f, 1.0f); float x, y; do { x = Float(0.0f, 1.0f); y = Float(0.0f, 1.0f); if (slope < 1) { y -= (1 - slope) / 2.0f; } } while (y > x * slope); return x; } //-------------------------------------------------------------------------------------------- // Exponential Distribution //-------------------------------------------------------------------------------------------- public float DistributionExponentialRange(float min, float max, float exponent, DistributionDirection direction) { return min + DistributionExponential(exponent, direction) * (max - min); } public float DistributionExponential(float exponent, DistributionDirection direction) { // our curve will go from 0 to 1. var maxCdf = ExponentialRightCdf(1.0f, exponent); var u = Float(0.0f, maxCdf); var xVal = EponentialRightInverseCDF(u, exponent); if (direction == DistributionDirection.Left) xVal = 1.0f - xVal; return xVal; } // The inverse of the curve. private float DistributionExponentialRightInverse(float y, float exponent) { return Math.Pow(y, 1.0f / exponent).ToFloat(); } // The integral of the exponent curve. private static float ExponentialRightCdf(float x, float exponent) { var integralExp = exponent + 1.0f; var exponentialRightCdf = (Math.Pow(x, integralExp)) / integralExp; return exponentialRightCdf.ToFloat(); } // The inverse of the integral of the exponent curve. private static float EponentialRightInverseCDF(float x, float exponent) { var integralExp = exponent + 1.0f; return Math.Pow(integralExp * x, 1.0f / integralExp).ToFloat(); } /// <summary> /// The inverse of the sec^2 function. /// </summary> /// <param name="y">The y coordinate. if y < 1, returns NaN. </param> private float Inverse_Sec_Sqrd(float y) { // Note: arcsec(x) = arccos(1/x) // return arcsec(sqrt(y)) var inverseSecSqrd = Math.Acos(1.0f / Math.Sqrt(y)); return inverseSecSqrd.ToFloat(); } /// <summary> /// The integral of sec^2 /// </summary> /// <param name="x"></param> /// <returns></returns> private static float Sec_Sqrd_CumulativeDistributionFunction(float x) { // The cumulative distribution function for sec^2 is just the definite integral of sec^2(x) = tan(x) - tan(0) = tan(x) return Math.Tan(x).ToFloat(); } /// <summary> /// The inverse of the integral of sec^2 /// </summary> /// <param name="x"></param> /// <returns></returns> private static float Sec_Sqrd_InverseCumulativeDistributionFunction(float x) { // The cumulative distribution function for sec^2 is just the definite integral of sec^2(x) = tan(x) - tan(0) = tan(x) // Then the Inverse cumulative distribution function is just atan(x) return Math.Atan(x).ToFloat(); } } }
mit
MTASZTAKI/ApertusVR
plugins/render/ogreRender/3rdParty/ogre/OgreMain/include/OgreParticleEmitter.h
28251
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2016 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #ifndef __ParticleEmitter_H__ #define __ParticleEmitter_H__ #include "OgrePrerequisites.h" #include "OgreVector3.h" #include "OgreColourValue.h" #include "OgreStringInterface.h" #include "OgreParticleEmitterCommands.h" #include "OgreParticle.h" #include "OgreHeaderPrefix.h" namespace Ogre { /** \addtogroup Core * @{ */ /** \addtogroup Effects * @{ */ /** Abstract class defining the interface to be implemented by particle emitters. @remarks Particle emitters are the sources of particles in a particle system. This class defines the ParticleEmitter interface, and provides a basic implementation for tasks which most emitters will do (these are of course overridable). Particle emitters can be grouped into types, e.g. 'point' emitters, 'box' emitters etc; each type will create particles with a different starting point, direction and velocity (although within the types you can configure the ranges of these parameters). @par Because there are so many types of emitters you could use, OGRE chooses not to dictate the available types. It comes with some in-built, but allows plugins or applications to extend the emitter types available. This is done by subclassing ParticleEmitter to have the appropriate emission behaviour you want, and also creating a subclass of ParticleEmitterFactory which is responsible for creating instances of your new emitter type. You register this factory with the ParticleSystemManager using addEmitterFactory, and from then on emitters of this type can be created either from code or through text particle scripts by naming the type. @par This same approach is used for ParticleAffectors (which modify existing particles per frame). This means that OGRE is particularly flexible when it comes to creating particle system effects, with literally infinite combinations of emitter and affector types, and parameters within those types. */ class _OgreExport ParticleEmitter : public StringInterface, public Particle { protected: // Command object for setting / getting parameters static EmitterCommands::CmdAngle msAngleCmd; static EmitterCommands::CmdColour msColourCmd; static EmitterCommands::CmdColourRangeStart msColourRangeStartCmd; static EmitterCommands::CmdColourRangeEnd msColourRangeEndCmd; static EmitterCommands::CmdDirection msDirectionCmd; static EmitterCommands::CmdUp msUpCmd; static EmitterCommands::CmdDirPositionRef msDirPositionRefCmd; static EmitterCommands::CmdEmissionRate msEmissionRateCmd; static EmitterCommands::CmdMaxTTL msMaxTTLCmd; static EmitterCommands::CmdMaxVelocity msMaxVelocityCmd; static EmitterCommands::CmdMinTTL msMinTTLCmd; static EmitterCommands::CmdMinVelocity msMinVelocityCmd; static EmitterCommands::CmdPosition msPositionCmd; static EmitterCommands::CmdTTL msTTLCmd; static EmitterCommands::CmdVelocity msVelocityCmd; static EmitterCommands::CmdDuration msDurationCmd; static EmitterCommands::CmdMinDuration msMinDurationCmd; static EmitterCommands::CmdMaxDuration msMaxDurationCmd; static EmitterCommands::CmdRepeatDelay msRepeatDelayCmd; static EmitterCommands::CmdMinRepeatDelay msMinRepeatDelayCmd; static EmitterCommands::CmdMaxRepeatDelay msMaxRepeatDelayCmd; static EmitterCommands::CmdName msNameCmd; static EmitterCommands::CmdEmittedEmitter msEmittedEmitterCmd; /// Parent particle system ParticleSystem* mParent; /// Position relative to the center of the ParticleSystem Vector3 mPosition; /// Rate in particles per second at which this emitter wishes to emit particles Real mEmissionRate; /// Name of the type of emitter, MUST be initialised by subclasses String mType; /// Base direction of the emitter, may not be used by some emitters Vector3 mDirection; /// Notional up vector, used to speed up generation of variant directions, and also to orient some emitters. Vector3 mUp; /// When true, mDirPositionRef is used instead of mDirection to generate particles bool mUseDirPositionRef; /* Center position to tell in which direction will particles be emitted according to their position, useful for explosions & implosions, some emitters (i.e. point emitter) may not need it. */ Vector3 mDirPositionRef; /// Angle around direction which particles may be emitted, internally radians but angleunits for interface Radian mAngle; /// Min speed of particles Real mMinSpeed; /// Max speed of particles Real mMaxSpeed; /// Initial time-to-live of particles (min) Real mMinTTL; /// Initial time-to-live of particles (max) Real mMaxTTL; /// Initial colour of particles (range start) ColourValue mColourRangeStart; /// Initial colour of particles (range end) ColourValue mColourRangeEnd; /// Whether this emitter is currently enabled (defaults to true) bool mEnabled; /// Start time (in seconds from start of first call to ParticleSystem to update) Real mStartTime; /// Minimum length of time emitter will run for (0 = forever) Real mDurationMin; /// Maximum length of time the emitter will run for (0 = forever) Real mDurationMax; /// Current duration remainder Real mDurationRemain; /// Time between each repeat Real mRepeatDelayMin; Real mRepeatDelayMax; /// Repeat delay left Real mRepeatDelayRemain; // Fractions of particles wanted to be emitted last time Real mRemainder; /// The name of the emitter. The name is optional unless it is used as an emitter that is emitted itself. String mName; /// The name of the emitter to be emitted (optional) String mEmittedEmitter; // If 'true', this emitter is emitted by another emitter. // NB. That doesn't imply that the emitter itself emits other emitters (that could or could not be the case) bool mEmitted; // NB Method below here are to help out people implementing emitters by providing the // most commonly used approaches as piecemeal methods /** Internal utility method for generating particle exit direction @param destVector Reference to vector to complete with new direction (normalised) */ virtual void genEmissionDirection( const Vector3 &particlePos, Vector3& destVector ); /** Internal utility method to apply velocity to a particle direction. @param destVector The vector to scale by a randomly generated scale between min and max speed. Assumed normalised already, and likely already oriented in the right direction. */ virtual void genEmissionVelocity(Vector3& destVector); /** Internal utility method for generating a time-to-live for a particle. */ virtual Real genEmissionTTL(void); /** Internal utility method for generating a colour for a particle. */ virtual void genEmissionColour(ColourValue& destColour); /** Internal utility method for generating an emission count based on a constant emission rate. */ virtual unsigned short genConstantEmissionCount(Real timeElapsed); /** Internal method for setting up the basic parameter definitions for a subclass. @remarks Because StringInterface holds a dictionary of parameters per class, subclasses need to call this to ask the base class to add it's parameters to their dictionary as well. Can't do this in the constructor because that runs in a non-virtual context. @par The subclass must have called it's own createParamDictionary before calling this method. */ void addBaseParameters(void); /** Internal method for initialising the duration & repeat of an emitter. */ void initDurationRepeat(void); public: ParticleEmitter(ParticleSystem* psys); /** Virtual destructor essential. */ virtual ~ParticleEmitter(); /** Sets the position of this emitter relative to the particle system center. */ virtual void setPosition(const Vector3& pos); /** Returns the position of this emitter relative to the center of the particle system. */ virtual const Vector3& getPosition(void) const; /** Sets the direction of the emitter. @remarks Most emitters will have a base direction in which they emit particles (those which emit in all directions will ignore this parameter). They may not emit exactly along this vector for every particle, many will introduce a random scatter around this vector using the angle property. @note This resets the up vector. @param direction The base direction for particles emitted. */ virtual void setDirection(const Vector3& direction); /** Returns the base direction of the emitter. */ virtual const Vector3& getDirection(void) const; /** Sets the notional up vector of the emitter @remarks Many emitters emit particles from within a region, and for some that region is not circularly symmetric about the emitter direction. The up vector allows such emitters to be orientated about the direction vector. @param up The base direction for particles emitted. It must be perpendicular to the direction vector. */ virtual void setUp(const Vector3& up); /** Returns the up vector of the emitter. */ virtual const Vector3& getUp(void) const; /** Sets the direction of the emitter. Some particle effects need to emit particles in many random directions, but still following some rules; like not having them collide against each other. Very useful for explosions and implosions (when velocity is negative) @note Although once enabled mDirPositionRef will supersede mDirection; calling setDirection() may still be needed to setup a custom up vector. @param position The reference position in which the direction of the particles will be calculated from, also taking into account the particle's position at the time of emission. @param enable True to use mDirPositionRef, false to use the default behaviour with mDirection */ virtual void setDirPositionReference( const Vector3& position, bool enable ); /** Returns the position reference to generate direction of emitted particles */ virtual const Vector3& getDirPositionReference() const; /** Returns whether direction or position reference is used */ virtual bool getDirPositionReferenceEnabled() const; /** Sets the maximum angle away from the emitter direction which particle will be emitted. @remarks Whilst the direction property defines the general direction of emission for particles, this property defines how far the emission angle can deviate away from this base direction. This allows you to create a scatter effect - if set to 0, all particles will be emitted exactly along the emitters direction vector, whereas if you set it to 180 degrees or more, particles will be emitted in a sphere, i.e. in all directions. @param angle Maximum angle which initial particle direction can deviate from the emitter base direction vector. */ virtual void setAngle(const Radian& angle); /** Returns the maximum angle which the initial particle direction can deviate from the emitters base direction. */ virtual const Radian& getAngle(void) const; /** Sets the initial velocity of particles emitted. @remarks This method sets a constant speed for emitted particles. See the alternate version of this method which takes 2 parameters if you want a variable speed. @param speed The initial speed in world units per second which every particle emitted starts with. */ virtual void setParticleVelocity(Real speed); /** Sets the initial velocity range of particles emitted. @remarks This method sets the range of starting speeds for emitted particles. See the alternate version of this method which takes 1 parameter if you want a constant speed. This emitter will randomly choose a speed between the minimum and maximum for each particle. @param max The maximum speed in world units per second for the initial particle speed on emission. @param min The minimum speed in world units per second for the initial particle speed on emission. */ virtual void setParticleVelocity(Real min, Real max); /** Returns the minimum particle velocity. */ virtual void setMinParticleVelocity(Real min); /** Returns the maximum particle velocity. */ virtual void setMaxParticleVelocity(Real max); /** Returns the initial velocity of particles emitted. */ virtual Real getParticleVelocity(void) const; /** Returns the minimum particle velocity. */ virtual Real getMinParticleVelocity(void) const; /** Returns the maximum particle velocity. */ virtual Real getMaxParticleVelocity(void) const; /** Sets the emission rate for this emitter. @remarks This method tells the emitter how many particles per second should be emitted. The emitter subclass does not have to emit these in a continuous burst - this is a relative parameter and the emitter may choose to emit all of the second's worth of particles every half-second for example. This is controlled by the emitter's getEmissionCount method. @par Also, if the ParticleSystem's particle quota is exceeded, not all the particles requested may be actually emitted. @param particlesPerSecond The number of particles to be emitted every second. */ virtual void setEmissionRate(Real particlesPerSecond); /** Returns the emission rate set for this emitter. */ virtual Real getEmissionRate(void) const; /** Sets the lifetime of all particles emitted. @remarks The emitter initialises particles with a time-to-live (TTL), the number of seconds a particle will exist before being destroyed. This method sets a constant TTL for all particles emitted. Note that affectors are able to modify the TTL of particles later. @par Also see the alternate version of this method which takes a min and max TTL in order to have the TTL vary per particle. @param ttl The number of seconds each particle will live for. */ virtual void setTimeToLive(Real ttl); /** Sets the range of lifetime for particles emitted. @remarks The emitter initialises particles with a time-to-live (TTL), the number of seconds a particle will exist before being destroyed. This method sets a range for the TTL for all particles emitted; the ttl may be randomised between these 2 extremes or will vary some other way depending on the emitter. Note that affectors are able to modify the TTL of particles later. @par Also see the alternate version of this method which takes a single TTL in order to set a constant TTL for all particles. @param minTtl The minimum number of seconds each particle will live for. Must be non-negative! @param maxTtl The maximum number of seconds each particle will live for. Must be non-negative! */ virtual void setTimeToLive(Real minTtl, Real maxTtl); /** Sets the minimum time each particle will live for. Must be non-negative! */ virtual void setMinTimeToLive(Real min); /** Sets the maximum time each particle will live for. Must be non-negative! */ virtual void setMaxTimeToLive(Real max); /** Gets the time each particle will live for. */ virtual Real getTimeToLive(void) const; /** Gets the minimum time each particle will live for. */ virtual Real getMinTimeToLive(void) const; /** Gets the maximum time each particle will live for. */ virtual Real getMaxTimeToLive(void) const; /** Sets the initial colour of particles emitted. @remarks Particles have an initial colour on emission which the emitter sets. This method sets this colour. See the alternate version of this method which takes 2 colours in order to establish a range of colours to be assigned to particles. @param colour The colour which all particles will be given on emission. */ virtual void setColour(const ColourValue& colour); /** Sets the range of colours for emitted particles. @remarks Particles have an initial colour on emission which the emitter sets. This method sets the range of this colour. See the alternate version of this method which takes a single colour in order to set a constant colour for all particles. Emitters may choose to randomly assign a colour in this range, or may use some other method to vary the colour. @param colourStart The start of the colour range @param colourEnd The end of the colour range */ virtual void setColour(const ColourValue& colourStart, const ColourValue& colourEnd); /** Sets the minimum colour of particles to be emitted. */ virtual void setColourRangeStart(const ColourValue& colour); /** Sets the maximum colour of particles to be emitted. */ virtual void setColourRangeEnd(const ColourValue& colour); /** Gets the colour of particles to be emitted. */ virtual const ColourValue& getColour(void) const; /** Gets the minimum colour of particles to be emitted. */ virtual const ColourValue& getColourRangeStart(void) const; /** Gets the maximum colour of particles to be emitted. */ virtual const ColourValue& getColourRangeEnd(void) const; /** Gets the number of particles which this emitter would like to emit based on the time elapsed. @remarks For efficiency the emitter does not actually create new Particle instances (these are reused by the ParticleSystem as existing particles 'die'). The implementation for this method must return the number of particles the emitter would like to emit given the number of seconds which have elapsed (passed in as a parameter). @par Based on the return value from this method, the ParticleSystem class will call _initParticle once for each particle it chooses to allow to be emitted by this emitter. The emitter should not track these _initParticle calls, it should assume all emissions requested were made (even if they could not be because of particle quotas). */ virtual unsigned short _getEmissionCount(Real timeElapsed) = 0; /** Initialises a particle based on the emitter's approach and parameters. @remarks See the _getEmissionCount method for details of why there is a separation between 'requested' emissions and actual initialised particles. @param pParticle Pointer to a particle which must be initialised based on how this emitter starts particles. This is passed as a pointer rather than being created by the emitter so the ParticleSystem can reuse Particle instances, and can also set defaults itself. */ virtual void _initParticle(Particle* pParticle) { // Initialise size in case it's been altered pParticle->resetDimensions(); } /** Returns the name of the type of emitter. @remarks This property is useful for determining the type of emitter procedurally so another can be created. */ const String &getType(void) const { return mType; } /** Sets whether or not the emitter is enabled. @remarks You can turn an emitter off completely by setting this parameter to false. */ virtual void setEnabled(bool enabled); /** Gets the flag indicating if this emitter is enabled or not. */ virtual bool getEnabled(void) const; /** Sets the 'start time' of this emitter. @remarks By default an emitter starts straight away as soon as a ParticleSystem is first created, or also just after it is re-enabled. This parameter allows you to set a time delay so that the emitter does not 'kick in' until later. @param startTime The time in seconds from the creation or enabling of the emitter. */ virtual void setStartTime(Real startTime); /** Gets the start time of the emitter. */ virtual Real getStartTime(void) const; /** Sets the duration of the emitter. @remarks By default emitters run indefinitely (unless you manually disable them). By setting this parameter, you can make an emitter turn off on it's own after a set number of seconds. It will then remain disabled until either setEnabled(true) is called, or if the 'repeatAfter' parameter has been set it will also repeat after a number of seconds. @par Also see the alternative version of this method which allows you to set a min and max duration for a random variable duration. @param duration The duration in seconds. */ virtual void setDuration(Real duration); /** Gets the duration of the emitter from when it is created or re-enabled. */ virtual Real getDuration(void) const; /** Sets the range of random duration for this emitter. @remarks By default emitters run indefinitely (unless you manually disable them). By setting this parameter, you can make an emitter turn off on it's own after a random number of seconds. It will then remain disabled until either setEnabled(true) is called, or if the 'repeatAfter' parameter has been set it will also repeat after a number of seconds. @par Also see the alternative version of this method which allows you to set a constant duration. @param min The minimum duration in seconds. @param max The minimum duration in seconds. */ virtual void setDuration(Real min, Real max); /** Sets the minimum duration of this emitter in seconds (see setDuration for more details) */ virtual void setMinDuration(Real min); /** Sets the maximum duration of this emitter in seconds (see setDuration for more details) */ virtual void setMaxDuration(Real max); /** Gets the minimum duration of this emitter in seconds (see setDuration for more details) */ virtual Real getMinDuration(void) const; /** Gets the maximum duration of this emitter in seconds (see setDuration for more details) */ virtual Real getMaxDuration(void) const; /** Sets the time between repeats of the emitter. @remarks By default emitters run indefinitely (unless you manually disable them). However, if you manually disable the emitter (by calling setEnabled(false), or it's duration runs out, it will cease to emit @par Also see the alternative version of this method which allows you to set a min and max duration for a random variable duration. @param duration The duration in seconds. */ virtual void setRepeatDelay(Real duration); /** Gets the duration of the emitter from when it is created or re-enabled. */ virtual Real getRepeatDelay(void) const; /** Sets the range of random duration for this emitter. @remarks By default emitters run indefinitely (unless you manually disable them). By setting this parameter, you can make an emitter turn off on it's own after a random number of seconds. It will then remain disabled until either setEnabled(true) is called, or if the 'repeatAfter' parameter has been set it will also repeat after a number of seconds. @par Also see the alternative version of this method which allows you to set a constant duration. @param min The minimum duration in seconds. @param max The minimum duration in seconds. */ virtual void setRepeatDelay(Real min, Real max); /** Sets the minimum duration of this emitter in seconds (see setRepeatDelay for more details) */ virtual void setMinRepeatDelay(Real min); /** Sets the maximum duration of this emitter in seconds (see setRepeatDelay for more details) */ virtual void setMaxRepeatDelay(Real max); /** Gets the minimum duration of this emitter in seconds (see setRepeatDelay for more details) */ virtual Real getMinRepeatDelay(void) const; /** Gets the maximum duration of this emitter in seconds (see setRepeatDelay for more details) */ virtual Real getMaxRepeatDelay(void) const; /** Returns the name of the emitter */ const String &getName(void) const; /** Sets the name of the emitter */ virtual void setName(const String& newName); /** Returns the name of the emitter to be emitted */ const String &getEmittedEmitter(void) const; /** Sets the name of the emitter to be emitted*/ virtual void setEmittedEmitter(const String& emittedEmitter); /** Return true if the emitter is emitted by another emitter */ virtual bool isEmitted(void) const; /** Set the indication (true/false) to indicate that the emitter is emitted by another emitter */ virtual void setEmitted(bool emitted); }; /** @} */ /** @} */ } #include "OgreHeaderSuffix.h" #endif
mit
abhishekbhalani/scripty2
templates/html/assets/stylesheets/apidocs.css
15954
.clearfix:after, .section:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clearfix, .section { display: inline-block; } html[xmlns] .clearfix, html[xmlns] .section { display: block; } * html .clearfix, * html .section { height: 1%; } span.replaced { visibility: hidden; } span.hidden { display: none; } div.transition { margin-top: 30px; width: 200px; height: 200px; position: relative; margin-bottom:10px; } div.transition div { position: absolute; height: 1px; width: 1px; background: #000; } div.transition span { display: block; position: absolute; border-bottom: 1px solid #dadada; font-size: 10x; color: #888; width: 200px; left: 0px; } div.transition div.indicator { background-color: #ABD474; height: 200px; top: 0px; left: 0px; } div.transition div.interactive div.hint { width: 100%; top: 90px; font-size: 18px; text-align: center; color: #888 !important; background: transparent; border: 0; z-index: 1; } div.transition div.interactive.active div.hint { display: none; } div.transition div.marker { background-color: #ABD474; height: 6px; width: 6px; border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; left: 0px; margin-bottom: -3px; margin-left: -3px; } div.transition div.label { background: transparent; color: #ABD474; font-size: 20px; height: 20px; width: 200px; text-align: center; top: 80px; left: 0px; z-index: -1; } div.transition div.interactive { width: 590px; height: 200px; left: 240px; border: 1px solid #dadada; background: #fff; } div.transition div.interactive div { color: #eee; } div.transition div.interactive.active div { color: #000; } div.transition div.interactive div.movement { width: 60px; height: 60px; border: 1px solid #eee; background: #fff; text-align:center; padding: 20px; top: 20px; left: 20px; } div.transition div.interactive.active div.movement { background: #F9FFED; border: 1px solid #ABD474; } div.transition div.interactive div.color { width: 328px; height: 20px; border: 1px solid #eee; background: #fff; text-align:center; padding: 10px; top: 140px; left: 20px; } div.transition div.interactive.active div.color { background: #ABD474; } div.transition div.interactive div.size { width: 30px; height: 30px; border: 1px solid #eee; background: #fff; text-align:center; padding: 20px; top: 60px; left: 450px; margin: 0; font-size: 100%; } div.transition div.interactive.active div.size { background: #F9FFED; border: 1px solid #ABD474; } body { font-size: 82.5%; line-height: 1.5em; margin: 0; padding: 0; font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; } body * { margin: 0; padding: 0; } h4 { font-size: 17px; color: #555; margin: 1.0em 0 0.6em; } h5 { font-size: 15px; color: #2a2a2a; margin: 1.0em 0 0.6em; } h6 { font-size: 14px; color: #000; margin: 1.0em 0 0.6em; } a img { border: 0; } ul, li { list-style-type: none; } ol, ul { margin: 0 0 15px; } #page a.img, #page a.img:link, #page a.img:visited { border: none; } /* Link bar */ div#links { margin: 0 auto; width: 835px; padding: 16px 0; height: 16px; overflow: hidden; } div#links_wrapper { background: #fff; } div#links li { display: inline; } div#links li a { color: #666; } div#links li.selected a { color: #000; font-weight: bold; text-decoration: none; } ul#internal_links { float: left; } ul#internal_links li { margin-right: 25px; } ul#external_links { float: right; } ul#external_links li { margin-left: 25px; padding-left: 21px; } p a, p a:link, h1 a, h1 a:link, h2 a, h2 a:link, h3 a, h3 a:link, h4 a, h4 a:link, h5 a, h5 a:link, h6 a, h6 a:link { color: #455C23; } p a:visited { } code { font-family: "Panic Sans", "Bitstream Vera Sans Mono", Monaco, Consolas, Andale Mono, monospace; font-size: 14px; } p code, li code { background-color: #f0f0f0; border: 1px solid #ccc; border-radius: 3px; -webkit-border-radius: 3px; padding: 0 3px; } pre code { background-color: transparent; border: 0; padding: 0; } div.code, div.code pre { font-family: "Panic Sans", "Bitstream Vera Sans Mono", Monaco, Consolas, Andale Mono, monospace; font-size: 12px; } #page { margin: 0 auto; padding-bottom: 100px; /* FIXME: Temporary as pages are built */ } /* top */ .related-links { width: 835px; font-size: 0.9em; margin: 0 auto 10px; padding: 10px 0 0; } .related-links a { color: #000; text-decoration: none; } .related-links ul { list-style-type: none; } .related-links ul.internal { float: left; width: 355px; } .related-links ul.internal li { text-align: center; } .related-links ul.external { float: right; width: 295px; } .related-links li { float: left; padding: 0 15px; width: 85px; margin-right: 5px; } .related-links li.last { margin-right: 0; } .related-links ul.external li.scripty { padding: 0 8px 0 22px; background: url(../images/icon-scripty.png) no-repeat; margin-right: 65px; } .related-links ul.external li.rails { padding: 0 8px 0 22px; background: url(../images/icon-rails.png) no-repeat; } .banner { height: 152px; padding: 1px 0; background: url(../images/header-stripe.png) repeat-x; } .banner-content { width: 835px; margin: 0 auto; } .banner h1 { width: 236px; height: 150px; background: url(../images/header-logo.png) no-repeat; } .banner h1 span { display: none; } .banner-small { height: 75px; padding: 1px 0; background: url(../images/header-stripe-small.png) repeat-x; } .banner-small h1 { width: 118px; height: 75px; background: url(../images/header-logo-small.png) no-repeat; margin-left: 60px; } .banner-small h1 span { display: none; } /* PAGE CONTENT */ .page-content { width: 955px; margin: 60px auto 0; } .page-content .page-title { margin-left: 140px; margin-bottom: 15px; font-size: 27px; letter-spacing: -1px; color: #444; } .page-content .page-introduction { margin-left: 140px; font-size: 15px; margin-bottom: 25px; } .page-content .page-introduction p { margin-top: 0; } .page-content .section { width: 955px; margin: 10px 0 20px; } .page-content .section .section-title { width: 130px; margin-top: -4px; margin-right: 10px; padding-right: 0; float: left; text-align: right; overflow: hidden; } .page-content .section .section-title h3 { color: #999; font-size: 14px; line-height: 110%; padding-right: 10px; padding-bottom: 5px; } .page-content .section .section-content { width: 815px; float: left; } .page-content .section .section-content h2 { color: #444; font-size: 16px; margin: 15px 0 5px 0; } .page-content .section .section-content h4.inherited { clear: both; font-size: 14px; } .page-content a, .page-content a:link { color: #455C23; border-bottom: 1px solid #455C23; text-decoration: none; } .page-content a:visited { border-bottom: 1px solid #bbb; } .page-content ul, .page-content ol { margin: 10px 0; } .page-content li { margin: 5px 0 8px 20px; list-style-type: disc; } .page-content p { margin: 0 0 0.8em; } .page-content pre { color: #333; background-color: #F9FFEE; border: 1px solid #ACD576; padding: 3px 5px; margin: 0 0 1em; } .page-content .two-column { } .page-content .two-column-left, .page-content .two-column-right { width: 475px; margin-right: 5px; float: left; } .page-content .two-column-right { margin-right: 0; } .page-content .two-column .section { width: 475px; } .page-content .two-column .section-content { width: 345px; padding-right: 10px; } .smallcaps { font-size: 0.85em; text-transform: uppercase; letter-spacing: 1px; } /* MASTHEAD */ div#masthead { margin-top: 50px; height: 76px; } div#masthead div#masthead_content { margin: 0 auto; width: 835px; position: relative; } div#masthead h1#logo { background: url(../images/header-logo.png) no-repeat 0 1px; width: 300px; height: 93px; position: relative; left: 75px; } div#masthead a { text-decoration: none; } pre { padding: 0; } code { font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", monospace; font-size: 12px; } div#footer { width: 960px; margin: 0 auto; } div.about { margin-top: 20px; padding-top: 20px; width: 745px; margin-left: 140px; border-top: 1px solid #aaa; color: #aaa; padding-left: 90px; background: url(../images/cc.png) no-repeat 20px left; } div.about a, div.about a:link { color: #888; text-decoration: underline; border: 0; } div.copyright, div.credits { width: 372px; float: left; } div.copyright .cc { width: 115px; margin-right: 5px; text-align: center; float: left; } div.copyright .copyright-about { width: 235px; float: left; } div.credits { text-align: right; } .page-title span.type { display: block; text-transform: uppercase; font-size: 14px; color: #aaa; letter-spacing: 0; } h2.page-title { margin-top: 0; line-height: 100%; } ul.breadcrumbs { margin-left: 140px; } ul.breadcrumbs li { float: left; list-style-type: none; margin-right: 10px; margin-left: 0; } ul.method-list { margin-top: 0; } ul.method-list li { margin-top: 0; float: left; margin-right: 5px; margin-left: 0; list-style-type: none; } ul.method-list li a, ul.method-list li a:link { text-decoration: none; border: 0; } ul.method-details-list { margin-top: 0; } ul.method-details-list li.method-description { margin-top: 0; margin-bottom: 3.0em; margin-left: 0; list-style-type: none; } ul.method-details-list li h4 { margin: 0 0 0.6em; line-height: 90%; } ul.method-details-list li pre { margin-top: 0; } ul.method-details-list li pre code { font-size: 13px; } ul.method-details-list li code { font-size: 12px; } .method-description h4 .method-permalink a { color: #aaa; text-decoration: none; border: 0; font-size: 14px; } ul.argument-list { margin-top: -5px; list-style-type: disc; margin-left: 20px; } ul.argument-list li { list-style-type: disc; font-size: 90%; margin-bottom: 0; } ul.argument-list li code { font-size: 11px; } ul.section-list { margin-top: 0; } ul.section-list li { margin-top: 0; margin-left: 0; list-style-type: none; } ul.section-list li h4 { margin-top: 0; } /* Aliases */ .alias, .related-to { font-style: italic; } .alias code, .related-to code { font-style: normal; } /* Section icons */ .page-content .section .section-title h3 { padding-right: 34px; background-position: right 0; background-repeat: no-repeat; height: 24px; padding-top: 5px; } .section-constructor .section-title h3 { background-image: url(../images/constructor.png); } .section-method-list .section-title h3 { background-image: url(../images/method.png); } .section-klass_methods .section-title h3 { background-image: url(../images/class_method.png); } .section-klass_properties .section-title h3 { background-image: url(../images/class_property.png); } .section-instance_methods .section-title h3 { background-image: url(../images/instance_method.png); } .section-instance_properties .section-title h3 { background-image: url(../images/instance_property.png); } .section-mixins .section-title h3 { background-image: url(../images/mixin.png); } .section-classes .section-title h3 { background-image: url(../images/class.png); } .section-namespaces .section-title h3 { background-image: url(../images/namespace.png); } .section-sections .section-title h3 { background-image: url(../images/section.png); } .section-utilities .section-title h3 { background-image: url(../images/utility.png); } .section-description .section-title h3 { background-image: url(../images/description.png); } .section-subclasses .section-title h3 { background-image: url(../images/subclass.png); } .section-superclass .section-title h3 { background-image: url(../images/superclass.png); } /* search box */ .search-results { position: absolute; background-color: #fff; height: 200px; width: 233px; overflow: auto; overflow-y: scroll; overflow-x: hidden; margin: 7px -11px 0; border: 1px solid #999; top: 28px; } * html .search-results { left: 486px; top: 30px; } /* search result types */ .menu-item a, .menu-item a:link { display: block; padding: 3px 10px 3px 28px; background-position: 6px 50%; background-repeat: no-repeat; text-align: left; text-decoration: none; color: #333; border-top: 1px solid #fff; border-bottom: 1px solid #fff; white-space: nowrap; } .menu-item a:hover, .menu-item a.highlighted, #menu .highlighted a { border-top: 1px solid #69f; border-bottom: 1px solid #69f; background-color: #f0f0ff; } .menu-item a.section { font-weight: bold; background-image: url(../images/section.png); } .menu-item a.class_method, .menu-item a.instance_method { background-image: url(../images/method.png); } .menu-item a.class { background-image: url(../images/class.png); } .menu-item a.constructor { background-image: url(../images/constructor.png); } .menu-item a.class_property { background-image: url(../images/class_property.png); } .menu-item a.instance_property { background-image: url(../images/instance_property.png); } .menu-item a.namespace { background-image: url(../images/namespace.png); } .menu-item a.utility { background-image: url(../images/utility.png); } .highlighter { border: 3px solid #ABD474; z-index: -1; border-radius: 20px; -webkit-border-radius: 20px; -moz-border-radius: 20px; background: #FBFFF8; padding: 20px; } div#menu { width: 960px; margin: 0 auto; position: relative; margin-top: -50px; } #menu .api-box h2 a, #menu .search-box { width: 213px; height: 25px; line-height: 25px; padding: 5px 10px; margin-right: 5px; text-align: center; float: right; } * html #menu .api-box h2 a, * html #menu .search-box { height: 20px; line-height: 30px; } #menu .api-box { } #menu .api-box h2 a { font-size: 14px; font-weight: normal; font-family: Verdana, sans-serif; display: block; text-decoration: none; color: #222; } #menu .api-box .menu-items { position: absolute; background-color: #fff; height: 400px; width: 233px; overflow: auto; overflow-y: scroll; overflow-x: hidden; top: 35px; border: 1px solid #999; right: 240px; } * html #menu .api-box .menu-items { right: 10px; top: 37px; } #menu .api-box ul, #menu .api-box li { margin: 0; padding: 0; } #menu .api-box .menu-item a { } #menu .search-box input { width: 150px; padding: 3px 10px; margin-top: 2px; border: 1px solid #999; border-radius: 10px; -webkit-border-radius: 10px; -moz-border-radius: 10px; } #menu #search.ghosted { color: #aaa; text-align: left; } /* notes */ p.note, p.alias, p.related-to { font-size: 11px; line-height: 14px; padding: 5px 5px 5px 60px; background-repeat: no-repeat; background-position: 20px 50%; border: 1px solid #000; } p.note { background-color: #f0f0f4; background-image: url(../images/information.png); border-color: #69c; } p.alias { background-color: #fff6de; background-image: url(../images/alias.png); border-color: #cc9; } p.related-to { background-color: #f4f0f4; background-image: url(../images/related_to.png); border-color: #c9c; } #morph_example { border:1px dashed #618AB8; overflow:hidden; margin-bottom:10px; } #morph_example .options { background:#CEDCEC; padding:10px; } #morph_example .options textarea { height:50px; font-size:15px; width:500px; padding:2px; float:left; } #morph_example .options a.button, #morph_example .options a.reset { background:#618AB8; text-decoration:none; border:none; color:#fff; position:relative; margin-left:5px; display:block; height:38px; width:58px; float:left; text-align:center; padding:18px 0 0 0; -webkit-border-radius:5px; -moz-border-radius:5px; } #morph_example .options a.button:hover { background:#365b85; } #morph_example .options a.reset { background:#aaa; margin-left:5px; } #morph_example .options a.reset:hover { background:#888; } #morph_example p { margin:50px auto; width:400px; position:relative; border:0px solid #000; } #morph_example .hint { clear:both; font-size:12px; } #morph_example .hint em { font-style:normal; color:#666; text-decoration:underline; cursor:pointer; }
mit
f0rki/cb-multios
original-challenges/LulzChat/cb_2/src/message.h
1527
/* * Copyright (c) 2014 Kaprica Security, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef MESSAGE_H #define MESSAGE_H #include "user.h" #define MAX_TEXT_LEN 512 #define TYPE_NORMAL 0 #define TYPE_PROTECTED 1 typedef struct message { unsigned short type; unsigned short to_id; unsigned short from_id; unsigned short text_len; char *text; } message_t; message_t* parse_message(char *, user_t *, user_t *, unsigned len); void free_message(message_t *); #endif
mit
wuhaiwei/RoundedCorner
RoundedCorner/MyTableViewCell.h
326
// // MyTableViewCell.h // RoundedCorner // // Created by Weipin Xia on 2/25/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface MyTableViewCell : UITableViewCell { UIImageView *myImageView_; } @property (nonatomic, retain) IBOutlet UIImageView* myImageView; @end
mit
ortutay/react-native-reverse-geo
README.md
1976
# react-native-reverse-geo React Native module bridge to convert address to geo coordinates. Makes use of the following native iOS classes: * [CLGeocoder](https://developer.apple.com/library/prerelease/ios/documentation/CoreLocation/Reference/CLGeocoder_class/index.html) * [CLPlacemark](https://developer.apple.com/library/prerelease/ios/documentation/CoreLocation/Reference/CLPlacemark_class/index.html) * [MKPlacemark](https://developer.apple.com/library/mac/documentation/MapKit/Reference/MKPlacemark_Class/index.html) ## API ## Getting Started (and running the demo project) 1. From inside your project run `npm install react-native-reverse-geo --save` 2. In XCode, in the project navigator, right click `Libraries` ➜ `Add Files to [your project's name]` 3. Go to `node_modules` ➜ `react-native-reverse-geo` and add `RNReverseGeo.xcodeproj` 4. In XCode, in the project navigator, select your project. Add `libRNReverseGeo.a` to your project's `Build Phases` ➜ `Link Binary With Libraries` 5. Click `RNReverseGeo.xcodeproj` in the project navigator and go the `Build Settings` tab. Make sure 'All' is toggled on (instead of 'Basic'). Look for `Header Search Paths` and make sure it contains both `$(SRCROOT)/../react-native/React` and `$(SRCROOT)/../../React` - mark both as `recursive`. 6. RNReverseGeoRun your project (`Cmd+R`) ## Usage Example ```js var React = require('react-native'); // Load Up our Native Module.. var { RNReverseGeo } = require('NativeModules'); getInitialState: function() { return { reverseGeoResults: "Loading..." }; }, componentDidMount: function() { var that = this; RNReverseGeo.geoCodeAddress("370 Tompkins Ave, Brooklyn, NY 11216", function(_results){ console.log(_results); that.setState({ reverseGeoResults : JSON.stringify(_results,null,2) }) }); }, ``` There is an example project supplied with the repo in the RNReverseGeoDemo folder.
mit
jenkinsci/credentials-plugin
src/test/java/com/cloudbees/plugins/credentials/builds/CredentialsParameterBinderReplayActionIntegrationTest.java
5191
/* * The MIT License * * Copyright (c) 2019 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.cloudbees.plugins.credentials.builds; import com.cloudbees.plugins.credentials.CredentialsParameterDefinition; import com.cloudbees.plugins.credentials.CredentialsParameterValue; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsScope; import com.cloudbees.plugins.credentials.common.IdCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.User; import hudson.model.queue.QueueTaskFuture; import hudson.security.ACL; import hudson.security.ACLContext; import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition; import org.jenkinsci.plugins.workflow.cps.replay.ReplayAction; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class CredentialsParameterBinderReplayActionIntegrationTest { private static final String PARAMETER_NAME = "parameterName"; @Rule public JenkinsRule j = new JenkinsRule(); private String credentialsId; @Before public void setUp() throws Exception { j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); final User alpha = User.getById("alpha", true); try (ACLContext ignored = ACL.as(alpha)) { credentialsId = UUID.randomUUID().toString(); CredentialsProvider.lookupStores(alpha).iterator().next() .addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl( CredentialsScope.USER, credentialsId, null, "user", "pass")); } } @Test public void replayActionShouldNotCopyCredentialsParameterBindingUserIds() throws Exception { final WorkflowJob job = j.createProject(WorkflowJob.class); job.addProperty(new ParametersDefinitionProperty(new CredentialsParameterDefinition( PARAMETER_NAME, null, null, IdCredentials.class.getName(), true))); job.setDefinition(new CpsFlowDefinition("echo 'hello, world'", true)); final WorkflowRun run = j.assertBuildStatusSuccess(job.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause("alpha")), new ParametersAction(new CredentialsParameterValue(PARAMETER_NAME, credentialsId, null)) )); final CredentialsParameterBinding original = CredentialsParameterBinder.getOrCreate(run).forParameterName(PARAMETER_NAME); assertNotNull(original); assertEquals("alpha", original.getUserId()); assertNotNull(CredentialsProvider.findCredentialById(PARAMETER_NAME, IdCredentials.class, run)); final User beta = User.getById("beta", true); final WorkflowRun replayedRun = replayRunAs(run, beta); final CredentialsParameterBinding replayed = CredentialsParameterBinder.getOrCreate(replayedRun).forParameterName(PARAMETER_NAME); assertNotNull(replayed); assertEquals("beta", replayed.getUserId()); assertNull(CredentialsProvider.findCredentialById(PARAMETER_NAME, IdCredentials.class, replayedRun)); } @SuppressWarnings("unchecked") private WorkflowRun replayRunAs(WorkflowRun run, User user) throws Exception { final ReplayAction replay = run.getAction(ReplayAction.class); assertNotNull(replay); final QueueTaskFuture<WorkflowRun> futureRun; try (ACLContext ignored = ACL.as(user)) { futureRun = replay.run(replay.getOriginalScript(), replay.getOriginalLoadedScripts()); } return j.assertBuildStatusSuccess(futureRun); } }
mit
daviddliu/THetA_luigi
PipelineSoftware/BICseq/PERL_pipeline/SAMgetUnique/samtools-0.1.7a_getUnique-0.1.1/bam_index.c
16596
#include <ctype.h> #include <assert.h> #include "bam.h" #include "khash.h" #include "ksort.h" #include "bam_endian.h" #ifdef _USE_KNETFILE #include "knetfile.h" #endif /*! @header Alignment indexing. Before indexing, BAM must be sorted based on the leftmost coordinate of alignments. In indexing, BAM uses two indices: a UCSC binning index and a simple linear index. The binning index is efficient for alignments spanning long distance, while the auxiliary linear index helps to reduce unnecessary seek calls especially for short alignments. The UCSC binning scheme was suggested by Richard Durbin and Lincoln Stein and is explained by Kent et al. (2002). In this scheme, each bin represents a contiguous genomic region which can be fully contained in another bin; each alignment is associated with a bin which represents the smallest region containing the entire alignment. The binning scheme is essentially another representation of R-tree. A distinct bin uniquely corresponds to a distinct internal node in a R-tree. Bin A is a child of Bin B if region A is contained in B. In BAM, each bin may span 2^29, 2^26, 2^23, 2^20, 2^17 or 2^14 bp. Bin 0 spans a 512Mbp region, bins 1-8 span 64Mbp, 9-72 8Mbp, 73-584 1Mbp, 585-4680 128Kbp and bins 4681-37449 span 16Kbp regions. If we want to find the alignments overlapped with a region [rbeg,rend), we need to calculate the list of bins that may be overlapped the region and test the alignments in the bins to confirm the overlaps. If the specified region is short, typically only a few alignments in six bins need to be retrieved. The overlapping alignments can be quickly fetched. */ #define BAM_MIN_CHUNK_GAP 32768 // 1<<14 is the size of minimum bin. #define BAM_LIDX_SHIFT 14 typedef struct { uint64_t u, v; } pair64_t; #define pair64_lt(a,b) ((a).u < (b).u) KSORT_INIT(off, pair64_t, pair64_lt) typedef struct { uint32_t m, n; pair64_t *list; } bam_binlist_t; typedef struct { int32_t n, m; uint64_t *offset; } bam_lidx_t; KHASH_MAP_INIT_INT(i, bam_binlist_t) struct __bam_index_t { int32_t n; khash_t(i) **index; bam_lidx_t *index2; }; // requirement: len <= LEN_MASK static inline void insert_offset(khash_t(i) *h, int bin, uint64_t beg, uint64_t end) { khint_t k; bam_binlist_t *l; int ret; k = kh_put(i, h, bin, &ret); l = &kh_value(h, k); if (ret) { // not present l->m = 1; l->n = 0; l->list = (pair64_t*)calloc(l->m, 16); } if (l->n == l->m) { l->m <<= 1; l->list = (pair64_t*)realloc(l->list, l->m * 16); } l->list[l->n].u = beg; l->list[l->n++].v = end; } static inline void insert_offset2(bam_lidx_t *index2, bam1_t *b, uint64_t offset) { int i, beg, end; beg = b->core.pos >> BAM_LIDX_SHIFT; end = (bam_calend(&b->core, bam1_cigar(b)) - 1) >> BAM_LIDX_SHIFT; if (index2->m < end + 1) { int old_m = index2->m; index2->m = end + 1; kroundup32(index2->m); index2->offset = (uint64_t*)realloc(index2->offset, index2->m * 8); memset(index2->offset + old_m, 0, 8 * (index2->m - old_m)); } for (i = beg + 1; i <= end; ++i) if (index2->offset[i] == 0) index2->offset[i] = offset; index2->n = end + 1; } static void merge_chunks(bam_index_t *idx) { #if defined(BAM_TRUE_OFFSET) || defined(BAM_VIRTUAL_OFFSET16) khash_t(i) *index; int i, l, m; khint_t k; for (i = 0; i < idx->n; ++i) { index = idx->index[i]; for (k = kh_begin(index); k != kh_end(index); ++k) { bam_binlist_t *p; if (!kh_exist(index, k)) continue; p = &kh_value(index, k); m = 0; for (l = 1; l < p->n; ++l) { #ifdef BAM_TRUE_OFFSET if (p->list[m].v + BAM_MIN_CHUNK_GAP > p->list[l].u) p->list[m].v = p->list[l].v; #else if (p->list[m].v>>16 == p->list[l].u>>16) p->list[m].v = p->list[l].v; #endif else p->list[++m] = p->list[l]; } // ~for(l) p->n = m + 1; } // ~for(k) } // ~for(i) #endif // defined(BAM_TRUE_OFFSET) || defined(BAM_BGZF) } bam_index_t *bam_index_core(bamFile fp) { bam1_t *b; bam_header_t *h; int i, ret; bam_index_t *idx; uint32_t last_bin, save_bin; int32_t last_coor, last_tid, save_tid; bam1_core_t *c; uint64_t save_off, last_off; idx = (bam_index_t*)calloc(1, sizeof(bam_index_t)); b = (bam1_t*)calloc(1, sizeof(bam1_t)); h = bam_header_read(fp); c = &b->core; idx->n = h->n_targets; bam_header_destroy(h); idx->index = (khash_t(i)**)calloc(idx->n, sizeof(void*)); for (i = 0; i < idx->n; ++i) idx->index[i] = kh_init(i); idx->index2 = (bam_lidx_t*)calloc(idx->n, sizeof(bam_lidx_t)); save_bin = save_tid = last_tid = last_bin = 0xffffffffu; save_off = last_off = bam_tell(fp); last_coor = 0xffffffffu; while ((ret = bam_read1(fp, b)) >= 0) { if (last_tid != c->tid) { // change of chromosomes last_tid = c->tid; last_bin = 0xffffffffu; } else if (last_coor > c->pos) { fprintf(stderr, "[bam_index_core] the alignment is not sorted (%s): %u > %u in %d-th chr\n", bam1_qname(b), last_coor, c->pos, c->tid+1); exit(1); } if (b->core.tid >= 0 && b->core.bin < 4681) insert_offset2(&idx->index2[b->core.tid], b, last_off); if (c->bin != last_bin) { // then possibly write the binning index if (save_bin != 0xffffffffu) // save_bin==0xffffffffu only happens to the first record insert_offset(idx->index[save_tid], save_bin, save_off, last_off); save_off = last_off; save_bin = last_bin = c->bin; save_tid = c->tid; if (save_tid < 0) break; } if (bam_tell(fp) <= last_off) { fprintf(stderr, "[bam_index_core] bug in BGZF/RAZF: %llx < %llx\n", (unsigned long long)bam_tell(fp), (unsigned long long)last_off); exit(1); } last_off = bam_tell(fp); last_coor = b->core.pos; } if (save_tid >= 0) insert_offset(idx->index[save_tid], save_bin, save_off, bam_tell(fp)); merge_chunks(idx); if (ret < -1) fprintf(stderr, "[bam_index_core] truncated file? Continue anyway. (%d)\n", ret); free(b->data); free(b); return idx; } void bam_index_destroy(bam_index_t *idx) { khint_t k; int i; if (idx == 0) return; for (i = 0; i < idx->n; ++i) { khash_t(i) *index = idx->index[i]; bam_lidx_t *index2 = idx->index2 + i; for (k = kh_begin(index); k != kh_end(index); ++k) { if (kh_exist(index, k)) free(kh_value(index, k).list); } kh_destroy(i, index); free(index2->offset); } free(idx->index); free(idx->index2); free(idx); } void bam_index_save(const bam_index_t *idx, FILE *fp) { int32_t i, size; khint_t k; fwrite("BAI\1", 1, 4, fp); if (bam_is_be) { uint32_t x = idx->n; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); } else fwrite(&idx->n, 4, 1, fp); for (i = 0; i < idx->n; ++i) { khash_t(i) *index = idx->index[i]; bam_lidx_t *index2 = idx->index2 + i; // write binning index size = kh_size(index); if (bam_is_be) { // big endian uint32_t x = size; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); } else fwrite(&size, 4, 1, fp); for (k = kh_begin(index); k != kh_end(index); ++k) { if (kh_exist(index, k)) { bam_binlist_t *p = &kh_value(index, k); if (bam_is_be) { // big endian uint32_t x; x = kh_key(index, k); fwrite(bam_swap_endian_4p(&x), 4, 1, fp); x = p->n; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); for (x = 0; (int)x < p->n; ++x) { bam_swap_endian_8p(&p->list[x].u); bam_swap_endian_8p(&p->list[x].v); } fwrite(p->list, 16, p->n, fp); for (x = 0; (int)x < p->n; ++x) { bam_swap_endian_8p(&p->list[x].u); bam_swap_endian_8p(&p->list[x].v); } } else { fwrite(&kh_key(index, k), 4, 1, fp); fwrite(&p->n, 4, 1, fp); fwrite(p->list, 16, p->n, fp); } } } // write linear index (index2) if (bam_is_be) { int x = index2->n; fwrite(bam_swap_endian_4p(&x), 4, 1, fp); } else fwrite(&index2->n, 4, 1, fp); if (bam_is_be) { // big endian int x; for (x = 0; (int)x < index2->n; ++x) bam_swap_endian_8p(&index2->offset[x]); fwrite(index2->offset, 8, index2->n, fp); for (x = 0; (int)x < index2->n; ++x) bam_swap_endian_8p(&index2->offset[x]); } else fwrite(index2->offset, 8, index2->n, fp); } fflush(fp); } static bam_index_t *bam_index_load_core(FILE *fp) { int i; char magic[4]; bam_index_t *idx; if (fp == 0) { fprintf(stderr, "[bam_index_load_core] fail to load index.\n"); return 0; } fread(magic, 1, 4, fp); if (strncmp(magic, "BAI\1", 4)) { fprintf(stderr, "[bam_index_load] wrong magic number.\n"); fclose(fp); return 0; } idx = (bam_index_t*)calloc(1, sizeof(bam_index_t)); fread(&idx->n, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&idx->n); idx->index = (khash_t(i)**)calloc(idx->n, sizeof(void*)); idx->index2 = (bam_lidx_t*)calloc(idx->n, sizeof(bam_lidx_t)); for (i = 0; i < idx->n; ++i) { khash_t(i) *index; bam_lidx_t *index2 = idx->index2 + i; uint32_t key, size; khint_t k; int j, ret; bam_binlist_t *p; index = idx->index[i] = kh_init(i); // load binning index fread(&size, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&size); for (j = 0; j < (int)size; ++j) { fread(&key, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&key); k = kh_put(i, index, key, &ret); p = &kh_value(index, k); fread(&p->n, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&p->n); p->m = p->n; p->list = (pair64_t*)malloc(p->m * 16); fread(p->list, 16, p->n, fp); if (bam_is_be) { int x; for (x = 0; x < p->n; ++x) { bam_swap_endian_8p(&p->list[x].u); bam_swap_endian_8p(&p->list[x].v); } } } // load linear index fread(&index2->n, 4, 1, fp); if (bam_is_be) bam_swap_endian_4p(&index2->n); index2->m = index2->n; index2->offset = (uint64_t*)calloc(index2->m, 8); fread(index2->offset, index2->n, 8, fp); if (bam_is_be) for (j = 0; j < index2->n; ++j) bam_swap_endian_8p(&index2->offset[j]); } return idx; } bam_index_t *bam_index_load_local(const char *_fn) { FILE *fp; char *fnidx, *fn; if (strstr(_fn, "ftp://") == _fn || strstr(_fn, "http://") == _fn) { const char *p; int l = strlen(_fn); for (p = _fn + l - 1; p >= _fn; --p) if (*p == '/') break; fn = strdup(p + 1); } else fn = strdup(_fn); fnidx = (char*)calloc(strlen(fn) + 5, 1); strcpy(fnidx, fn); strcat(fnidx, ".bai"); fp = fopen(fnidx, "r"); if (fp == 0) { // try "{base}.bai" char *s = strstr(fn, "bam"); if (s == fn + strlen(fn) - 3) { strcpy(fnidx, fn); fnidx[strlen(fn)-1] = 'i'; fp = fopen(fnidx, "r"); } } free(fnidx); free(fn); if (fp) { bam_index_t *idx = bam_index_load_core(fp); fclose(fp); return idx; } else return 0; } #ifdef _USE_KNETFILE static void download_from_remote(const char *url) { const int buf_size = 1 * 1024 * 1024; char *fn; FILE *fp; uint8_t *buf; knetFile *fp_remote; int l; if (strstr(url, "ftp://") != url && strstr(url, "http://") != url) return; l = strlen(url); for (fn = (char*)url + l - 1; fn >= url; --fn) if (*fn == '/') break; ++fn; // fn now points to the file name fp_remote = knet_open(url, "r"); if (fp_remote == 0) { fprintf(stderr, "[download_from_remote] fail to open remote file.\n"); return; } if ((fp = fopen(fn, "w")) == 0) { fprintf(stderr, "[download_from_remote] fail to create file in the working directory.\n"); knet_close(fp_remote); return; } buf = (uint8_t*)calloc(buf_size, 1); while ((l = knet_read(fp_remote, buf, buf_size)) != 0) fwrite(buf, 1, l, fp); free(buf); fclose(fp); knet_close(fp_remote); } #else static void download_from_remote(const char *url) { return; } #endif bam_index_t *bam_index_load(const char *fn) { bam_index_t *idx; idx = bam_index_load_local(fn); if (idx == 0 && (strstr(fn, "ftp://") == fn || strstr(fn, "http://") == fn)) { char *fnidx = calloc(strlen(fn) + 5, 1); strcat(strcpy(fnidx, fn), ".bai"); fprintf(stderr, "[bam_index_load] attempting to download the remote index file.\n"); download_from_remote(fnidx); idx = bam_index_load_local(fn); } if (idx == 0) fprintf(stderr, "[bam_index_load] fail to load BAM index.\n"); return idx; } int bam_index_build2(const char *fn, const char *_fnidx) { char *fnidx; FILE *fpidx; bamFile fp; bam_index_t *idx; if ((fp = bam_open(fn, "r")) == 0) { fprintf(stderr, "[bam_index_build2] fail to open the BAM file.\n"); return -1; } idx = bam_index_core(fp); bam_close(fp); if (_fnidx == 0) { fnidx = (char*)calloc(strlen(fn) + 5, 1); strcpy(fnidx, fn); strcat(fnidx, ".bai"); } else fnidx = strdup(_fnidx); fpidx = fopen(fnidx, "w"); if (fpidx == 0) { fprintf(stderr, "[bam_index_build2] fail to create the index file.\n"); free(fnidx); return -1; } bam_index_save(idx, fpidx); bam_index_destroy(idx); fclose(fpidx); free(fnidx); return 0; } int bam_index_build(const char *fn) { return bam_index_build2(fn, 0); } int bam_index(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: samtools index <in.bam> [<out.index>]\n"); return 1; } if (argc >= 3) bam_index_build2(argv[1], argv[2]); else bam_index_build(argv[1]); return 0; } #define MAX_BIN 37450 // =(8^6-1)/7+1 static inline int reg2bins(uint32_t beg, uint32_t end, uint16_t list[MAX_BIN]) { int i = 0, k; --end; list[i++] = 0; for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) list[i++] = k; for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) list[i++] = k; for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) list[i++] = k; for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) list[i++] = k; for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) list[i++] = k; return i; } static inline int is_overlap(uint32_t beg, uint32_t end, const bam1_t *b) { uint32_t rbeg = b->core.pos; uint32_t rend = b->core.n_cigar? bam_calend(&b->core, bam1_cigar(b)) : b->core.pos + 1; return (rend > beg && rbeg < end); } // bam_fetch helper function retrieves pair64_t * get_chunk_coordinates(const bam_index_t *idx, int tid, int beg, int end, int* cnt_off) { uint16_t *bins; int i, n_bins, n_off; pair64_t *off; khint_t k; khash_t(i) *index; uint64_t min_off; bins = (uint16_t*)calloc(MAX_BIN, 2); n_bins = reg2bins(beg, end, bins); index = idx->index[tid]; min_off = (beg>>BAM_LIDX_SHIFT >= idx->index2[tid].n)? 0 : idx->index2[tid].offset[beg>>BAM_LIDX_SHIFT]; for (i = n_off = 0; i < n_bins; ++i) { if ((k = kh_get(i, index, bins[i])) != kh_end(index)) n_off += kh_value(index, k).n; } if (n_off == 0) { free(bins); return 0; } off = (pair64_t*)calloc(n_off, 16); for (i = n_off = 0; i < n_bins; ++i) { if ((k = kh_get(i, index, bins[i])) != kh_end(index)) { int j; bam_binlist_t *p = &kh_value(index, k); for (j = 0; j < p->n; ++j) if (p->list[j].v > min_off) off[n_off++] = p->list[j]; } } free(bins); { bam1_t *b = (bam1_t*)calloc(1, sizeof(bam1_t)); int l; ks_introsort(off, n_off, off); // resolve completely contained adjacent blocks for (i = 1, l = 0; i < n_off; ++i) if (off[l].v < off[i].v) off[++l] = off[i]; n_off = l + 1; // resolve overlaps between adjacent blocks; this may happen due to the merge in indexing for (i = 1; i < n_off; ++i) if (off[i-1].v >= off[i].u) off[i-1].v = off[i].u; { // merge adjacent blocks #if defined(BAM_TRUE_OFFSET) || defined(BAM_VIRTUAL_OFFSET16) for (i = 1, l = 0; i < n_off; ++i) { #ifdef BAM_TRUE_OFFSET if (off[l].v + BAM_MIN_CHUNK_GAP > off[i].u) off[l].v = off[i].v; #else if (off[l].v>>16 == off[i].u>>16) off[l].v = off[i].v; #endif else off[++l] = off[i]; } n_off = l + 1; #endif } bam_destroy1(b); } *cnt_off = n_off; return off; } int bam_fetch(bamFile fp, const bam_index_t *idx, int tid, int beg, int end, void *data, bam_fetch_f func) { int n_off; pair64_t *off = get_chunk_coordinates(idx, tid, beg, end, &n_off); if (off == 0) return 0; { // retrive alignments uint64_t curr_off; int i, ret, n_seeks; n_seeks = 0; i = -1; curr_off = 0; bam1_t *b = (bam1_t*)calloc(1, sizeof(bam1_t)); for (;;) { if (curr_off == 0 || curr_off >= off[i].v) { // then jump to the next chunk if (i == n_off - 1) break; // no more chunks if (i >= 0) assert(curr_off == off[i].v); // otherwise bug if (i < 0 || off[i].v != off[i+1].u) { // not adjacent chunks; then seek bam_seek(fp, off[i+1].u, SEEK_SET); curr_off = bam_tell(fp); ++n_seeks; } ++i; } if ((ret = bam_read1(fp, b)) > 0) { curr_off = bam_tell(fp); if (b->core.tid != tid || b->core.pos >= end) break; // no need to proceed else if (is_overlap(beg, end, b)) func(b, data); } else break; // end of file } // fprintf(stderr, "[bam_fetch] # seek calls: %d\n", n_seeks); bam_destroy1(b); } free(off); return 0; }
mit
blackbaud/skyux2
src/demos/card/index.ts
39
export * from './card-demo.component';
mit
Jason3S/cspell
packages/cspell/CONTRIBUTORS.md
359
# Contributors This is an incomplete list of people who have helped out with this spell checker. Please see: [Contributors to cspell](https://github.com/streetsidesoftware/cspell/graphs/contributors) ## Accepted Pull Requests See: [Merged Pull Requests](https://github.com/streetsidesoftware/cspell/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aclosed+is%3Amerged)
mit
michada/HYS2
DAAExample-master/src/main/webapp/js/dao/event.js
737
function listEvent(login, userCity, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + login + '/' + userCity, type : 'GET' }).done(done).fail(fail).always(always); } function joinEvent(login, eventId, done, fail, always) { done = typeof done !== 'undefined' ? done : function() { }; fail = typeof fail !== 'undefined' ? fail : function() { }; always = typeof always !== 'undefined' ? always : function() { }; $.ajax({ url : 'rest/event/' + eventId + '/' + login, type : 'POST' }).done(done).fail(fail).always(always); }
mit
SketchUp/testup-2
src/testup/ui/css/su-base.css
1042
[v-cloak] { display: none; } @font-face { font-family: "Open Sans"; font-style: normal; font-weight: normal; src: url(../fonts/OpenSans-Regular.ttf); } @font-face { font-family: "Open Sans"; font-style: normal; font-weight: bold; src: url(../fonts/OpenSans-Bold.ttf); } @font-face { font-family: "Open Sans"; font-style: italic; font-weight: bold; src: url(../fonts/OpenSans-BoldItalic.ttf); } @font-face { font-family: "Open Sans"; font-style: italic; font-weight: normal; src: url(../fonts/OpenSans-Italic.ttf); } * { cursor: inherit; box-sizing: border-box; } input, select, textarea { cursor: auto; } a[href] { cursor: pointer; } html, body { border: 0; padding: 0; margin: 0; cursor: default; overflow: hidden; /* Needed for WebDialogs */ } html { background: #f3f3f7; } html, input, select, textarea { font-family: "Open Sans", Helvetica, Arial, sans-serif; font-size: 14px; } a { color: #bc0911; text-decoration: none; } a:hover { text-decoration: underline; }
mit
GangWang/crasheye-ios-sdk
Crasheye/Crasheye.h
2248
// [2.4.0] // Crasheye.h // Crasheye // // Created by 王刚 on 14-8-30. // Copyright (c) 2014年 Gang.Wang. All rights reserved. // #import <Foundation/Foundation.h> @interface Crasheye : NSObject /* @brief:通过appKey注册Dump收集 */ +(void) initWithAppKey:(NSString *) appKey; /* @brief:通过appKey注册Dump收集,并指定channel @param:appKey appKey @param:channel 指定的channel, 由开发都自行填入 */ +(void) initWithAppKey:(NSString *) appKey withChannel:(NSString *) channel; #pragma - mark 自定义数据 /* @brief:添加自定义数据 */ +(void) addExtraDataWithKey:(NSString *) key withValue:(NSString *) value; /* @brief:添加自定义数据 */ +(void) addExtraDataWithDic:(NSDictionary *) dic; /* @brief:移除一项自定义数据 */ +(void) removeExtraDataWithKey:(NSString *) key; /* @brief:移除所有自定义数据 */ +(void) clearExtraData; +(void) addLog: (NSString *) log; +(void) removeLog; /* @brief:获取已添加的自定义数据 */ +(NSDictionary *) extraData; /* @brief:主动上报脚本异常,可用于lua,js等脚本异常时上报 @param: errorTitle 错误的标题,由开发人员指定,不可以为空 exception 异常的详细内容 不可以为空 */ +(void) sendScriptExceptionRequestWithTitle:(NSString *) errorTitle exception:(NSString *) exception file:(NSString *) file language:(NSString *) language; #pragma - mark 打点信息 /* @brief:操作打点, 打点信息会做crash信息一同上报,只保留最后的10个打点信息 */ +(void) leaveBreadcrumb:(NSString *) breadcrumb; #pragma - mark User 信息 /* @brief:设置用户ID */ +(void) setUserID:(NSString *) userID; /* @brief:设置用户信息 */ +(void) setUserInfo:(NSDictionary *) userInfo; #pragma - mark SDK /* @brief:获取Crasheye收集SDK的版本号 */ +(NSString *) versionForCrasheye; /* @brief:获取设备唯一码 */ +(NSString *) getDeviceID; #pragma - mark callback typedef void (*CrashCallback)(int nSign); /* @brief:注册一个回调函数,用于发生Crash的时候,由crasheye通知client */ +(void) registerCrashCallback:(CrashCallback) callback; +(void) setFlushOnlyOverWiFi:(int32_t ) enabled; @end
mit
vidur89/Smart-RFID-Tag
sample-Code/touch-sensor/capacitive touch library/Example_Projects/Source/RO_CSIO_TA0_RTC_One_Button_Compact/main.c
7227
/* --COPYRIGHT--,BSD * Copyright (c) 2014, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * --/COPYRIGHT--*/ //****************************************************************************** // RO_CSIO_TA0_RTC_One_Button_Compact example for MSP430FR4xx // Touch the middle element to turn on/off the center button LED // RO method capactiance measurement using CSIO, TimerA0, and RTC // // Schematic Description: // // MSP430FR4xx // +---------------+ // | | // middle--------|P1.3 XIN|---+ // up----------|P1.4 | 32Khz // right------|P1.5 XOUT|---+ // down--------|P8.2 // | // left----------|P8.2 // | // LED----------|P8.1 // // The RTC interval represents the measurement window. The number of // counts within the TA0R that have accumulated during the measurement // window represents the capacitance of the element. This is lowest // power option with either LPM3 (ACLK VLO source) or LPM0 (SMCLK // source). // // This is the preliminary code revised by Eric Fu // 12 May, 2014 //****************************************************************************** #include "CTS_Layer.h" #include "msp430.h" // Uncomment to have this compiler directive run characterization functions only // Comment to have this compiler directive run example application //#define ELEMENT_CHARACTERIZATION_MODE //Revised for Gradon #define DELAY 3276 // Timer delay timeout count - 3277/32768 = 100 msec // Sensor settings #define KEY_lvl 50 // Defines the min count for a "key press" // Set to ~ half the max delta expected // Global variables for sensing unsigned int base_cnt; unsigned int meas_cnt; unsigned int delta_cnt; char key_pressed, key_loc; int cycles; // Sleep Function // Configures Timer A to run off ACLK, count in UP mode, places the CPU in LPM3 // and enables the interrupt vector to jump to ISR upon timeout void sleep(unsigned int time) { TA0CCR0 = time; TA0CTL = TASSEL__ACLK + MC__UP + TACLR; TA0CCTL0 &= ~CCIFG; TA0CCTL0 = CCIE; __bis_SR_register(LPM3_bits+GIE); __no_operation(); } // Main Function void main(void) { // Initialize System Clocks WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer //Clock Setting CSCTL1 &= ~(DCORSEL_7); // Clear DCO frequency select bits first CSCTL1 |= DCORSEL_3; // Set DCO = 8MHz CSCTL2 = FLLD_0 + 243; // DCODIV = 8MHz CSCTL3 |= SELREF__XT1CLK; // Set REFO as FLL reference source CSCTL4 = SELMS__DCOCLKDIV | SELREF__XT1CLK; // set default REFO(~32768Hz) as ACLK source, ACLK = 32768Hz // default DCODIV as MCLK and SMCLK source CSCTL5 |= DIVM_0 | DIVS_0; // SMCLK = MCLK = DCODIV = 8MHz // Initializing GPIO P8DIR |= BIT1; //Set the pin controlling the center LED P8.1 as output pin PM5CTL0 &= ~LOCKLPM5; // Initialize Baseline measurement int i = 0; TI_CAPT_Raw(&middle_button,&base_cnt); for( i = 0; i < 100; i++) { TI_CAPT_Raw(&middle_button,&meas_cnt); base_cnt += meas_cnt; base_cnt /= 2; } // Main loop starts here while (1) { // Take raw delta measurement TI_CAPT_Raw(&middle_button,&meas_cnt); #ifndef fRO_CSIO_TA2_TA3 if(base_cnt < meas_cnt) // Handle baseline measurment for a base C decrease { // beyond baseline, i.e. cap decreased base_cnt = (base_cnt+meas_cnt) >> 1; // Re-average baseline up quickly delta_cnt = 0; // Zero out delta for position determination } else { delta_cnt = base_cnt - meas_cnt; // Calculate delta: c_change } #endif #ifdef fRO_CSIO_TA2_TA3 if(base_cnt > meas_cnt) // Handle baseline measurment for a base C decrease { // beyond baseline, i.e. cap decreased base_cnt = (base_cnt+meas_cnt) >> 1; // Re-average baseline up quickly delta_cnt = 0; // Zero out delta for position determination } else { delta_cnt = meas_cnt - base_cnt; // Calculate delta: c_change } #endif /* Determine if each key is pressed per a preset threshold */ if (delta_cnt > KEY_lvl) { // turn on LED P8OUT |= BIT1; } else { // turn off LED base_cnt = base_cnt - 1; // Adjust baseline down, should be slow to P8OUT &= ~BIT1; } // Put the MSP430 into LPM3 for a certain DELAY period sleep(DELAY); } } // End Main /******************************************************************************/ // Timer0_A0 Interrupt Service Routine: Disables the timer and exists LPM3 /******************************************************************************/ #pragma vector=TIMER0_A0_VECTOR __interrupt void ISR_Timer0_A0(void) { TA0CTL &= ~(MC_1); TA0CCTL0 &= ~(CCIE); __bic_SR_register_on_exit(LPM3_bits+GIE); } #pragma vector = LCD_E_VECTOR, PORT2_VECTOR, PORT1_VECTOR, ADC_VECTOR, USCI_B0_VECTOR,USCI_A0_VECTOR,\ WDT_VECTOR, /*RTC_VECTOR,*/TIMER1_A1_VECTOR, TIMER1_A0_VECTOR, TIMER0_A1_VECTOR, /*TIMER0_A0_VECTOR,*/\ UNMI_VECTOR, SYSNMI_VECTOR __interrupt void ISR_trap(void) { // the following will cause an access violation which results in a SW BOR PMMCTL0 = PMMPW | PMMSWBOR; }
mit
clarete/s3sync
spec/spec_helper.rb
912
require 'fileutils' require 'simplecov' SimpleCov.start def fixture *args File.join File.dirname(__FILE__), "fixtures", *args end def directory path full = fixture(path) FileUtils::mkdir_p full return full end def file *args file = File.join(*args[0..-2]) directory File.dirname(file) File.open(file, 'w') {|f| f.write args[-1] } return file end def rm path FileUtils::rm_rf path end RSpec::Matchers.define :match_stdout do |check| @capture = nil match do |block| begin stdout_saved = $stdout $stdout = StringIO.new block.call ensure @capture = $stdout $stdout = stdout_saved end @capture.string.match check end failure_message do "expected to #{description}" end failure_message_when_negated do "expected not to #{description}" end description do "match [#{check}] on stdout [#{@capture.string}]" end end
mit
sillsdev/libpalaso
SIL.Windows.Forms.WritingSystems.Tests/WritingSystemFromWindowsLocaleProviderTests.cs
3430
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using NUnit.Framework; using SIL.TestUtilities; using SIL.WritingSystems; using SIL.WritingSystems.Tests; namespace SIL.Windows.Forms.WritingSystems.Tests { [TestFixture] [OfflineSldr] public class WritingSystemFromWindowsLocaleProviderTests { private class WritingSystemFromWindowsLocaleProviderAccessor: WritingSystemFromWindowsLocaleProvider { public WritingSystemFromWindowsLocaleProviderAccessor( IWritingSystemFactory writingSystemFactory) : base(writingSystemFactory) { } public static string CallGetRegion(string cultureName) { return GetRegion(cultureName); } } [Test] [Category("DesktopRequired")] // Fails on Jenkins because InputLanguage.InstalledInputLanguages returns an empty list. [Platform(Exclude = "Linux", Reason = "Linux only usually returns the Invariant, reimplement using IBus")] public void ActiveIncludesAtLeastOneLanguage() { IEnumerable<Tuple<string, string>> provider = new WritingSystemFromWindowsLocaleProvider(new TestWritingSystemFactory()); Assert.IsNotNull(provider.First()); } /// <summary> /// This is only really testing something if your computer happens to have multiple /// keyboards set up for a language. /// </summary> [Test] [Category("DesktopRequired")] // Fails on Jenkins because InputLanguage.InstalledInputLanguages returns an empty list. [Platform(Exclude = "Linux", Reason = "Linux only usually returns the Invariant, reimplement using IBus")] public void GetEnumerator_IfHaveMultipleSystemKeyboardsForSameLanguage_OnlyReturnsOneForEachLanguage() { IEnumerable<Tuple<string, string>> provider = new WritingSystemFromWindowsLocaleProvider(new TestWritingSystemFactory()); Assert.IsNotNull(provider.First()); foreach (var group in provider.GroupBy(d => d.Item1)) Assert.AreEqual(1, group.Count()); } // [Test] // public void GetGoodPropertiesOutOfCulture() // { // IEnumerable<WritingSystemDefinition> provider = // new SIL.Windows.Forms.WritingSystems.WritingSystemFromWindowsLocaleProvider(); // foreach (WritingSystemDefinition language in provider.WritingSystems) // { //// if (language.Language == "eng") //// { //// Assert.AreEqual("Latn",language.Script); //// Assert.AreEqual("en-Latn", language.RFC5646); //// } // } // } [TestCase("aa", ExpectedResult = "ET")] // returns default region [TestCase("chr", ExpectedResult = "US")] // previously ArgumentException [TestCase("chr-Cher", ExpectedResult = "US")] // previously ArgumentException [TestCase("chr-Cher-US", ExpectedResult = "US")] [TestCase("en", ExpectedResult = "US")] // previously ArgumentException [TestCase("en-US", ExpectedResult = "US")] [TestCase("en-001", ExpectedResult = "001")] [TestCase("jv-Latn", ExpectedResult = "ID")] [TestCase("jv-Latn-ID", ExpectedResult = "ID")] [TestCase("kok", ExpectedResult = "IN")] // previously ArgumentException [TestCase("kok-IN", ExpectedResult = "IN")] [TestCase("und", ExpectedResult = "")] [TestCase("und-001", ExpectedResult = "001")] public string GetRegion(string cultureName) { return WritingSystemFromWindowsLocaleProviderAccessor.CallGetRegion(cultureName); } } }
mit
goldcoin/Goldcoin-GLD
src/rpc/blockchain.cpp
65642
// Copyright (c) 2007-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "checkpointsync.h" #include "coins.h" #include "consensus/validation.h" #include "validation.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "streams.h" #include "sync.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "hash.h" #include <stdint.h> #include <univalue.h> #include <boost/thread/thread.hpp> // boost::thread::interrupt #include <mutex> #include <condition_variable> using namespace std; struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion))); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false, bool fQueuedBlock = false) { UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", !fQueuedBlock ? blockindex->GetBlockHash().GetHex() : block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("height", fQueuedBlock ? blockindex->nHeight+1 : blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion))); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); UniValue txs(UniValue::VARR); for(const auto& tx : block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(*tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("mediantime", blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex ? blockindex->nChainWork.GetHex() : 0)); if (!fQueuedBlock && blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); else result.push_back(Pair("previousblockhash", blockindex->GetBlockHash().GetHex())); if (!fQueuedBlock) { CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); } return result; } UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest blockchain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest blockchain.\n" "\nResult:\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples:\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { if(pindex) { std::lock_guard<std::mutex> lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "waitfornewblock (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitfornewblock", "1000") + HelpExampleRpc("waitfornewblock", "1000") ); int timeout = 0; if (request.params.size() > 0) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); block = latestblock; if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "waitforblock <blockhash> (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. \"blockhash\" (required, string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") ); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "waitforblockheight <height> (timeout)\n" "\nWaits for (at least) block height and returns the height and hash\n" "of the current tip.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. height (required, int) Block height to wait for (int)\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblockheight", "\"100\", 1000") + HelpExampleRpc("waitforblockheight", "\"100\", 1000") ); int timeout = 0; int height = request.params[0].get_int(); if (request.params.size() > 1) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(); } std::string EntryDescriptionString() { return " \"size\" : n, (numeric) actual transaction size\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) DEPRECATED. Priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) DEPRECATED. Transaction priority now\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" " \"ancestorsize\" : n, (numeric) transaction size of in-mempool ancestors (including this one)\n" " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n"; } void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) { AssertLockHeld(mempool.cs); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); info.push_back(Pair("ancestorcount", e.GetCountWithAncestors())); info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors())); info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors())); const CTransaction& tx = e.GetTx(); set<string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); BOOST_FOREACH(const string& dep, setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); } UniValue mempoolToJSON(bool fVerbose = false) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(hash.ToString(), info)); } return o; } else { vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); bool fVerbose = false; if (request.params.size() > 0) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "getmempoolancestors txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolancestors", "\"mytxid\"") + HelpExampleRpc("getmempoolancestors", "\"mytxid\"") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) { const CTxMemPoolEntry &e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw runtime_error( "getmempooldescendants txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool descendants.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempooldescendants", "\"mytxid\"") + HelpExampleRpc("getmempooldescendants", "\"mytxid\"") ); } bool fVerbose = false; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setDescendants; mempool.CalculateDescendants(it, setDescendants); // CTxMemPool::CalculateDescendants will include the given tx setDescendants.erase(it); if (!fVerbose) { UniValue o(UniValue::VARR); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { o.push_back(descendantIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) { const CTxMemPoolEntry &e = *descendantIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempoolentry(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw runtime_error( "getmempoolentry txid\n" "\nReturns mempool data for given transaction\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "\nResult:\n" "{ (json object)\n" + EntryDescriptionString() + "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolentry", "\"mytxid\"") + HelpExampleRpc("getmempoolentry", "\"mytxid\"") ); } uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } const CTxMemPoolEntry &e = *it; UniValue info(UniValue::VOBJ); entryToJSON(info, e); return info; } UniValue getblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "getblockhash height\n" "\nReturns hash of block in best-block-chain at height provided.\n" "\nArguments:\n" "1. height (numeric, required) The height index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") + HelpExampleRpc("getblockheader", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw runtime_error( "getblock \"blockhash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"weight\" : n (numeric) The block weight as defined in BIP 141\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") + HelpExampleRpc("getblock", "\"e2acdf2dd19a702e5d12a925f1e984b01e47a933562ca893656d4afb38b44ee3\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); shared_ptr<const CBlock> queuedBlock; bool fVerbose = true; if (request.params.size() > 1) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) { queuedBlock = GetQueuedBlock(); if(queuedBlock == nullptr || queuedBlock->GetHash().Compare(hash) != 0 || nReportQueuedBlocks != REPORT_QUEUED_BLOCK_TRANSACTION) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } CBlock block; CBlockIndex* pblockindex = queuedBlock == nullptr ? mapBlockIndex[hash] : 0; if(queuedBlock == nullptr) { if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } else { //Copy the block so it is available in the waiting thread. CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); queuedBlock->Serialize(stream); stream.Rewind(stream.size()); block.Unserialize(stream); pblockindex = chainActive.Tip(); } if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex, false, queuedBlock != nullptr); } // RPC commands related to sync checkpoints // get information of sync-checkpoint (first introduced in ppcoin) UniValue getcheckpoint(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); UniValue result(UniValue::VARR); UniValue entry(UniValue::VOBJ); CBlockIndex* pindexCheckpoint; entry.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str())); if (mapBlockIndex.count(hashSyncCheckpoint)) { pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint]; entry.push_back(Pair("height", pindexCheckpoint->nHeight)); entry.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime())); } if (IsArgSet("-checkpointkey")) entry.push_back(Pair("checkpointmaster", true)); result.push_back(entry); return result; } UniValue sendcheckpoint(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "sendcheckpoint <blockhash>\n" "Send a synchronized checkpoint.\n"); if (IsArgSet("-checkpointkey") || CSyncCheckpoint::strMasterPrivKey.empty()) throw std::runtime_error("Not a checkpointmaster node, first set checkpointkey in configuration and restart client. "); std::string strHash = request.params[0].get_str(); uint256 hash = uint256S(strHash); if (!SendSyncCheckpoint(hash)) throw std::runtime_error("Failed to send checkpoint, check log. "); UniValue result(UniValue::VARR); UniValue entry(UniValue::VOBJ); CBlockIndex* pindexCheckpoint; entry.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str())); if (mapBlockIndex.count(hashSyncCheckpoint)) { pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint]; entry.push_back(Pair("height", pindexCheckpoint->nHeight)); entry.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime())); } if (IsArgSet("-checkpointkey")) entry.push_back(Pair("checkpointmaster", true)); result.push_back(entry); return result; } struct CCoinsStats { int nHeight; uint256 hashBlock; uint64_t nTransactions; uint64_t nTransactionOutputs; uint64_t nSerializedSize; uint256 hashSerialized; CAmount nTotalAmount; CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {} }; //! Calculate statistics about the unspent transaction output set static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) { std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); uint256 key; CCoins coins; if (pcursor->GetKey(key) && pcursor->GetValue(coins)) { stats.nTransactions++; ss << key; for (unsigned int i=0; i<coins.vout.size(); i++) { const CTxOut &out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i+1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + pcursor->GetValueSize(); ss << VARINT(0); } else { return error("%s: unable to read value", __func__); } pcursor->Next(); } stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } UniValue pruneblockchain(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "pruneblockchain\n" "\nArguments:\n" "1. \"height\" (numeric, required) The block height to prune up to. May be set to a discrete height, or a unix timestamp\n" " to prune blocks whose block time is at least 2 hours older than the provided timestamp.\n" "\nResult:\n" "n (numeric) Height of the last block pruned.\n" "\nExamples:\n" + HelpExampleCli("pruneblockchain", "1000") + HelpExampleRpc("pruneblockchain", "1000")); if (!fPruneMode) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Cannot prune blocks because node is not in prune mode."); LOCK(cs_main); int heightParam = request.params[0].get_int(); if (heightParam < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative block height."); // Height value more than a billion is too high to be a block height, and // too low to be a block time (corresponds to timestamp from Sep 2001). if (heightParam > 1000000000) { // Add a 2 hour buffer to include blocks which might have had old timestamps CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - 7200); if (!pindex) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not find block with at least the specified timestamp."); } heightParam = pindex->nHeight; } unsigned int height = (unsigned int) heightParam; unsigned int chainHeight = (unsigned int) chainActive.Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_INTERNAL_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) throw JSONRPCError(RPC_INVALID_PARAMETER, "Blockchain is shorter than the attempted prune height."); else if (height > chainHeight - MIN_BLOCKS_TO_KEEP) { LogPrint("rpc", "Attempt to prune blocks close to the tip. Retaining the minimum number of blocks."); height = chainHeight - MIN_BLOCKS_TO_KEEP; } PruneBlockFilesManual(height); return uint64_t(height); } UniValue gettxoutsetinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (GetUTXOStats(pcoinsTip, stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } else { throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); } return ret; } UniValue gettxout(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw runtime_error( "gettxout \"txid\" n ( include_mempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout number\n" "3. include_mempool (boolean, optional) Whether to include the mempool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of goldcoin addresses\n" " \"address\" (string) goldcoin address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int n = request.params[1].get_int(); bool fMempool = true; if (request.params.size() > 2) fMempool = request.params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return NullUniValue; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return NullUniValue; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return NullUniValue; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } UniValue verifychain(const JSONRPCRequest& request) { int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (request.fHelp || request.params.size() > 2) throw runtime_error( "verifychain ( checklevel nblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (request.params.size() > 0) nCheckLevel = request.params[0].get_int(); if (request.params.size() > 1) nCheckDepth = request.params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); bool activated = false; bool hasSuperMajority = pindex->nHeight >= consensusParams.BIP65Height ? true : CBlockIndex::IsSuperMajority(4, pindex->pprev, consensusParams, consensusParams.nEnforceBlockUpgradeMajority); switch(version) { case 2: activated = pindex->nHeight >= consensusParams.BIP34Height || hasSuperMajority; break; case 3: activated = pindex->nHeight >= consensusParams.BIP66Height|| hasSuperMajority; break; case 4: activated = pindex->nHeight >= consensusParams.BIP65Height|| hasSuperMajority; break; } rv.push_back(Pair("status", activated)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); rv.push_back(Pair("version", version)); rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams))); return rv; } static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { UniValue rv(UniValue::VOBJ); const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id); switch (thresholdState) { case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break; case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break; case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break; case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break; case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break; } if (THRESHOLD_STARTED == thresholdState) { rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit)); } rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime)); rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout)); rv.push_back(Pair("since", VersionBitsTipStateSinceHeight(consensusParams, id))); return rv; } void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) { // Deployments with timeout value of 0 are hidden. // A timeout value of 0 guarantees a softfork will never be activated. // This is used when softfork codes are merged without specifying the deployment schedule. if (consensusParams.vDeployments[id].nTimeout > 0) bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id))); } UniValue getblockchaininfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding blockchain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"pruned\": xx, (boolean) if the blocks are subject to pruning\n" " \"pruneheight\": xxxxxx, (numeric) lowest-height complete block stored\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " },\n" " }, ...\n" " ],\n" " \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n" " \"xxxx\" : { (string) name of the softfork\n" " \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n" " \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n" " \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n" " \"timeout\": xx, (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n" " \"since\": xx (numeric) height of the first block to which the status applies\n" " }\n" " }\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("pruned", fPruneMode)); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); UniValue bip9_softforks(UniValue::VOBJ); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("bip9_softforks", bip9_softforks)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair("pruneheight", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. * - add chainActive.Tip() */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; std::set<const CBlockIndex*> setOrphans; std::set<const CBlockIndex*> setPrevs; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { if (!chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } } for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) { if (setPrevs.erase(*it) == 0) { setTips.insert(*it); } } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); BOOST_FOREACH(const CBlockIndex* block, setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair("maxmempool", (int64_t) maxmempool)); ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK()))); return ret; } UniValue getmempoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all serialized transaction sizes\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } UniValue preciousblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "preciousblock \"blockhash\"\n" "\nTreats a block as if it were received before others with the same work.\n" "\nA later preciousblock call can override the effect of an earlier one.\n" "\nThe effects of preciousblock are not retained across restarts.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("preciousblock", "\"blockhash\"") + HelpExampleRpc("preciousblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CBlockIndex* pblockindex; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hash]; } CValidationState state; PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue invalidateblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "invalidateblock \"blockhash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw runtime_error( "reconsiderblock \"blockhash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ResetBlockFailureFlags(pblockindex); } CValidationState state; ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } static const CRPCCommand commands[] = { // category name actor (function) okSafe argNames // --------------------- ------------------------ ----------------------- ------ ---------- { "blockchain", "getblockchaininfo", &getblockchaininfo, true, {} }, { "blockchain", "getbestblockhash", &getbestblockhash, true, {} }, { "blockchain", "getblockcount", &getblockcount, true, {} }, { "blockchain", "getblock", &getblock, true, {"blockhash","verbose"} }, { "blockchain", "getblockhash", &getblockhash, true, {"height"} }, { "blockchain", "getblockheader", &getblockheader, true, {"blockhash","verbose"} }, { "blockchain", "getcheckpoint", &getcheckpoint, true, {} }, { "blockchain", "sendcheckpoint", &sendcheckpoint, true, {"blockhash"} }, { "blockchain", "getchaintips", &getchaintips, true, {} }, { "blockchain", "getdifficulty", &getdifficulty, true, {} }, { "blockchain", "getmempoolancestors", &getmempoolancestors, true, {"txid","verbose"} }, { "blockchain", "getmempooldescendants", &getmempooldescendants, true, {"txid","verbose"} }, { "blockchain", "getmempoolentry", &getmempoolentry, true, {"txid"} }, { "blockchain", "getmempoolinfo", &getmempoolinfo, true, {} }, { "blockchain", "getrawmempool", &getrawmempool, true, {"verbose"} }, { "blockchain", "gettxout", &gettxout, true, {"txid","n","include_mempool"} }, { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, {} }, { "blockchain", "pruneblockchain", &pruneblockchain, true, {"height"} }, { "blockchain", "verifychain", &verifychain, true, {"checklevel","nblocks"} }, { "blockchain", "preciousblock", &preciousblock, true, {"blockhash"} }, /* Not shown in help */ { "hidden", "invalidateblock", &invalidateblock, true, {"blockhash"} }, { "hidden", "reconsiderblock", &reconsiderblock, true, {"blockhash"} }, { "hidden", "waitfornewblock", &waitfornewblock, true, {"timeout"} }, { "hidden", "waitforblock", &waitforblock, true, {"blockhash","timeout"} }, { "hidden", "waitforblockheight", &waitforblockheight, true, {"height","timeout"} }, }; void RegisterBlockchainRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
mit
starius/lua-npge
spec/sequence/to_fasta_spec.lua
832
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2016 Boris Nagaev -- See the LICENSE file for terms of use. describe("npge.sequence.toFasta", function() it("converts sequence to fasta", function() local model = require 'npge.model' local s = model.Sequence("g&c&c", string.rep("ATAT", 100)) local toFasta = require 'npge.sequence.toFasta' local fasta = toFasta(s) local split = require 'npge.util.split' local lines = split(fasta, '\n') local itFromArray = require 'npge.util.itFromArray' local it = itFromArray(lines) local ReadSequencesFromFasta = require 'npge.io.ReadSequencesFromFasta' local bs = ReadSequencesFromFasta(it) assert.equal(bs, model.BlockSet({s}, {})) end) end)
mit
kego/ke
tests/packer/silent/silent.go
134
package silent // silent import - e.g. only referenced in Go code, not in json imports // frizz type Silent interface { Silent() }
mit
nanobox-io/nanobox-pkgsrc-base
nodejs08/Makefile
1570
# $NetBSD$ # DISTNAME= node-v0.8.28 CATEGORIES= devel MASTER_SITES= http://nodejs.org/dist/${DISTNAME:S/node-//}/ PKGNAME= ${DISTNAME:S/-v/js-/} MAINTAINER= [email protected] HOMEPAGE= http://nodejs.org/ COMMENT= V8 JavaScript for clients and servers LICENSE= mit CHECK_INTERPRETER= no HAS_CONFIGURE= yes USE_TOOLS+= pkg-config USE_TOOLS+= gmake USE_LANGUAGES= c c++ .include "../../mk/bsd.prefs.mk" .include "options.mk" SUBST_CLASSES+= python SUBST_STAGE.python= pre-configure SUBST_MESSAGE.python= Fixing Python references SUBST_FILES.python= node.gyp deps/v8/tools/gyp/v8.gyp SUBST_VARS.python= PYTHONBIN SUBST_CLASSES+= man SUBST_STAGE.man= pre-configure SUBST_MESSAGE.man= Fixing man path SUBST_FILES.man= tools/install.py SUBST_VARS.man= PKGMANDIR CONFIG_SHELL= ${PYTHONBIN} CONFIGURE_ARGS+= --prefix=${PREFIX} .if ${OPSYS} == "NetBSD" CONFIGURE_ENV+= GYP_DEFINES="OS=netbsd" MAKE_ENV+= GYP_DEFINES="OS=netbsd" .endif REPLACE_PYTHON+= configure REPLACE_PYTHON+= tools/genv8constants.py REPLACE_PYTHON+= tools/gyp_node REPLACE_PYTHON+= tools/gyp/pylib/gyp/sun_tool.py REPLACE_PYTHON+= tools/node-waf REPLACE_PYTHON+= tools/waf-light REPLACE_PYTHON+= tools/wafadmin/*.py REPLACE_PYTHON+= tools/wafadmin/Tools/*.py CHECK_INTERPRETER_SKIP+= lib/node_modules/npm/* .if ${OPSYS} == "NetBSD" || ${OPSYS} == "FreeBSD" || ${OPSYS} == "OpenBSD" . include "../../wip/libexecinfo/buildlink3.mk" .endif .if ${OPSYS} == "NetBSD" BUILD_DEPENDS+= lockf-[0-9]*:../../wip/lockf .endif .include "../../lang/python/application.mk" .include "../../mk/bsd.pkg.mk"
mit
dm-dashboard/dashboard
node_modules/npm/html/doc/api/npm-ls.html
4421
<!doctype html> <html> <title>npm-ls</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <link rel="canonical" href="https://www.npmjs.org/doc/api/npm-ls.html"> <script async=true src="../../static/toc.js"></script> <body> <div id="wrapper"> <h1><a href="../api/npm-ls.html">npm-ls</a></h1> <p>List installed packages</p> <h2 id="synopsis">SYNOPSIS</h2> <pre><code>npm.commands.ls(args, [silent,] callback) </code></pre><h2 id="description">DESCRIPTION</h2> <p>This command will print to stdout all the versions of packages that are installed, as well as their dependencies, in a tree-structure. It will also return that data using the callback.</p> <p>This command does not take any arguments, but args must be defined. Beyond that, if any arguments are passed in, npm will politely warn that it does not take positional arguments, though you may set config flags like with any other command, such as <code>global</code> to list global packages.</p> <p>It will print out extraneous, missing, and invalid packages.</p> <p>If the silent parameter is set to true, nothing will be output to the screen, but the data will still be returned.</p> <p>Callback is provided an error if one occurred, the full data about which packages are installed and which dependencies they will receive, and a &quot;lite&quot; data object which just shows which versions are installed where. Note that the full data object is a circular structure, so care must be taken if it is serialized to JSON.</p> <h2 id="configuration">CONFIGURATION</h2> <h3 id="long">long</h3> <ul> <li>Default: false</li> <li>Type: Boolean</li> </ul> <p>Show extended information.</p> <h3 id="parseable">parseable</h3> <ul> <li>Default: false</li> <li>Type: Boolean</li> </ul> <p>Show parseable output instead of tree view.</p> <h3 id="global">global</h3> <ul> <li>Default: false</li> <li>Type: Boolean</li> </ul> <p>List packages in the global install prefix instead of in the current project.</p> <p>Note, if parseable is set or long isn&#39;t set, then duplicates will be trimmed. This means that if a submodule has the same dependency as a parent module, then the dependency will only be output once.</p> </div> <table border=0 cellspacing=0 cellpadding=0 id=npmlogo> <tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18>&nbsp;</td></tr> <tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td colspan=6 style="width:60px;height:10px;background:#fff">&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td></tr> <tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2>&nbsp;</td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff" rowspan=2>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff">&nbsp;</td></tr> <tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6>&nbsp;</td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td></tr> <tr><td colspan=5 style="width:50px;height:10px;background:#fff">&nbsp;</td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4>&nbsp;</td><td style="width:90px;height:10px;background:#fff" colspan=9>&nbsp;</td></tr> </table> <p id="footer">npm-ls &mdash; [email protected]</p>
mit
rusekr/JsSIP
lib/Transport.js
8034
module.exports = Transport; var C = { // Transport status codes STATUS_READY: 0, STATUS_DISCONNECTED: 1, STATUS_ERROR: 2 }; /** * Expose C object. */ Transport.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Transport'); var debugerror = require('debug')('JsSIP:ERROR:Transport'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('./Constants'); var Parser = require('./Parser'); var UA = require('./UA'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); // 'websocket' module uses the native WebSocket interface when bundled to run in a browser. var W3CWebSocket = require('websocket').w3cwebsocket; function Transport(ua, server) { this.ua = ua; this.ws = null; this.server = server; this.reconnection_attempts = 0; this.closed = false; this.connected = false; this.reconnectTimer = null; this.lastTransportError = {}; /** * Options for the Node "websocket" library. */ this.node_websocket_options = this.ua.configuration.node_websocket_options || {}; // Add our User-Agent header. this.node_websocket_options.headers = this.node_websocket_options.headers || {}; this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT; } Transport.prototype = { /** * Connect socket. */ connect: function() { var transport = this; if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) { debug('WebSocket ' + this.server.ws_uri + ' is already connected'); return false; } if(this.ws) { this.ws.close(); } debug('connecting to WebSocket ' + this.server.ws_uri); this.ua.onTransportConnecting(this, (this.reconnection_attempts === 0)?1:this.reconnection_attempts); try { // Hack in case W3CWebSocket is not the class exported by Node-WebSocket // (may just happen if the above `var W3CWebSocket` line is overriden by // `var W3CWebSocket = global.W3CWebSocket`). if (W3CWebSocket.length > 3) { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig); } else { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip'); } this.ws.binaryType = 'arraybuffer'; this.ws.onopen = function() { transport.onOpen(); }; this.ws.onclose = function(e) { transport.onClose(e); }; this.ws.onmessage = function(e) { transport.onMessage(e); }; this.ws.onerror = function(e) { transport.onError(e); }; } catch(e) { debugerror('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e); this.lastTransportError.code = null; this.lastTransportError.reason = e.message; this.ua.onTransportError(this); } }, /** * Disconnect socket. */ disconnect: function() { if(this.ws) { // Clear reconnectTimer clearTimeout(this.reconnectTimer); // TODO: should make this.reconnectTimer = null here? this.closed = true; debug('closing WebSocket ' + this.server.ws_uri); this.ws.close(); } // TODO: Why this?? if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.ua.onTransportDisconnected({ transport: this, code: this.lastTransportError.code, reason: this.lastTransportError.reason }); } }, /** * Send a message. */ send: function(msg) { var message = msg.toString(); if(this.ws && this.ws.readyState === this.ws.OPEN) { debug('sending WebSocket message:\n%s\n', message); this.ws.send(message); return true; } else { debugerror('unable to send message, WebSocket is not open'); return false; } }, // Transport Event Handlers onOpen: function() { this.connected = true; debug('WebSocket ' + this.server.ws_uri + ' connected'); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // Reset reconnection_attempts this.reconnection_attempts = 0; // Disable closed this.closed = false; // Trigger onTransportConnected callback this.ua.onTransportConnected(this); }, onClose: function(e) { var connected_before = this.connected; this.connected = false; this.lastTransportError.code = e.code; this.lastTransportError.reason = e.reason; debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')'); if(e.wasClean === false) { debugerror('WebSocket abrupt disconnection'); } // Transport was connected if (connected_before === true) { this.ua.onTransportClosed(this); // Check whether the user requested to close. if(!this.closed) { this.reConnect(); } } else { // This is the first connection attempt // May be a network error (or may be UA.stop() was called) this.ua.onTransportError(this); } }, onMessage: function(e) { var message, transaction, data = e.data; // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received WebSocket message with CRLF Keep Alive response'); return; } // WebSocket binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debugerror('received WebSocket binary message failed to be converted into string, message discarded'); return; } debug('received WebSocket binary message:\n%s\n', data); } // WebSocket text message. else { debug('received WebSocket text message:\n%s\n', data); } message = Parser.parseMessage(data, this.ua); if (! message) { return; } if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this.ua, this)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = this; this.ua.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.ua.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.ua.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } }, onError: function(e) { debugerror('WebSocket connection error: %o', e); }, /** * Reconnection attempt logic. */ reConnect: function() { var transport = this; this.reconnection_attempts += 1; if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) { debugerror('maximum reconnection attempts for WebSocket ' + this.server.ws_uri); this.ua.onTransportError(this); } else { debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')'); this.reconnectTimer = setTimeout(function() { transport.connect(); transport.reconnectTimer = null; }, this.ua.configuration.ws_server_reconnection_timeout * 1000); } } };
mit
RanadeepPolavarapu/IRCd
unrealircd/src/modules/extbans/realname.c
2241
/* * Extended ban to ban based on real name / gecos field (+b ~r) * (C) Copyright 2003-.. Bram Matthys (Syzop) and the UnrealIRCd team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "unrealircd.h" ModuleHeader MOD_HEADER(realname) = { "chanmodes/extbans/realname", "4.0", "ExtBan ~r - Ban based on realname/gecos field", "3.2-b8-1", NULL }; /* Forward declarations */ char *extban_realname_conv_param(char *para); int extban_realname_is_banned(aClient *sptr, aChannel *chptr, char *banin, int type); /** Called upon module init */ MOD_INIT(realname) { ExtbanInfo req; req.flag = 'r'; req.is_ok = NULL; req.conv_param = extban_realname_conv_param; req.is_banned = extban_realname_is_banned; req.options = EXTBOPT_CHSVSMODE|EXTBOPT_INVEX; if (!ExtbanAdd(modinfo->handle, req)) { config_error("could not register extended ban type"); return MOD_FAILED; } MARK_AS_OFFICIAL_MODULE(modinfo); return MOD_SUCCESS; } /** Called upon module load */ MOD_LOAD(realname) { return MOD_SUCCESS; } /** Called upon unload */ MOD_UNLOAD(realname) { return MOD_SUCCESS; } /** Realname bans - conv_param */ char *extban_realname_conv_param(char *para) { static char retbuf[REALLEN + 8]; char *mask; strlcpy(retbuf, para, sizeof(retbuf)); mask = retbuf+3; if (strlen(mask) > REALLEN + 3) mask[REALLEN + 3] = '\0'; if (*mask == '~') *mask = '?'; /* Is this good? No ;) */ return retbuf; } int extban_realname_is_banned(aClient *sptr, aChannel *chptr, char *banin, int type) { char *ban = banin+3; if (!match_esc(ban, sptr->info)) return 1; return 0; }
mit
firebitsbr/kbuild_openbsd
trunk/src/kmk/kmkbuiltin/mscfakes.c
20232
/* $Id: mscfakes.c 2759 2015-01-28 16:14:00Z bird $ */ /** @file * Fake Unix stuff for MSC. */ /* * Copyright (c) 2005-2015 knut st. osmundsen <[email protected]> * * This file is part of kBuild. * * kBuild is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * kBuild is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with kBuild. If not, see <http://www.gnu.org/licenses/> * */ /******************************************************************************* * Header Files * *******************************************************************************/ #include "config.h" #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include "err.h" #include "mscfakes.h" #define timeval windows_timeval #include <Windows.h> #undef timeval /******************************************************************************* * Internal Functions * *******************************************************************************/ static BOOL isPipeFd(int fd); /** * Makes corrections to a directory path that ends with a trailing slash. * * @returns temporary buffer to free. * @param ppszPath The path pointer. This is updated when necessary. * @param pfMustBeDir This is set if it must be a directory, otherwise it's cleared. */ static char * msc_fix_path(const char **ppszPath, int *pfMustBeDir) { const char *pszPath = *ppszPath; const char *psz; char *pszNew; *pfMustBeDir = 0; /* * Skip any compusory trailing slashes */ if (pszPath[0] == '/' || pszPath[0] == '\\') { if ( (pszPath[1] == '/' || pszPath[1] == '\\') && pszPath[2] != '/' && pszPath[2] != '\\') /* unc */ pszPath += 2; else /* root slash(es) */ pszPath++; } else if ( isalpha(pszPath[0]) && pszPath[1] == ':') { if (pszPath[2] == '/' || pszPath[2] == '\\') /* drive w/ slash */ pszPath += 3; else /* drive relative path. */ pszPath += 2; } /* else: relative path, no skipping necessary. */ /* * Any trailing slashes to drop off? */ psz = strchr(pszPath, '\0'); if (pszPath <= psz) return NULL; if ( psz[-1] != '/' || psz[-1] != '\\') return NULL; /* figure how many, make a copy and strip them off. */ while ( psz > pszPath && ( psz[-1] == '/' || psz[-1] == '\\')) psz--; pszNew = strdup(pszPath); pszNew[psz - pszPath] = '\0'; *pfMustBeDir = 1; *ppszPath = pszNew; /* use this one */ return pszNew; } int birdSetErrno(unsigned dwErr) { switch (dwErr) { default: case ERROR_INVALID_FUNCTION: errno = EINVAL; break; case ERROR_FILE_NOT_FOUND: errno = ENOENT; break; case ERROR_PATH_NOT_FOUND: errno = ENOENT; break; case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break; case ERROR_ACCESS_DENIED: errno = EACCES; break; case ERROR_INVALID_HANDLE: errno = EBADF; break; case ERROR_ARENA_TRASHED: errno = ENOMEM; break; case ERROR_NOT_ENOUGH_MEMORY: errno = ENOMEM; break; case ERROR_INVALID_BLOCK: errno = ENOMEM; break; case ERROR_BAD_ENVIRONMENT: errno = E2BIG; break; case ERROR_BAD_FORMAT: errno = ENOEXEC; break; case ERROR_INVALID_ACCESS: errno = EINVAL; break; case ERROR_INVALID_DATA: errno = EINVAL; break; case ERROR_INVALID_DRIVE: errno = ENOENT; break; case ERROR_CURRENT_DIRECTORY: errno = EACCES; break; case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break; case ERROR_NO_MORE_FILES: errno = ENOENT; break; case ERROR_LOCK_VIOLATION: errno = EACCES; break; case ERROR_BAD_NETPATH: errno = ENOENT; break; case ERROR_NETWORK_ACCESS_DENIED: errno = EACCES; break; case ERROR_BAD_NET_NAME: errno = ENOENT; break; case ERROR_FILE_EXISTS: errno = EEXIST; break; case ERROR_CANNOT_MAKE: errno = EACCES; break; case ERROR_FAIL_I24: errno = EACCES; break; case ERROR_INVALID_PARAMETER: errno = EINVAL; break; case ERROR_NO_PROC_SLOTS: errno = EAGAIN; break; case ERROR_DRIVE_LOCKED: errno = EACCES; break; case ERROR_BROKEN_PIPE: errno = EPIPE; break; case ERROR_DISK_FULL: errno = ENOSPC; break; case ERROR_INVALID_TARGET_HANDLE: errno = EBADF; break; case ERROR_WAIT_NO_CHILDREN: errno = ECHILD; break; case ERROR_CHILD_NOT_COMPLETE: errno = ECHILD; break; case ERROR_DIRECT_ACCESS_HANDLE: errno = EBADF; break; case ERROR_NEGATIVE_SEEK: errno = EINVAL; break; case ERROR_SEEK_ON_DEVICE: errno = EACCES; break; case ERROR_DIR_NOT_EMPTY: errno = ENOTEMPTY; break; case ERROR_NOT_LOCKED: errno = EACCES; break; case ERROR_BAD_PATHNAME: errno = ENOENT; break; case ERROR_MAX_THRDS_REACHED: errno = EAGAIN; break; case ERROR_LOCK_FAILED: errno = EACCES; break; case ERROR_ALREADY_EXISTS: errno = EEXIST; break; case ERROR_FILENAME_EXCED_RANGE: errno = ENOENT; break; case ERROR_NESTING_NOT_ALLOWED: errno = EAGAIN; break; #ifdef EMLINK case ERROR_TOO_MANY_LINKS: errno = EMLINK; break; #endif } return -1; } char *dirname(char *path) { /** @todo later */ return path; } int lchmod(const char *pszPath, mode_t mode) { int rc = 0; int fMustBeDir; char *pszPathFree = msc_fix_path(&pszPath, &fMustBeDir); /* * Get the current attributes */ DWORD fAttr = GetFileAttributes(pszPath); if (fAttr == INVALID_FILE_ATTRIBUTES) rc = birdSetErrno(GetLastError()); else if (fMustBeDir & !(fAttr & FILE_ATTRIBUTE_DIRECTORY)) { errno = ENOTDIR; rc = -1; } else { /* * Modify the attributes and try set them. */ if (mode & _S_IWRITE) fAttr &= ~FILE_ATTRIBUTE_READONLY; else fAttr |= FILE_ATTRIBUTE_READONLY; if (!SetFileAttributes(pszPath, fAttr)) rc = birdSetErrno(GetLastError()); } if (pszPathFree) { int saved_errno = errno; free(pszPathFree); errno = saved_errno; } return rc; } int msc_chmod(const char *pszPath, mode_t mode) { int rc = 0; int fMustBeDir; char *pszPathFree = msc_fix_path(&pszPath, &fMustBeDir); /* * Get the current attributes. */ DWORD fAttr = GetFileAttributes(pszPath); if (fAttr == INVALID_FILE_ATTRIBUTES) rc = birdSetErrno(GetLastError()); else if (fMustBeDir & !(fAttr & FILE_ATTRIBUTE_DIRECTORY)) { errno = ENOTDIR; rc = -1; } else if (fAttr & FILE_ATTRIBUTE_REPARSE_POINT) { errno = ENOSYS; /** @todo resolve symbolic link / rewrite to NtSetInformationFile. */ rc = -1; } else { /* * Modify the attributes and try set them. */ if (mode & _S_IWRITE) fAttr &= ~FILE_ATTRIBUTE_READONLY; else fAttr |= FILE_ATTRIBUTE_READONLY; if (!SetFileAttributes(pszPath, fAttr)) rc = birdSetErrno(GetLastError()); } if (pszPathFree) { int saved_errno = errno; free(pszPathFree); errno = saved_errno; } return rc; } typedef BOOL (WINAPI *PFNCREATEHARDLINKA)(LPCSTR, LPCSTR, LPSECURITY_ATTRIBUTES); int link(const char *pszDst, const char *pszLink) { static PFNCREATEHARDLINKA s_pfnCreateHardLinkA = NULL; static int s_fTried = FALSE; /* The API was introduced in Windows 2000, so resolve it dynamically. */ if (!s_pfnCreateHardLinkA) { if (!s_fTried) { HMODULE hmod = LoadLibrary("KERNEL32.DLL"); if (hmod) *(FARPROC *)&s_pfnCreateHardLinkA = GetProcAddress(hmod, "CreateHardLinkA"); s_fTried = TRUE; } if (!s_pfnCreateHardLinkA) { errno = ENOSYS; return -1; } } if (s_pfnCreateHardLinkA(pszLink, pszDst, NULL)) return 0; return birdSetErrno(GetLastError()); } int mkdir_msc(const char *path, mode_t mode) { int rc = (mkdir)(path); if (rc) { size_t len = strlen(path); if (len > 0 && (path[len - 1] == '/' || path[len - 1] == '\\')) { char *str = strdup(path); while (len > 0 && (str[len - 1] == '/' || str[len - 1] == '\\')) str[--len] = '\0'; rc = (mkdir)(str); free(str); } } return rc; } int rmdir_msc(const char *path) { int rc = (rmdir)(path); if (rc) { size_t len = strlen(path); if (len > 0 && (path[len - 1] == '/' || path[len - 1] == '\\')) { char *str = strdup(path); while (len > 0 && (str[len - 1] == '/' || str[len - 1] == '\\')) str[--len] = '\0'; rc = (rmdir)(str); free(str); } } return rc; } static int doname(char *pszX, char *pszEnd) { static char s_szChars[] = "Xabcdefghijklmnopqrstuwvxyz1234567890"; int rc = 0; do { char ch; pszEnd++; ch = *(strchr(s_szChars, *pszEnd) + 1); if (ch) { *pszEnd = ch; return 0; } *pszEnd = 'a'; } while (pszEnd != pszX); return 1; } int mkstemp(char *temp) { char *pszX = strchr(temp, 'X'); char *pszEnd = strchr(pszX, '\0'); int cTries = 1000; while (--cTries > 0) { int fd; if (doname(pszX, pszEnd)) return -1; fd = open(temp, _O_EXCL | _O_CREAT | _O_BINARY | _O_RDWR, 0777); if (fd >= 0) return fd; } return -1; } /** Unix to DOS. */ static char *fix_slashes(char *psz) { char *pszRet = psz; for (; *psz; psz++) if (*psz == '/') *psz = '\\'; return pszRet; } /** Calcs the SYMBOLIC_LINK_FLAG_DIRECTORY flag for CreatesymbolcLink. */ static DWORD is_directory(const char *pszPath, const char *pszRelativeTo) { size_t cchPath = strlen(pszPath); struct stat st; if (cchPath > 0 && pszPath[cchPath - 1] == '\\' || pszPath[cchPath - 1] == '/') return 1; /* SYMBOLIC_LINK_FLAG_DIRECTORY */ if (stat(pszPath, &st)) { size_t cchRelativeTo = strlen(pszRelativeTo); char *psz = malloc(cchPath + cchRelativeTo + 4); memcpy(psz, pszRelativeTo, cchRelativeTo); memcpy(psz + cchRelativeTo, "\\", 1); memcpy(psz + cchRelativeTo + 1, pszPath, cchPath + 1); if (stat(pszPath, &st)) st.st_mode = _S_IFREG; free(psz); } return (st.st_mode & _S_IFMT) == _S_IFDIR ? 1 : 0; } int symlink(const char *pszDst, const char *pszLink) { static BOOLEAN (WINAPI *s_pfnCreateSymbolicLinkA)(LPCSTR, LPCSTR, DWORD) = 0; static BOOL s_fTried = FALSE; if (!s_fTried) { HMODULE hmod = LoadLibrary("KERNEL32.DLL"); if (hmod) *(FARPROC *)&s_pfnCreateSymbolicLinkA = GetProcAddress(hmod, "CreateSymbolicLinkA"); s_fTried = TRUE; } if (s_pfnCreateSymbolicLinkA) { char *pszDstCopy = fix_slashes(strdup(pszDst)); char *pszLinkCopy = fix_slashes(strdup(pszLink)); BOOLEAN fRc = s_pfnCreateSymbolicLinkA(pszLinkCopy, pszDstCopy, is_directory(pszDstCopy, pszLinkCopy)); DWORD err = GetLastError(); free(pszDstCopy); free(pszLinkCopy); if (fRc) return 0; switch (err) { case ERROR_NOT_SUPPORTED: errno = ENOSYS; break; case ERROR_ALREADY_EXISTS: case ERROR_FILE_EXISTS: errno = EEXIST; break; case ERROR_DIRECTORY: errno = ENOTDIR; break; case ERROR_ACCESS_DENIED: case ERROR_PRIVILEGE_NOT_HELD: errno = EPERM; break; default: errno = EINVAL; break; } return -1; } errno = ENOSYS; err(1, "symlink() is not implemented on windows!"); return -1; } #if _MSC_VER < 1400 int snprintf(char *buf, size_t size, const char *fmt, ...) { int cch; va_list args; va_start(args, fmt); cch = vsprintf(buf, fmt, args); va_end(args); return cch; } #endif int utimes(const char *pszPath, const struct timeval *paTimes) { /** @todo implement me! */ return 0; } /* We override the libc write function (in our modules only, unfortunately) so we can kludge our way around a ENOSPC problem observed on build servers capturing STDOUT and STDERR via pipes. Apparently this may happen when the pipe buffer is full, even with the mscfake_init hack in place. XXX: Probably need to hook into fwrite as well. */ ssize_t msc_write(int fd, const void *pvSrc, size_t cbSrc) { ssize_t cbRet; if (cbSrc < UINT_MAX / 4) { #ifndef MSC_WRITE_TEST cbRet = _write(fd, pvSrc, (unsigned int)cbSrc); #else cbRet = -1; errno = ENOSPC; #endif if (cbRet < 0) { /* ENOSPC on pipe kludge. */ int cbLimit; int cSinceLastSuccess; if (cbSrc == 0) return 0; if (errno != ENOSPC) return -1; #ifndef MSC_WRITE_TEST if (!isPipeFd(fd)) { errno = ENOSPC; return -1; } #endif /* Likely a full pipe buffer, try write smaller amounts and do some sleeping inbetween each unsuccessful one. */ cbLimit = cbSrc / 4; if (cbLimit < 4) cbLimit = 4; else if (cbLimit > 512) cbLimit = 512; cSinceLastSuccess = 0; cbRet = 0; #ifdef MSC_WRITE_TEST cbLimit = 4; #endif while (cbSrc > 0) { unsigned int cbAttempt = cbSrc > cbLimit ? (int)cbLimit : (int)cbSrc; ssize_t cbActual = _write(fd, pvSrc, cbAttempt); if (cbActual > 0) { assert(cbActual <= (ssize_t)cbAttempt); pvSrc = (char *)pvSrc + cbActual; cbSrc -= cbActual; cbRet += cbActual; #ifndef MSC_WRITE_TEST if (cbLimit < 32) cbLimit = 32; #endif cSinceLastSuccess = 0; } else if (errno != ENOSPC) return -1; else { /* Delay for about 30 seconds, then just give up. */ cSinceLastSuccess++; if (cSinceLastSuccess > 1860) return -1; if (cSinceLastSuccess <= 2) Sleep(0); else if (cSinceLastSuccess <= 66) { if (cbLimit >= 8) cbLimit /= 2; /* Just in case the pipe buffer is very very small. */ Sleep(1); } else Sleep(16); } } } } else { /* * Type limit exceeded. Split the job up. */ cbRet = 0; while (cbSrc > 0) { size_t cbToWrite = cbSrc > UINT_MAX / 4 ? UINT_MAX / 4 : cbSrc; ssize_t cbWritten = msc_write(fd, pvSrc, cbToWrite); if (cbWritten > 0) { pvSrc = (char *)pvSrc + (size_t)cbWritten; cbSrc -= (size_t)cbWritten; cbRet += (size_t)cbWritten; } else if (cbWritten == 0 || cbRet > 0) break; else return -1; } } return cbRet; } ssize_t writev(int fd, const struct iovec *vector, int count) { int size = 0; int i; for (i = 0; i < count; i++) { int cb = msc_write(fd, vector[i].iov_base, (int)vector[i].iov_len); if (cb < 0) return cb; size += cb; } return size; } intmax_t strtoimax(const char *nptr, char **endptr, int base) { if (*nptr != '-') return _strtoui64(nptr, endptr, base); return -(intmax_t)_strtoui64(nptr + 1, endptr, base); } uintmax_t strtoumax(const char *nptr, char **endptr, int base) { return _strtoui64(nptr, endptr, base); } int asprintf(char **strp, const char *fmt, ...) { int rc; va_list va; va_start(va, fmt); rc = vasprintf(strp, fmt, va); va_end(va); return rc; } int vasprintf(char **strp, const char *fmt, va_list va) { int rc; char *psz; size_t cb = 1024; *strp = NULL; for (;;) { va_list va2; psz = malloc(cb); if (!psz) return -1; #ifdef va_copy va_copy(va2, va); rc = snprintf(psz, cb, fmt, va2); va_end(vaCopy); #else va2 = va; rc = snprintf(psz, cb, fmt, va2); #endif if (rc < 0 || (size_t)rc < cb) break; cb *= 2; free(psz); } *strp = psz; return rc; } /** * Checks if the given file descriptor is a pipe or not. * * @returns TRUE if pipe, FALSE if not. * @param fd The libc file descriptor number. */ static BOOL isPipeFd(int fd) { /* Is pipe? */ HANDLE hFile = (HANDLE)_get_osfhandle(fd); if (hFile != INVALID_HANDLE_VALUE) { DWORD fType = GetFileType(hFile); fType &= ~FILE_TYPE_REMOTE; if (fType == FILE_TYPE_PIPE) return TRUE; } return FALSE; } /** * This is a kludge to make pipe handles blocking. * * @returns TRUE if it's now blocking, FALSE if not a pipe or we failed to fix * the blocking mode. * @param fd The libc file descriptor number. */ static BOOL makePipeBlocking(int fd) { if (isPipeFd(fd)) { /* Try fix it. */ HANDLE hFile = (HANDLE)_get_osfhandle(fd); DWORD fState = 0; if (GetNamedPipeHandleState(hFile, &fState, NULL, NULL, NULL, NULL, 0)) { fState &= ~PIPE_NOWAIT; fState |= PIPE_WAIT; if (SetNamedPipeHandleState(hFile, &fState, NULL, NULL)) return TRUE; } } return FALSE; } /** * Initializes the msc fake stuff. * @returns 0 on success (non-zero would indicate failure, see rterr.h). */ int mscfake_init(void) { /* * Kludge against _write returning ENOSPC on non-blocking pipes. */ makePipeBlocking(STDOUT_FILENO); makePipeBlocking(STDERR_FILENO); return 0; } /* * Do this before main is called. */ #pragma section(".CRT$XIA", read) #pragma section(".CRT$XIU", read) #pragma section(".CRT$XIZ", read) typedef int (__cdecl *PFNCRTINIT)(void); static __declspec(allocate(".CRT$XIU")) PFNCRTINIT g_MscFakeInitVectorEntry = mscfake_init;
mit
ditup/ditapp-ng
src/app/tags/tags-related-to-tags/tags-related-to-tags.component.spec.ts
2949
import { async, fakeAsync, tick, ComponentFixture, TestBed } from '@angular/core/testing'; import { TagsRelatedToTagsComponent } from './tags-related-to-tags.component'; import { Component, EventEmitter, Input, Output } from '@angular/core'; import { By } from '@angular/platform-browser'; import * as _ from 'lodash'; import { Tag } from '../../shared/types'; import { ModelService } from '../../model.service'; @Component({ selector: 'app-select-tags', template: '' }) class SelectTagsStubComponent { // tslint:disable-next-line:no-output-on-prefix @Output() onSelected = new EventEmitter<Tag[]>(); } @Component({ selector: 'app-tag-list', template: '' }) class TagListStubComponent { @Input() tags: Tag[] = []; } class ModelStubService { async findTagsByTags(tagsIn: Tag[]): Promise<Tag[]> { const allTags: Tag[] = [ { tagname: 'tag0' }, { tagname: 'tag1' }, { tagname: 'tag2' }, { tagname: 'tag3' }, { tagname: 'tag4' }, { tagname: 'tag5' }, { tagname: 'tag6' } ]; const tagnamesIn = _.map(tagsIn, (tag: Tag) => tag.tagname); const tagsOut: Tag[] = _.filter(allTags, (tag: Tag) => { return tagnamesIn.indexOf(tag.tagname) === -1; }); return tagsOut; } } describe('TagsRelatedToTagsComponent', () => { let component: TagsRelatedToTagsComponent; let fixture: ComponentFixture<TagsRelatedToTagsComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ TagsRelatedToTagsComponent, SelectTagsStubComponent, TagListStubComponent ], providers: [ { provide: ModelService, useClass: ModelStubService } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(TagsRelatedToTagsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); it('should contain tag selecting component', () => { const tagSelector = fixture.debugElement.query(By.css('app-select-tags')); expect(tagSelector).toBeTruthy(); }); it('should contain tag list component', () => { const tagList = fixture.debugElement.query(By.css('app-tag-list')); expect(tagList).toBeTruthy(); }); it('when tags are selected, related tags should be found and provided to app-tag-list', fakeAsync(() => { const selectTagsComponent = fixture.debugElement.query(By.css('app-select-tags')).componentInstance; const emitter = selectTagsComponent.onSelected; emitter.emit([ { tagname: 'tag0' }, { tagname: 'tag1' }, { tagname: 'tag2' }, { tagname: 'tag3' } ]); const tagListComponent = fixture.debugElement.query(By.css('app-tag-list')).componentInstance; fixture.detectChanges(); tick(); fixture.detectChanges(); expect(tagListComponent.tags.length).toEqual(3); })); });
mit
StanJav/language-ext
LanguageExt.Tests/Transformer/Traverse/IEnumerable/Collections/Que.cs
1668
using System.Collections.Generic; using System.Linq; using Xunit; using static LanguageExt.Prelude; namespace LanguageExt.Tests.Transformer.Traverse.IEnumerableT.Collections { public class QueIEnumerable { [Fact] public void EmptyEmptyIsEmptyEmpty() { Que<IEnumerable<int>> ma = Empty; var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueIEnumerableCrossProduct() { var ma = Queue<IEnumerable<int>>(Seq(1, 2), Seq(10, 20, 30)); var mb = ma.Traverse(identity); var mc = new[] { Queue(1, 10), Queue(1, 20), Queue(1, 30), Queue(2, 10), Queue(2, 20), Queue(2, 30) } .AsEnumerable(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueOfEmptiesAndNonEmptiesIsEmpty() { var ma = Queue<IEnumerable<int>>(Seq<int>(), Seq<int>(1, 2, 3)); var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } [Fact] public void QueOfEmptiesIsEmpty() { var ma = Queue<IEnumerable<int>>(Seq<int>(), Seq<int>()); var mb = ma.Traverse(identity); var mc = Enumerable.Empty<Que<int>>(); Assert.True(mb.ToSeq() == mc.ToSeq()); } } }
mit
JonMidhir/sinatra
test/radius_test.rb
1369
require File.expand_path('../helper', __FILE__) begin require 'radius' class RadiusTest < Minitest::Test def radius_app(&block) mock_app do set :views, File.dirname(__FILE__) + '/views' get('/', &block) end get '/' end it 'renders inline radius strings' do radius_app { radius '<h1>Hiya</h1>' } assert ok? assert_equal "<h1>Hiya</h1>", body end it 'renders .radius files in views path' do radius_app { radius :hello } assert ok? assert_equal "<h1>Hello From Radius</h1>\n", body end it "renders with inline layouts" do mock_app do layout { "<h1>THIS. IS. <r:yield /></h1>" } get('/') { radius '<EM>SPARTA</EM>' } end get '/' assert ok? assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>", body end it "renders with file layouts" do radius_app { radius 'Hello World', :layout => :layout2 } assert ok? assert_equal "<h1>Radius Layout!</h1>\n<p>Hello World</p>\n", body end it "raises error if template not found" do mock_app { get('/') { radius :no_such_template } } assert_raises(Errno::ENOENT) { get('/') } end it "allows passing locals" do radius_app { radius '<r:value />', :locals => { :value => 'foo' } } assert ok? assert_equal 'foo', body end end rescue LoadError warn "#{$!}: skipping radius tests" end
mit
yevheniyc/Autodidact
1o_RonR_ET_Lynda/test/demo_project_mysql/config/initializers/session_store.rb
150
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_demo_project_mysql_session'
mit
Gnucki/danf
test/unit/http/session-handler.js
2669
'use strict'; require('../../../lib/common/init'); var assert = require('assert'), request = require('supertest'), danf = require('../../../lib/server/app')(require('../../fixture/http/danf'), null, {environment: 'test', verbosity: 0, cluster: null}) ; danf.buildServer(function(app) { describe('SessionHandler', function() { it('should allow to get and set values in session', function(done) { request(app) .get('/session/0') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to regenerate the session', function(done) { request(app) .get('/session/1') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) it('should allow to destroy a session', function(done) { request(app) .get('/session/2') .expect(500) .end(function(err, res) { if (err) { if (res) { /^The session does not exist or has been destroyed\./.test(res.text); } else { /^The session does not exist or has been destroyed\./.test(err); } throw err; } done(); }) ; }) it('should allow to save and reload a session', function(done) { request(app) .get('/session/3') .expect(204) .end(function(err, res) { if (err) { if (res) { console.log(res.text); } else { console.log(err); } throw err; } done(); }) ; }) }) });
mit
byllyfish/libofp
include/ofp/protocolmsg.h
1884
// Copyright (c) 2015-2018 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #ifndef OFP_PROTOCOLMSG_H_ #define OFP_PROTOCOLMSG_H_ #include "ofp/header.h" #include "ofp/message.h" namespace ofp { class Validation; /// \brief Static base class template for all protocol message types. This class /// implements the two static methods, type() and cast(), common to all protocol /// message types. This class also specifies the minimum and maximum length of /// a message, and whether the length of the message must be a multiple of 8. template <class MsgClass, OFPType MsgType, size_t MsgMinLength = 8, size_t MsgMaxLength = 65528, bool MsgMultiple8 = true> class ProtocolMsg { public: static_assert(MsgMinLength >= 8, "MinLength must be >= 8"); static_assert(MsgMaxLength <= 65535, "MaxLength must be <= 2^16-1"); enum : size_t { MinLength = MsgMinLength, MaxLength = MsgMaxLength, Multiple8 = MsgMultiple8 && (MsgMinLength != MsgMaxLength) }; /// \returns OpenFlow message type represented by this class. static constexpr OFPType type() { return MsgType; } /// \returns Pointer to message memory as given class or nullptr. static const MsgClass *cast(const Message *message) { OFPErrorCode error; return message->castMessage<MsgClass>(&error); } /// \returns true if message length is potentially valid. static bool isLengthValid(size_t length) { return (length >= MinLength) && (length <= MaxLength) && (!Multiple8 || ((length % 8) == 0)); } const Header *msgHeader() const { return reinterpret_cast<const Header *>(this); } ByteRange msgBody() const { return ByteRange{msgHeader() + 1, msgHeader()->length() - sizeof(Header)}; } size_t msgLength() const { return msgHeader()->length(); } }; } // namespace ofp #endif // OFP_PROTOCOLMSG_H_
mit
nitishgarg88/Operating-System
bin/ls/ls.c
1454
#include <stdio.h> #include <stdlib.h> #include "utilities.h" int main(int argc, char * argv[]) { if(argc < 1) { printf("Error in ls.c\n"); } if(argc == 1) { /* list files or dir in current working dir */ char directory[100]; getcwd(directory, 100); //printf("No arguments given, so listing files in current directory: %s\n", directory); struct Dir * dir = (struct Dir *)opendir(directory); struct dirent * dentry ; while((dentry = readdir((void *)dir)) != NULL) { char data[100]; strncpy(data, dentry->d_name, strlen(dentry->d_name)); write(1, data, strlen(dentry->d_name)); write(1, "\n", 1); } } if(argc >= 2) { /* Only first folder will be considered */ //printf("Argument received: %s\n", argv[1]); char old_cwd[100]; getcwd(old_cwd, 100); char * user_input = argv[1]; int res = chdir(user_input); if(res == 0) { char new_cwd[100]; getcwd(new_cwd, 100); struct Dir * dir = (struct Dir *)opendir(new_cwd); struct dirent * dentry; while((dentry = readdir((void *)dir)) != NULL) { char data[100]; strncpy(data, dentry->d_name, strlen(dentry->d_name)); write(1, data, strlen(dentry->d_name)); write(1, "\n", 1); } /* Don't forget to reset current working directory */ chdir(old_cwd); } else { //printf("%s: No such directory\n", user_input); char * data = "No such file or directory"; write(1, data, 30); } } return 0; }
mit
jaeko44/nilavu
lib/biller/whmcs_auto_auth.rb
701
require 'uri' module Biller::WHMCSAutoAuth def self.redirect_url(email, action) ensure_autoauth_params time = Time.now.to_i query= ["email=#{email}","timestamp=#{time}", "hash="+ autoauth_hash(email, time), "goto="+ URI.encode("clientarea.php?action=#{action}")].join('&') return [SiteSetting.whmcs_autoauth_url, query].join("?") end private def self.ensure_autoauth_params raise Nilavu::NotFound unless SiteSetting.whmcs_autoauth_url && SiteSetting.whmcs_autoauth_key end def self.autoauth_hash(email, time) Digest::SHA1([email, time,SiteSetting.whmcs_autoauth_key].join('')) end end
mit
ConsultingMD/factree
test/factree/aggregate_test.rb
1330
require 'test_helper' describe Factree::Aggregate do describe ".alternatives" do let(:facts) { :facts } let(:nil_decision) { -> (_) { nil } } let(:final_decision) { -> (_) { conclusion } } let(:conclusion) { Factree::Conclusion.new(:b) } let(:decisions) { [] } subject { Factree::Aggregate.alternatives(facts, *decisions) } describe "with a nil decision followed by a final decision" do let(:decisions) { [nil_decision, final_decision] } it "decides on conclusion" do assert_equal subject, conclusion end end describe "with a final decision followed by a nil decision" do let(:decisions) { [final_decision, nil_decision] } it "decides on conclusion" do assert_equal subject, conclusion end end describe "with only a nil decision" do let(:decisions) { [nil_decision] } it "decides on nil" do assert_nil subject end end it "returns a nil decision" do assert_nil subject end describe "with a mock decision" do let(:mock_decision) { Minitest::Mock.new } let(:decisions) { [mock_decision] } it "passes facts through to decision procs" do mock_decision.expect(:call, nil, [facts]) subject mock_decision.verify end end end end
mit
whatsupmailbox/whatsupmailbox.github.io
_posts/2015-08-18-Sprezza-Box-Subscription-August-2015-Review-Coupon.md
7542
--- layout: post published: true categories: - Subscriptions - Reviews title: Sprezza Box August 2015 Review + Coupon! featured: false comments: true type: photo imagefeature: SprezzaBoxAugust2015Box.jpg headline: Sprezza Box August 2015 Review + Coupon! tags: [Sprezza Box, Subscriptions, Reviews, August 2015] date: 2015-08-18 13:22:39 -08:00 --- <center><a href="http://www.sprezzabox.com?rfsn=103516.e98b8" target="_blank"> <img src="/images/SprezzaBoxAugust2015Box.jpg" border="0" style="border:none;max-width:100%;" alt="Sprezza Box August 2015" /> </a></center> <p><b>Subscription:</b> <a href="http://www.sprezzabox.com?rfsn=103516.e98b8" target="_blank">Sprezza Box</a></p> <p><b>Cost:</b> $28/monthly + Free Shipping</p> <p><b>What's in the box:</b> You'll receive 4-5 lifestyle items plus a grooming product. Items have included ties, socks, pockets squares and all things to make you dress like a dapper man!</p> <p><b>Coupon:</b> Use coupon code <a href="http://www.sprezzabox.com?rfsn=103516.e98b8" target="_blank"><big>WHATSUPMAILBOX</big></a> to receive 10% off your first box!</p> <br> <center><img src='/images/SprezzaBoxAugust2015OpenBox.jpg'></center> <figcaption>First look at unboxing</figcaption> <br> <p>The August 2015 box is titled the <big>Empire Box</big>.</p> <br> <figure class="half"> <img src='/images/SprezzaBoxAugust2015OpenBox2.jpg'> <img src='/images/SprezzaBoxAugust2015OpenBox3.jpg'> <figcaption>More unboxing pictures</figcaption> </figure> <br> <center><img src='/images/SprezzaBoxAugust2015Info.jpg'></center> <figcaption>Info card detailing the products inside</figcaption> <br> <p>Sprezza Box is becoming one of the top boxes that my husband can't wait to receive. It's filled with quality products and their customer service is spectacular (I've experienced it myself due to receiving a flawed item). I was amazed by last month's box which included a beautiful Arvo watch (<a href="http://whatsupmailbox.com/subscriptions/reviews/Sprezza-Box-Subscription-July-2015-Review-Coupon/" target="_blank">you can read the July 2015 review here</a>)! So needless to say, it's always exciting opening up this box =)</p> <br> <DT>And here are the items:</DT> <p><center><a href="http://www.sprezzabox.com?rfsn=103516.e98b8" target="_blank"> <img src="/images/SprezzaBoxAugust2015Items.jpg" border="0" style="border:none;max-width:100%;" alt="Sprezza Box August 2015 Items" /> </a></center></p> <br> <p>How awesome is this month's items, so perfectly blue and dapper!</p> <H4>Items in Detail:</H4> <p><center><img src='/images/SprezzaBoxAugust2015Tie2.jpg'></center></p> <DL> <DT><a href="http://www.bullandmoose.com" target="_blank">Bull + Moose</a> Tie</DT> <DD>Retail Value $39</DD> </DL> <p>I love it when boxes include a tie. My husband needs to expand his tie collection since he barely has any, so this was a great item to get!</p> <p>The color and pattern is classic yet modern, so it will surely go with just about anything.</p> <center><img src='/images/SprezzaBoxAugust2015Tie.jpg'></center> <p>The tie is hand made and 100% cotton.</p> <br> <center><img src='/images/SprezzaBoxAugust2015PocketSquare.jpg'></center> <DL> <DT><a href="http://saltdapper.com/pocket-squares.html" target="_blank">Salt + Dapper Pocket Square</a></DT> <DD>Retail Value $15</DD> </DL> <p>Pocket squares are great to add that extra pop in your outfit and it definitely completes the look in my opinion. The checkered pattern fits the tie quite well and as always Sprezza Box always color coordinates the items in the box to be used together. I love that about this box!</p> <br> <center><img src='/images/SprezzaBoxAugust2015Socks.jpg'></center> <DL> <DT><a href="https://www.yo-sox.com/collections/mens-socks" target="_blank">Yo Sox! Socks</a></DT> <DD>Retail Value $9.95</DD> </DL> <p>As my husband always say, you can never have enough socks! And unlike other sub boxes, Sprezza tends to send classy patterns compared to the crazy and sometimes whacky ones that others tend to send. The Navy blue paired with the herringbone pattern goes quite well together and will certainly make your feet look dapper.</p> <p>Yo Sox! also has a "Sock of the month club" subscription where you can choose to get 1, 2 or 3 pairs of socks delivered to you monthly. You can <a href="https://www.yo-sox.com/collections/sock-of-the-month-club" target="_blank">read more about it here</a>.</p> <br> <center><img src='/images/SprezzaBoxAugust2015TieClip.jpg'></center> <DL> <DT><a href="http://www.weekendcasual.com/collections/tie-clips/products/silver-arrow-tie-clip-1-75" target="_blank">Weekend Casual SILVER ARROW Tie Clip</a></DT> <DD>Retail Value $12 (Sprezza valued this at $10 but on their website it's actually $12!)</DD> </DL> <p>Another item that my husband has very little of, a tie clip, yay! And what a cool one to boot!</p> <p>Sprezza suggests using this clip between the 3rd or 4th buttons to keep your necktie in place.</p> <center><img src='/images/SprezzaBoxAugust2015TieClip2.jpg'></center> <p>The clip came packaged in a small zipped bag for extra protection.</p> <br> <center><img src='/images/SprezzaBoxAugust2015Soap.jpg'></center> <DL> <DT><a href="http://drsquatch.com/collections/our-products/products/gold-moss-scrub" target="_blank">Dr. Squatch GOLD MOSS SCRUB Soap</a></DT> <DD>1.2 oz Sample Bar, Value $1.44</DD> </DL> <p>This soap bar smells like a handsome strong rugged man if that makes sense. It's unique and masculine, I can't wait for my husband to use this! ;)</p> <p>From Dr. Squatch: "One of our most revered scents, a truly unique bar scented with oak moss. This bar is a subtle earthy musk with a hint of freshly ground cocoa and added sea salt. Very popular with woodsmen and urbanites alike."</p> <p>There was also a coupon code to get free shipping with any order on the other side of this bar, which I will surely be using asap!</p> <br> <p><i class="icon-exclamation-sign"></i><b> My Thoughts:</b> I'm continuously happy with each and every box I've received so far and not one item disappoints! I love how everything is color coordinated which makes it easy for my husband to style himself. I also love the fact that they always have their values on point (no overpricing items here!) in fact they under valued an item this time around. To me that's the signs of a quality and reliable subscription box. I'm a loyal fan of Sprezza for sure!</p> <p>If you haven't subscribed yet, you can <a href="http://www.sprezzabox.com?rfsn=103516.e98b8" target="_blank">click here to subscribe to Sprezza Box</a> and don't forget to use coupon code <b>WHATSUPMAILBOX</b> to get 10% off your first box! This is by far becoming one of my top men's subscription boxes.</p> <br> <TABLE BORDER="5" style="width:60%"> <TR> <TH COLSPAN="2"> <H3><BR><center>ITEMS IN THE BOX</center></H3> </TH> </TR> <TH>Product</TH> <TH>Price</TH> <TR> <TD>Bull + Moose Tie</TD> <TD>$39</TD> </TR> <TR> <TD>Salt + Dapper Pocket Square</TD> <TD>$15</TD> </TR> <TR> <TD>Yo Sox! Socks</TD> <TD>$9.95</TD> </TR> <TR> <TD>Weekend Casual Tie Clip</TD> <TD>$12</TD> </TR> <TR> <TD>Dr. Squatch Soap</TD> <TD>$1.44</TD> </TR> <TR> <TD><b><big>TOTAL VALUE</big></b></TD> <TD><b><big>$77.39</big></b></TD> </TR> <TR> <TD><i><big>Subscription Cost</big></i></TD> <TD><i><big>$28</big></i></TD> </TR> </TABLE>
mit
abpolym/crypto-tools
rot/README.md
784
# Caesar Rot Implementation ``` usage: rot.py [-h] [-s] [-t] [-l] [-u] rotvalue text positional arguments: rotvalue The rotation value text The text to rotate optional arguments: -h, --help show this help message and exit -s, --seperate Rotate Lower and Upper case letters seperately -t, --total Rotate Lower and Upper case letters together -l, --loweronly Rotate Lower case letters only -u, --upperonly Rotate Upper case letters only ``` Sample usage: ```bash 0∣19ː39∣rot▶ for i in {1..52}; do python rot.py -t $i xLMWmWewIGVIXxIbX; done yMNXnXfxJHWJYyJcY zNOYoYgyKIXKZzKdZ [...] SghrHrzRdbqdsSdws ThisIsASecretText UijtJtBTfdsfuUfyu [...] sGHRhRZrDBQDSsDWS tHISiSasECRETtEXT uIJTjTbtFDSFUuFYU [...] xLMWmWewIGVIXxIbX ```
mit
tony-wuhongtao/OurYincart2
star-core/modules/station/views/default/create.php
417
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model core\models\Station */ $this->title = 'Create Station'; $this->params['breadcrumbs'][] = ['label' => 'Stations', 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="station-create"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
mit
Hexatown/docs
microsoft/office365/teams/no.md
1433
--- title: Lag inshort: Gruppe chat & videochat [slakk] translator: Microsoft Cognitive Services --- Et knutepunkt for samarbeid i Office 365 ## Chat, tale og video Kommunisere i øyeblikket og holde alle i vet. Se innhold og chat historie når som helst i team eller private samtaler. Planlegg liten gruppe eller team møter. Bokføre en e-post i en tråd å holde teamet i loopen. Fullføre møter med deling av video- og lydinnhold møter med full kalle støtte, inkludert avanserte talefunksjoner. Starte en interaktiv demonstrasjon av Microsoft Teams ## Innebygd tilgang til Office 365 apps Gi din team umiddelbar tilgang til alt de trenger rett i Office 365. Behandle alle samtaler, filer og verktøy i ett arbeidsområde-team. Få innebygd tilgang til SharePoint, OneNote, PowerBI og planlegger. Arbeide med dokumenter direkte i app. holde laget i sløyfen med e-post integrasjon. Søke på folk, filer og samtaler med intelligens fra Microsoft Graph. ## Tilpasses og utvides Skreddersy Microsoft Teams arbeidsområdet raskt tilgang til viktige tjenester, utforske data, og få oppdateringer fra apps lag bruker hver dag. Opprette ulike team kanaler basert på arbeidsflyter eller emner. PIN brukte filer for enkel referanse. Tilpasse varsler så du ikke går glipp av viktig aktivitet og informasjon fra tredjeparts tjenester. Bygge integrasjoner med APIer og legge til boter som fungerer på gruppens vegne.
mit
bluecitymoon/demo-swift-ios
demo-swift/Quickblox.framework/Versions/A/Headers/QBCBlobCompleteQuery.h
415
// // QBCBlobCompleteQuery.h // ContentService // // Copyright 2011 QuickBlox team. All rights reserved. // #import <Foundation/Foundation.h> @interface QBCBlobCompleteQuery : QBCBlobQuery { @private NSUInteger blobId; NSUInteger size; } @property (nonatomic,readonly) NSUInteger blobId; @property (nonatomic,readonly) NSUInteger size; -(id)initWithBlobId:(NSUInteger)blobid size:(NSUInteger)size; @end
mit
mahill/phaser
src/display/canvas/CanvasPool.js
7526
/** * @author Richard Davey <[email protected]> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var CONST = require('../../const'); var Smoothing = require('./Smoothing'); // The pool into which the canvas elements are placed. var pool = []; // Automatically apply smoothing(false) to created Canvas elements var _disableContextSmoothing = false; /** * The CanvasPool is a global static object, that allows Phaser to recycle and pool 2D Context Canvas DOM elements. * It does not pool WebGL Contexts, because once the context options are set they cannot be modified again, * which is useless for some of the Phaser pipelines / renderer. * * This singleton is instantiated as soon as Phaser loads, before a Phaser.Game instance has even been created. * Which means all instances of Phaser Games on the same page can share the one single pool. * * @namespace Phaser.Display.Canvas.CanvasPool * @since 3.0.0 */ var CanvasPool = function () { /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * @param {boolean} [selfParent=false] - Use the generated Canvas element as the parent? * * @return {HTMLCanvasElement} The canvas element that was created or pulled from the pool */ var create = function (parent, width, height, canvasType, selfParent) { if (width === undefined) { width = 1; } if (height === undefined) { height = 1; } if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (selfParent === undefined) { selfParent = false; } var canvas; var container = first(canvasType); if (container === null) { container = { parent: parent, canvas: document.createElement('canvas'), type: canvasType }; if (canvasType === CONST.CANVAS) { pool.push(container); } canvas = container.canvas; } else { container.parent = parent; canvas = container.canvas; } if (selfParent) { container.parent = canvas; } canvas.width = width; canvas.height = height; if (_disableContextSmoothing && canvasType === CONST.CANVAS) { Smoothing.disable(canvas.getContext('2d')); } return canvas; }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.create2D * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created canvas. */ var create2D = function (parent, width, height) { return create(parent, width, height, CONST.CANVAS); }; /** * Creates a new Canvas DOM element, or pulls one from the pool if free. * * @function Phaser.Display.Canvas.CanvasPool.createWebGL * @since 3.0.0 * * @param {*} parent - The parent of the Canvas object. * @param {integer} [width=1] - The width of the Canvas. * @param {integer} [height=1] - The height of the Canvas. * * @return {HTMLCanvasElement} The created WebGL canvas. */ var createWebGL = function (parent, width, height) { return create(parent, width, height, CONST.WEBGL); }; /** * Gets the first free canvas index from the pool. * * @function Phaser.Display.Canvas.CanvasPool.first * @since 3.0.0 * * @param {integer} [canvasType=Phaser.CANVAS] - The type of the Canvas. Either `Phaser.CANVAS` or `Phaser.WEBGL`. * * @return {HTMLCanvasElement} The first free canvas, or `null` if a WebGL canvas was requested or if the pool doesn't have free canvases. */ var first = function (canvasType) { if (canvasType === undefined) { canvasType = CONST.CANVAS; } if (canvasType === CONST.WEBGL) { return null; } for (var i = 0; i < pool.length; i++) { var container = pool[i]; if (!container.parent && container.type === canvasType) { return container; } } return null; }; /** * Looks up a canvas based on its parent, and if found puts it back in the pool, freeing it up for re-use. * The canvas has its width and height set to 1, and its parent attribute nulled. * * @function Phaser.Display.Canvas.CanvasPool.remove * @since 3.0.0 * * @param {*} parent - The canvas or the parent of the canvas to free. */ var remove = function (parent) { // Check to see if the parent is a canvas object var isCanvas = parent instanceof HTMLCanvasElement; pool.forEach(function (container) { if ((isCanvas && container.canvas === parent) || (!isCanvas && container.parent === parent)) { container.parent = null; container.canvas.width = 1; container.canvas.height = 1; } }); }; /** * Gets the total number of used canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.total * @since 3.0.0 * * @return {integer} The number of used canvases. */ var total = function () { var c = 0; pool.forEach(function (container) { if (container.parent) { c++; } }); return c; }; /** * Gets the total number of free canvas elements in the pool. * * @function Phaser.Display.Canvas.CanvasPool.free * @since 3.0.0 * * @return {integer} The number of free canvases. */ var free = function () { return pool.length - total(); }; /** * Disable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.disableSmoothing * @since 3.0.0 */ var disableSmoothing = function () { _disableContextSmoothing = true; }; /** * Enable context smoothing on any new Canvas element created. * * @function Phaser.Display.Canvas.CanvasPool.enableSmoothing * @since 3.0.0 */ var enableSmoothing = function () { _disableContextSmoothing = false; }; return { create2D: create2D, create: create, createWebGL: createWebGL, disableSmoothing: disableSmoothing, enableSmoothing: enableSmoothing, first: first, free: free, pool: pool, remove: remove, total: total }; }; // If we export the called function here, it'll only be invoked once (not every time it's required). module.exports = CanvasPool();
mit
Hexadorsimal/pynes
nes/processors/cpu/__init__.py
21
from .cpu import Cpu
mit
JayWalker512/brandonfoltz.com
projects.php
1055
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <?php require_once("globals.php"); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <?php $page_title = "Projects"; require_once("meta.php"); ?> </head> <body> <div id="logo"> <?php require_once("header.php"); ?> </div> <!-- end of logo --> <div id="header"> <div id="navigation"> <?php require_once("navigation.php"); ?> </div> <!-- end of navigation --> </div> <!-- end of header --> <div id="wrap"> <div id="wrap-btm"> <div id="main"> <div id="content"> <div class="post"> projects </div> </div> <!-- end of content --> <!-- start sidebar --> <div id="sidepanel"> <?php require_once("leftpanel.php"); ?> </div> <div style="clear: both;">&nbsp;</div> </div> <!-- end of main --> </div> <!-- end of wrap --> </div> <!-- end of wrap-btm --> <div id="footer-wrap"> <div id="footer"> <?php require_once("footer.php"); ?> </div> </div> <!-- end of footer --> </body> </html>
mit
selste/micropython
ports/stm32/Makefile
19715
# Select the board to build for: if not given on the command line, # then default to PYBV10. BOARD ?= PYBV10 # If the build directory is not given, make it reflect the board name. BUILD ?= build-$(BOARD) BOARD_DIR ?= boards/$(BOARD) ifeq ($(wildcard $(BOARD_DIR)/.),) $(error Invalid BOARD specified: $(BOARD_DIR)) endif include ../../py/mkenv.mk -include mpconfigport.mk include $(BOARD_DIR)/mpconfigboard.mk # Files that are generated and needed before the QSTR build. QSTR_GENERATED_HEADERS = $(BUILD)/pins_qstr.h $(BUILD)/modstm_qstr.h # qstr definitions (must come before including py.mk) QSTR_DEFS = qstrdefsport.h $(QSTR_GENERATED_HEADERS) QSTR_GLOBAL_DEPENDENCIES = mpconfigboard_common.h $(BOARD_DIR)/mpconfigboard.h $(QSTR_GENERATED_HEADERS) # MicroPython feature configurations MICROPY_ROM_TEXT_COMPRESSION ?= 1 # File containing description of content to be frozen into firmware. FROZEN_MANIFEST ?= boards/manifest.py # include py core make definitions include $(TOP)/py/py.mk GIT_SUBMODULES = lib/lwip lib/mbedtls lib/mynewt-nimble lib/stm32lib MCU_SERIES_UPPER = $(shell echo $(MCU_SERIES) | tr '[:lower:]' '[:upper:]') CMSIS_MCU_LOWER = $(shell echo $(CMSIS_MCU) | tr '[:upper:]' '[:lower:]') LD_DIR=boards CMSIS_DIR=$(TOP)/lib/stm32lib/CMSIS/STM32$(MCU_SERIES_UPPER)xx/Include HAL_DIR=lib/stm32lib/STM32$(MCU_SERIES_UPPER)xx_HAL_Driver USBDEV_DIR=usbdev #USBHOST_DIR=usbhost DFU=$(TOP)/tools/dfu.py # may need to prefix dfu-util with sudo USE_PYDFU ?= 1 PYDFU ?= $(TOP)/tools/pydfu.py DFU_UTIL ?= dfu-util BOOTLOADER_DFU_USB_VID ?= 0x0483 BOOTLOADER_DFU_USB_PID ?= 0xDF11 STFLASH ?= st-flash OPENOCD ?= openocd OPENOCD_CONFIG ?= boards/openocd_stm32f4.cfg STARTUP_FILE ?= lib/stm32lib/CMSIS/STM32$(MCU_SERIES_UPPER)xx/Source/Templates/gcc/startup_$(CMSIS_MCU_LOWER).o SYSTEM_FILE ?= lib/stm32lib/CMSIS/STM32$(MCU_SERIES_UPPER)xx/Source/Templates/system_stm32$(MCU_SERIES)xx.o # Select the cross compile prefix CROSS_COMPILE ?= arm-none-eabi- INC += -I. INC += -I$(TOP) INC += -I$(BUILD) INC += -I$(TOP)/lib/cmsis/inc INC += -I$(CMSIS_DIR)/ INC += -I$(TOP)/$(HAL_DIR)/Inc INC += -I$(USBDEV_DIR)/core/inc -I$(USBDEV_DIR)/class/inc #INC += -I$(USBHOST_DIR) INC += -Ilwip_inc # Basic Cortex-M flags CFLAGS_CORTEX_M = -mthumb # Select hardware floating-point support SUPPORTS_HARDWARE_FP_SINGLE = 0 SUPPORTS_HARDWARE_FP_DOUBLE = 0 ifeq ($(CMSIS_MCU),$(filter $(CMSIS_MCU),STM32F765xx STM32F767xx STM32F769xx STM32H743xx)) CFLAGS_CORTEX_M += -mfpu=fpv5-d16 -mfloat-abi=hard SUPPORTS_HARDWARE_FP_SINGLE = 1 SUPPORTS_HARDWARE_FP_DOUBLE = 1 else ifeq ($(MCU_SERIES),$(filter $(MCU_SERIES),f0 l0)) CFLAGS_CORTEX_M += -msoft-float else CFLAGS_CORTEX_M += -mfpu=fpv4-sp-d16 -mfloat-abi=hard SUPPORTS_HARDWARE_FP_SINGLE = 1 endif endif # Options for particular MCU series CFLAGS_MCU_f0 = $(CFLAGS_CORTEX_M) -mtune=cortex-m0 -mcpu=cortex-m0 CFLAGS_MCU_f4 = $(CFLAGS_CORTEX_M) -mtune=cortex-m4 -mcpu=cortex-m4 CFLAGS_MCU_f7 = $(CFLAGS_CORTEX_M) -mtune=cortex-m7 -mcpu=cortex-m7 CFLAGS_MCU_l0 = $(CFLAGS_CORTEX_M) -mtune=cortex-m0plus -mcpu=cortex-m0plus CFLAGS_MCU_l4 = $(CFLAGS_CORTEX_M) -mtune=cortex-m4 -mcpu=cortex-m4 CFLAGS_MCU_h7 = $(CFLAGS_CORTEX_M) -mtune=cortex-m7 -mcpu=cortex-m7 CFLAGS_MCU_wb = $(CFLAGS_CORTEX_M) -mtune=cortex-m4 -mcpu=cortex-m4 CFLAGS += $(INC) -Wall -Wpointer-arith -Werror -Wdouble-promotion -Wfloat-conversion -std=gnu99 -nostdlib $(CFLAGS_MOD) $(CFLAGS_EXTRA) CFLAGS += -D$(CMSIS_MCU) CFLAGS += $(CFLAGS_MCU_$(MCU_SERIES)) CFLAGS += $(COPT) CFLAGS += -I$(BOARD_DIR) CFLAGS += -DSTM32_HAL_H='<stm32$(MCU_SERIES)xx_hal.h>' CFLAGS += -DMICROPY_HW_VTOR=$(TEXT0_ADDR) # Configure for nan-boxing object model if requested ifeq ($(NANBOX),1) CFLAGS += -DMP_CONFIGFILE='"mpconfigport_nanbox.h"' ifneq ($(MICROPY_FLOAT_IMPL),none) MICROPY_FLOAT_IMPL = double endif endif # Configure floating point support ifeq ($(MICROPY_FLOAT_IMPL),double) CFLAGS += -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_DOUBLE else ifeq ($(MICROPY_FLOAT_IMPL),none) CFLAGS += -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_NONE else CFLAGS += -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT CFLAGS += -fsingle-precision-constant endif endif LDFLAGS = -nostdlib -L $(LD_DIR) $(addprefix -T,$(LD_FILES)) -Map=$(@:.elf=.map) --cref LDFLAGS += --defsym=_estack_reserve=8 LIBS = "$(shell $(CC) $(CFLAGS) -print-libgcc-file-name)" # Remove uncalled code from the final image. CFLAGS += -fdata-sections -ffunction-sections LDFLAGS += --gc-sections # Debugging/Optimization ifeq ($(DEBUG), 1) CFLAGS += -g -DPENDSV_DEBUG COPT = -O0 else COPT += -Os -DNDEBUG endif # Options for mpy-cross MPY_CROSS_FLAGS += -march=armv7m LIB_SRC_C = $(addprefix lib/,\ libc/string0.c \ mp-readline/readline.c \ netutils/netutils.c \ netutils/trace.c \ netutils/dhcpserver.c \ timeutils/timeutils.c \ utils/gchelper_native.c \ utils/pyexec.c \ utils/interrupt_char.c \ utils/sys_stdio_mphal.c \ utils/mpirq.c \ ) ifeq ($(MICROPY_FLOAT_IMPL),double) LIBM_SRC_C = $(addprefix lib/libm_dbl/,\ __cos.c \ __expo2.c \ __fpclassify.c \ __rem_pio2.c \ __rem_pio2_large.c \ __signbit.c \ __sin.c \ __tan.c \ acos.c \ acosh.c \ asin.c \ asinh.c \ atan.c \ atan2.c \ atanh.c \ ceil.c \ cos.c \ cosh.c \ copysign.c \ erf.c \ exp.c \ expm1.c \ floor.c \ fmod.c \ frexp.c \ ldexp.c \ lgamma.c \ log.c \ log10.c \ log1p.c \ modf.c \ nearbyint.c \ pow.c \ rint.c \ round.c \ scalbn.c \ sin.c \ sinh.c \ tan.c \ tanh.c \ tgamma.c \ trunc.c \ ) ifeq ($(SUPPORTS_HARDWARE_FP_DOUBLE),1) LIBM_SRC_C += lib/libm_dbl/thumb_vfp_sqrt.c else LIBM_SRC_C += lib/libm_dbl/sqrt.c endif else LIBM_SRC_C = $(addprefix lib/libm/,\ math.c \ acoshf.c \ asinfacosf.c \ asinhf.c \ atan2f.c \ atanf.c \ atanhf.c \ ef_rem_pio2.c \ erf_lgamma.c \ fmodf.c \ kf_cos.c \ kf_rem_pio2.c \ kf_sin.c \ kf_tan.c \ log1pf.c \ nearbyintf.c \ roundf.c \ sf_cos.c \ sf_erf.c \ sf_frexp.c \ sf_ldexp.c \ sf_modf.c \ sf_sin.c \ sf_tan.c \ wf_lgamma.c \ wf_tgamma.c \ ) ifeq ($(SUPPORTS_HARDWARE_FP_SINGLE),1) LIBM_SRC_C += lib/libm/thumb_vfp_sqrtf.c else LIBM_SRC_C += lib/libm/ef_sqrt.c endif endif LIBM_O = $(addprefix $(BUILD)/, $(LIBM_SRC_C:.c=.o)) # Too many warnings in libm_dbl, disable for now. ifeq ($(MICROPY_FLOAT_IMPL),double) $(LIBM_O): CFLAGS := $(filter-out -Wdouble-promotion -Wfloat-conversion, $(CFLAGS)) endif EXTMOD_SRC_C = $(addprefix extmod/,\ modonewire.c \ ) DRIVERS_SRC_C = $(addprefix drivers/,\ bus/softspi.c \ bus/softqspi.c \ memory/spiflash.c \ dht/dht.c \ ) SRC_C = \ main.c \ stm32_it.c \ usbd_conf.c \ usbd_desc.c \ usbd_cdc_interface.c \ usbd_hid_interface.c \ usbd_msc_interface.c \ mphalport.c \ mpthreadport.c \ irq.c \ pendsv.c \ systick.c \ softtimer.c \ powerctrl.c \ powerctrlboot.c \ rfcore.c \ pybthread.c \ factoryreset.c \ timer.c \ led.c \ pin.c \ pin_defs_stm32.c \ pin_named_pins.c \ bufhelper.c \ dma.c \ i2c.c \ pyb_i2c.c \ spi.c \ pyb_spi.c \ qspi.c \ uart.c \ can.c \ fdcan.c \ pyb_can.c \ usb.c \ wdt.c \ eth.c \ gccollect.c \ help.c \ machine_adc.c \ machine_i2c.c \ machine_spi.c \ machine_timer.c \ machine_uart.c \ modmachine.c \ modpyb.c \ modstm.c \ moduos.c \ modutime.c \ modusocket.c \ network_lan.c \ modnetwork.c \ extint.c \ usrsw.c \ rng.c \ rtc.c \ flash.c \ flashbdev.c \ spibdev.c \ storage.c \ sdcard.c \ sdram.c \ fatfs_port.c \ lcd.c \ accel.c \ servo.c \ dac.c \ adc.c \ $(wildcard $(BOARD_DIR)/*.c) SRC_O = \ $(STARTUP_FILE) \ $(SYSTEM_FILE) ifeq ($(MCU_SERIES),f0) SRC_O += \ resethandler_m0.o \ lib/utils/gchelper_m0.o else ifeq ($(MCU_SERIES),l0) CSUPEROPT = -Os # save some code space SRC_O += \ resethandler_m0.o \ lib/utils/gchelper_m0.o else SRC_O += \ system_stm32.o \ resethandler.o \ lib/utils/gchelper_m3.o endif endif SRC_HAL = $(addprefix $(HAL_DIR)/Src/stm32$(MCU_SERIES)xx_,\ hal.c \ hal_adc.c \ hal_adc_ex.c \ hal_cortex.c \ hal_dma.c \ hal_flash.c \ hal_flash_ex.c \ hal_gpio.c \ hal_i2c.c \ hal_pcd.c \ hal_pcd_ex.c \ hal_pwr.c \ hal_pwr_ex.c \ hal_rcc.c \ hal_rcc_ex.c \ hal_rtc.c \ hal_rtc_ex.c \ hal_spi.c \ hal_tim.c \ hal_tim_ex.c \ hal_uart.c \ ) ifeq ($(MCU_SERIES),$(filter $(MCU_SERIES),f4 f7 h7 l0 l4 wb)) SRC_HAL += $(addprefix $(HAL_DIR)/Src/stm32$(MCU_SERIES)xx_,\ ll_usb.c \ ) endif ifeq ($(MCU_SERIES),$(filter $(MCU_SERIES),f4 f7 h7 l4)) SRC_HAL += $(addprefix $(HAL_DIR)/Src/stm32$(MCU_SERIES)xx_,\ hal_sd.c \ ll_sdmmc.c \ ll_fmc.c \ ) endif ifeq ($(MCU_SERIES),$(filter $(MCU_SERIES),f4 f7 h7)) SRC_HAL += $(addprefix $(HAL_DIR)/Src/stm32$(MCU_SERIES)xx_,\ hal_mmc.c \ hal_sdram.c \ hal_dma_ex.c \ hal_dcmi.c \ ) endif ifeq ($(CMSIS_MCU),$(filter $(CMSIS_MCU),STM32H743xx)) SRC_HAL += $(addprefix $(HAL_DIR)/Src/stm32$(MCU_SERIES)xx_, hal_fdcan.c) else ifeq ($(MCU_SERIES),$(filter $(MCU_SERIES),f0 f4 f7 h7 l4)) SRC_HAL += $(addprefix $(HAL_DIR)/Src/stm32$(MCU_SERIES)xx_, hal_can.c) endif endif SRC_USBDEV = $(addprefix $(USBDEV_DIR)/,\ core/src/usbd_core.c \ core/src/usbd_ctlreq.c \ core/src/usbd_ioreq.c \ class/src/usbd_cdc_msc_hid.c \ class/src/usbd_msc_bot.c \ class/src/usbd_msc_scsi.c \ ) ifeq ($(MICROPY_PY_BLUETOOTH),1) CFLAGS_MOD += -DMICROPY_PY_BLUETOOTH=1 CFLAGS_MOD += -DMICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE=1 CFLAGS_MOD += -DMICROPY_PY_BLUETOOTH_GATTS_ON_READ_CALLBACK=1 endif ifeq ($(MICROPY_PY_NETWORK_CYW43),1) CFLAGS_MOD += -DMICROPY_PY_NETWORK_CYW43=1 SRC_C += sdio.c EXTMOD_SRC_C += extmod/network_cyw43.c DRIVERS_SRC_C += drivers/cyw43/cyw43_ctrl.c drivers/cyw43/cyw43_lwip.c LIBS += $(TOP)/drivers/cyw43/libcyw43.a endif ifneq ($(MICROPY_PY_WIZNET5K),0) WIZNET5K_DIR=drivers/wiznet5k INC += -I$(TOP)/$(WIZNET5K_DIR) CFLAGS_MOD += -DMICROPY_PY_WIZNET5K=$(MICROPY_PY_WIZNET5K) -D_WIZCHIP_=$(MICROPY_PY_WIZNET5K) ifeq ($(MICROPY_PY_LWIP),1) # When using MACRAW mode (with lwIP), maximum buffer space must be used for the raw socket CFLAGS_MOD += -DWIZCHIP_USE_MAX_BUFFER endif SRC_MOD += network_wiznet5k.c modnwwiznet5k.c SRC_MOD += $(addprefix $(WIZNET5K_DIR)/,\ ethernet/w$(MICROPY_PY_WIZNET5K)/w$(MICROPY_PY_WIZNET5K).c \ ethernet/wizchip_conf.c \ ethernet/socket.c \ internet/dns/dns.c \ ) endif # for CC3000 module ifeq ($(MICROPY_PY_CC3K),1) CC3000_DIR=drivers/cc3000 INC += -I$(TOP)/$(CC3000_DIR)/inc CFLAGS_MOD += -DMICROPY_PY_CC3K=1 SRC_MOD += modnwcc3k.c SRC_MOD += $(addprefix $(CC3000_DIR)/src/,\ cc3000_common.c \ evnt_handler.c \ hci.c \ netapp.c \ nvmem.c \ security.c \ socket.c \ wlan.c \ ccspi.c \ inet_ntop.c \ inet_pton.c \ patch.c \ patch_prog.c \ ) endif ifeq ($(MICROPY_SSL_MBEDTLS),1) CFLAGS_MOD += -DMBEDTLS_CONFIG_FILE='"mbedtls/mbedtls_config.h"' SRC_MOD += mbedtls/mbedtls_port.c # replace mbedtls' error.c by ours SRC_MOD := $(filter-out %/mbedtls/library/error.c, $(SRC_MOD)) LIB_SRC_C += lib/mbedtls_errors/mp_mbedtls_errors.c endif ifeq ($(MICROPY_PY_BLUETOOTH),1) SRC_C += modbluetooth_hci.c ifeq ($(MICROPY_BLUETOOTH_NIMBLE),1) ifeq ($(MICROPY_BLUETOOTH_BTSTACK),1) $(error Cannot enable both NimBLE and BTstack at the same time) endif endif ifeq ($(MICROPY_BLUETOOTH_NIMBLE),1) include $(TOP)/extmod/nimble/nimble.mk SRC_C += nimble.c endif ifeq ($(MICROPY_BLUETOOTH_BTSTACK),1) include $(TOP)/extmod/btstack/btstack.mk SRC_C += btstack.c endif ifeq ($(MICROPY_PY_NETWORK_CYW43),1) DRIVERS_SRC_C += drivers/cyw43/cywbt.c endif endif OBJ = OBJ += $(PY_O) OBJ += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o)) OBJ += $(LIBM_O) OBJ += $(addprefix $(BUILD)/, $(EXTMOD_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(DRIVERS_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_O)) OBJ += $(addprefix $(BUILD)/, $(SRC_HAL:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_USBDEV:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) OBJ += $(BUILD)/pins_$(BOARD).o # This file contains performance critical functions so turn up the optimisation # level. It doesn't add much to the code size and improves performance a bit. # Don't use -O3 with this file because gcc tries to optimise memset in terms of itself. $(BUILD)/lib/libc/string0.o: COPT += -O2 # We put several files into the first 16K section with the ISRs. # If we compile these using -O0 then it won't fit. So if you really want these # to be compiled with -O0, then edit boards/common.ld (in the .isr_vector section) # and comment out the following lines. $(BUILD)/$(OOFATFS_DIR)/ff.o: COPT += -Os $(filter $(PY_BUILD)/../extmod/vfs_fat_%.o, $(PY_O)): COPT += -Os $(PY_BUILD)/formatfloat.o: COPT += -Os $(PY_BUILD)/parsenum.o: COPT += -Os $(PY_BUILD)/mpprint.o: COPT += -Os all: $(TOP)/lib/stm32lib/README.md $(BUILD)/firmware.dfu $(BUILD)/firmware.hex # For convenience, automatically fetch required submodules if they don't exist $(TOP)/lib/stm32lib/README.md: $(ECHO) "stm32lib submodule not found, fetching it now..." (cd $(TOP) && git submodule update --init lib/stm32lib) ifneq ($(FROZEN_MANIFEST)$(FROZEN_DIR),) # To use frozen source modules, put your .py files in a subdirectory (eg scripts/) # and then invoke make with FROZEN_DIR=scripts (be sure to build from scratch). CFLAGS += -DMICROPY_MODULE_FROZEN_STR endif ifneq ($(FROZEN_MANIFEST)$(FROZEN_MPY_DIR),) # To use frozen bytecode, put your .py files in a subdirectory (eg frozen/) and # then invoke make with FROZEN_MPY_DIR=frozen (be sure to build from scratch). CFLAGS += -DMICROPY_QSTR_EXTRA_POOL=mp_qstr_frozen_const_pool CFLAGS += -DMICROPY_MODULE_FROZEN_MPY endif .PHONY: deploy deploy: $(BUILD)/firmware.dfu $(ECHO) "Writing $< to the board" ifeq ($(USE_PYDFU),1) $(Q)$(PYTHON) $(PYDFU) --vid $(BOOTLOADER_DFU_USB_VID) --pid $(BOOTLOADER_DFU_USB_PID) -u $< else $(Q)$(DFU_UTIL) -a 0 -d $(BOOTLOADER_DFU_USB_VID):$(BOOTLOADER_DFU_USB_PID) -D $< endif # A board should specify TEXT0_ADDR if to use a different location than the # default for the firmware memory location. A board can also optionally define # TEXT1_ADDR to split the firmware into two sections; see below for details. TEXT0_ADDR ?= 0x08000000 ifeq ($(TEXT1_ADDR),) # No TEXT1_ADDR given so put all firmware at TEXT0_ADDR location TEXT0_SECTIONS ?= .isr_vector .text .data deploy-stlink: $(BUILD)/firmware.dfu $(ECHO) "Writing $(BUILD)/firmware.bin to the board via ST-LINK" $(Q)$(STFLASH) write $(BUILD)/firmware.bin $(TEXT0_ADDR) deploy-openocd: $(BUILD)/firmware.dfu $(ECHO) "Writing $(BUILD)/firmware.bin to the board via ST-LINK using OpenOCD" $(Q)$(OPENOCD) -f $(OPENOCD_CONFIG) -c "stm_flash $(BUILD)/firmware.bin $(TEXT0_ADDR)" $(BUILD)/firmware.dfu: $(BUILD)/firmware.elf $(ECHO) "Create $@" $(Q)$(OBJCOPY) -O binary $(addprefix -j ,$(TEXT0_SECTIONS)) $^ $(BUILD)/firmware.bin $(Q)$(PYTHON) $(DFU) -D $(BOOTLOADER_DFU_USB_VID):$(BOOTLOADER_DFU_USB_PID) -b $(TEXT0_ADDR):$(BUILD)/firmware.bin $@ else # TEXT0_ADDR and TEXT1_ADDR are specified so split firmware between these locations TEXT0_SECTIONS ?= .isr_vector TEXT1_SECTIONS ?= .text .data deploy-stlink: $(BUILD)/firmware.dfu $(ECHO) "Writing $(BUILD)/firmware0.bin to the board via ST-LINK" $(Q)$(STFLASH) write $(BUILD)/firmware0.bin $(TEXT0_ADDR) $(ECHO) "Writing $(BUILD)/firmware1.bin to the board via ST-LINK" $(Q)$(STFLASH) --reset write $(BUILD)/firmware1.bin $(TEXT1_ADDR) deploy-openocd: $(BUILD)/firmware.dfu $(ECHO) "Writing $(BUILD)/firmware{0,1}.bin to the board via ST-LINK using OpenOCD" $(Q)$(OPENOCD) -f $(OPENOCD_CONFIG) -c "stm_flash $(BUILD)/firmware0.bin $(TEXT0_ADDR) $(BUILD)/firmware1.bin $(TEXT1_ADDR)" $(BUILD)/firmware.dfu: $(BUILD)/firmware.elf $(ECHO) "GEN $@" $(Q)$(OBJCOPY) -O binary $(addprefix -j ,$(TEXT0_SECTIONS)) $^ $(BUILD)/firmware0.bin $(Q)$(OBJCOPY) -O binary $(addprefix -j ,$(TEXT1_SECTIONS)) $^ $(BUILD)/firmware1.bin $(Q)$(PYTHON) $(DFU) -D $(BOOTLOADER_DFU_USB_VID):$(BOOTLOADER_DFU_USB_PID) -b $(TEXT0_ADDR):$(BUILD)/firmware0.bin -b $(TEXT1_ADDR):$(BUILD)/firmware1.bin $@ endif $(BUILD)/firmware.hex: $(BUILD)/firmware.elf $(ECHO) "GEN $@" $(Q)$(OBJCOPY) -O ihex $< $@ $(BUILD)/firmware.elf: $(OBJ) $(ECHO) "LINK $@" $(Q)$(LD) $(LDFLAGS) -o $@ $^ $(LDFLAGS_MOD) $(LIBS) $(Q)$(SIZE) $@ ifneq ($(TEXT0_ADDR),0x08000000) $(ECHO) "INFO: this build requires mboot to be installed first" endif ifeq ($(TEXT1_ADDR),0x90000000) $(ECHO) "INFO: this build places firmware in external QSPI flash" endif PLLVALUES = boards/pllvalues.py MAKE_PINS = boards/make-pins.py BOARD_PINS = $(BOARD_DIR)/pins.csv PREFIX_FILE = boards/stm32f4xx_prefix.c GEN_PINS_SRC = $(BUILD)/pins_$(BOARD).c GEN_PINS_HDR = $(HEADER_BUILD)/pins.h GEN_PINS_QSTR = $(BUILD)/pins_qstr.h GEN_PINS_AF_CONST = $(HEADER_BUILD)/pins_af_const.h GEN_PINS_AF_DEFS = $(HEADER_BUILD)/pins_af_defs.h GEN_PINS_AF_PY = $(BUILD)/pins_af.py INSERT_USB_IDS = $(TOP)/tools/insert-usb-ids.py FILE2H = $(TOP)/tools/file2h.py USB_IDS_FILE = usb.h CDCINF_TEMPLATE = pybcdc.inf_template GEN_CDCINF_FILE = $(HEADER_BUILD)/pybcdc.inf GEN_CDCINF_HEADER = $(HEADER_BUILD)/pybcdc_inf.h # List of sources for qstr extraction SRC_QSTR += $(SRC_C) $(SRC_MOD) $(LIB_SRC_C) $(EXTMOD_SRC_C) # Append any auto-generated sources that are needed by sources listed in # SRC_QSTR SRC_QSTR_AUTO_DEPS += $(GEN_CDCINF_HEADER) # Making OBJ use an order-only depenedency on the generated pins.h file # has the side effect of making the pins.h file before we actually compile # any of the objects. The normal dependency generation will deal with the # case when pins.h is modified. But when it doesn't exist, we don't know # which source files might need it. $(OBJ): | $(GEN_PINS_HDR) # With conditional pins, we may need to regenerate qstrdefs.h when config # options change. $(HEADER_BUILD)/qstrdefs.generated.h: $(BOARD_DIR)/mpconfigboard.h # main.c can't be even preprocessed without $(GEN_CDCINF_HEADER) main.c: $(GEN_CDCINF_HEADER) # Use a pattern rule here so that make will only call make-pins.py once to make # both pins_$(BOARD).c and pins.h $(BUILD)/%_$(BOARD).c $(HEADER_BUILD)/%.h $(HEADER_BUILD)/%_af_const.h $(HEADER_BUILD)/%_af_defs.h $(BUILD)/%_qstr.h: $(BOARD_DIR)/%.csv $(MAKE_PINS) $(AF_FILE) $(PREFIX_FILE) | $(HEADER_BUILD) $(ECHO) "GEN $@" $(Q)$(PYTHON) $(MAKE_PINS) --board $(BOARD_PINS) --af $(AF_FILE) \ --prefix $(PREFIX_FILE) --hdr $(GEN_PINS_HDR) --hdr-obj-decls \ --qstr $(GEN_PINS_QSTR) --af-const $(GEN_PINS_AF_CONST) \ --af-defs $(GEN_PINS_AF_DEFS) --af-defs-cmp-strings \ --af-py $(GEN_PINS_AF_PY) > $(GEN_PINS_SRC) $(BUILD)/pins_$(BOARD).o: $(BUILD)/pins_$(BOARD).c $(call compile_c) GEN_PLLFREQTABLE_HDR = $(HEADER_BUILD)/pllfreqtable.h GEN_STMCONST_HDR = $(HEADER_BUILD)/modstm_const.h GEN_STMCONST_QSTR = $(BUILD)/modstm_qstr.h GEN_STMCONST_MPZ = $(HEADER_BUILD)/modstm_mpz.h CMSIS_MCU_HDR = $(CMSIS_DIR)/$(CMSIS_MCU_LOWER).h modmachine.c: $(GEN_PLLFREQTABLE_HDR) $(GEN_PLLFREQTABLE_HDR): $(PLLVALUES) | $(HEADER_BUILD) $(ECHO) "GEN $@" $(Q)$(PYTHON) $(PLLVALUES) -c -m $(MCU_SERIES) file:$(BOARD_DIR)/stm32$(MCU_SERIES)xx_hal_conf.h > $@ $(BUILD)/modstm.o: $(GEN_STMCONST_HDR) # Use a pattern rule here so that make will only call make-stmconst.py once to # make both modstm_const.h and modstm_qstr.h $(HEADER_BUILD)/%_const.h $(BUILD)/%_qstr.h: $(CMSIS_MCU_HDR) make-stmconst.py | $(HEADER_BUILD) $(ECHO) "GEN stmconst $@" $(Q)$(PYTHON) make-stmconst.py --qstr $(GEN_STMCONST_QSTR) --mpz $(GEN_STMCONST_MPZ) $(CMSIS_MCU_HDR) > $(GEN_STMCONST_HDR) $(GEN_CDCINF_HEADER): $(GEN_CDCINF_FILE) $(FILE2H) | $(HEADER_BUILD) $(ECHO) "GEN $@" $(Q)$(PYTHON) $(FILE2H) $< > $@ $(GEN_CDCINF_FILE): $(CDCINF_TEMPLATE) $(INSERT_USB_IDS) $(USB_IDS_FILE) | $(HEADER_BUILD) $(ECHO) "GEN $@" $(Q)$(PYTHON) $(INSERT_USB_IDS) $(USB_IDS_FILE) $< > $@ include $(TOP)/py/mkrules.mk
mit
alecharp/blog
content/post/2012/2012-05-30-maven-project-starter.md
1206
--- author: email: [email protected] name: Adrien Lecharpentier date: 2012-05-30T16:44:47Z tags: maven bash title: Maven project starter url: /2012/05/30/maven-project-starter/ --- Parfois commencer un project c'est long et embêtant car il faut commencer par créer la structure du project selon maven. Comment peut-on le faire rapidement? Aujourd'hui, on utilise beaucoup maven dans le développement, surtout web, mais commencer la phase de dev d'un projet peut être un peu long. Il faut toujours passer par la phase de création des dossiers conventionnés par maven et ce n'est pas toujours simple. Alors astuce : {{< highlight powershell >}} function create-maven-struct(){ local base=$1 [ "$base" == "" ] && base="." mkdir -p $base/src/{main,test}/{java,resources} } {{< / highlight >}} Ajoutez cette fonction dans votre `~/.bashrc` ou équivalent et vous serez en mesure de créer la structure d'un projet maven très simplement grâce à la fonction `create-maven-struct`. A noter que sans argument, la structure sera créée dans le dossier courant, et avec argument la structure sera créée à partir de l'argument (également créé s'il n'existe pas). Enjoy :)
mit
j-froehlich/magento2_wk
vendor/magento/module-tax/Controller/Adminhtml/Rule/Delete.php
1412
<?php /** * * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Tax\Controller\Adminhtml\Rule; use Magento\Framework\Controller\ResultFactory; class Delete extends \Magento\Tax\Controller\Adminhtml\Rule { /** * @return \Magento\Backend\Model\View\Result\Redirect */ public function execute() { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $ruleId = (int)$this->getRequest()->getParam('rule'); try { $this->ruleService->deleteById($ruleId); $this->messageManager->addSuccess(__('The tax rule has been deleted.')); return $resultRedirect->setPath('tax/*/'); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $this->messageManager->addError(__('This rule no longer exists.')); return $resultRedirect->setPath('tax/*/'); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong deleting this tax rule.')); } return $resultRedirect->setUrl($this->_redirect->getRedirectUrl($this->getUrl('*'))); } }
mit
reyno-uk/ApplicationInsights-JS
JavaScript/JavaScriptSDK/Init.ts
1610
/// <reference path="initialization.ts" /> function initializeAppInsights() { try { // only initialize if we are running in a browser that supports JSON serialization (ie7<, node.js, cordova) if (typeof window !== "undefined" && typeof JSON !== "undefined") { // get snippet or initialize to an empty object var aiName = "appInsights"; if (window[aiName] === undefined) { // if no snippet is present, initialize default values Microsoft.ApplicationInsights.AppInsights.defaultConfig = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(); } else { // this is the typical case for browser+snippet var snippet: Microsoft.ApplicationInsights.Snippet = window[aiName] || <any>{}; // overwrite snippet with full appInsights var init = new Microsoft.ApplicationInsights.Initialization(snippet); var appInsightsLocal = init.loadAppInsights(); // apply full appInsights to the global instance that was initialized in the snippet for (var field in appInsightsLocal) { snippet[field] = appInsightsLocal[field]; } init.emptyQueue(); init.pollInteralLogs(appInsightsLocal); init.addHousekeepingBeforeUnload(appInsightsLocal); } } } catch (e) { console.error('Failed to initialize AppInsights JS SDK: ' + e.message); } } initializeAppInsights();
mit
AzureZhao/android-developer-cn
reference/android/view/Choreographer.html
80094
<!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>Choreographer - Android SDK | 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"> <!-- FULLSCREEN STYLESHEET --> <link href="../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen" 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" itemscope itemtype="http://schema.org/Article"> <div id="doc-api-level" class="16" style="display:none"></div> <a name="top"></a> <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"> <a class="totop" href="#top" data-g-event="left-nav-top">to top</a> <div id="api-nav-header"> <div id="api-level-toggle"> <label for="apiLevelCheckbox" class="disabled">API level: </label> <div class="select-wrapper"> <select id="apiLevelSelector"> <!-- option elements added by buildApiLevelSelector() --> </select> </div> </div><!-- end toggle --> <div id="api-nav-title">Android APIs</div> </div><!-- end nav header --> <script> var SINCE_DATA = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19' ]; buildApiLevelSelector(); </script> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav" class="scroll-pane"> <ul> <li class="api apilevel-1"> <a href="../../../reference/android/package-summary.html">android</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/accessibilityservice/package-summary.html">android.accessibilityservice</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/accounts/package-summary.html">android.accounts</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/animation/package-summary.html">android.animation</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/app/package-summary.html">android.app</a></li> <li class="api apilevel-8"> <a href="../../../reference/android/app/admin/package-summary.html">android.app.admin</a></li> <li class="api apilevel-8"> <a href="../../../reference/android/app/backup/package-summary.html">android.app.backup</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/appwidget/package-summary.html">android.appwidget</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/bluetooth/package-summary.html">android.bluetooth</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/package-summary.html">android.content</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/pm/package-summary.html">android.content.pm</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/content/res/package-summary.html">android.content.res</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/database/package-summary.html">android.database</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/database/sqlite/package-summary.html">android.database.sqlite</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/drm/package-summary.html">android.drm</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/gesture/package-summary.html">android.gesture</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/package-summary.html">android.graphics</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/drawable/package-summary.html">android.graphics.drawable</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/graphics/drawable/shapes/package-summary.html">android.graphics.drawable.shapes</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/graphics/pdf/package-summary.html">android.graphics.pdf</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/hardware/package-summary.html">android.hardware</a></li> <li class="api apilevel-17"> <a href="../../../reference/android/hardware/display/package-summary.html">android.hardware.display</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/hardware/input/package-summary.html">android.hardware.input</a></li> <li class="api apilevel-18"> <a href="../../../reference/android/hardware/location/package-summary.html">android.hardware.location</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/hardware/usb/package-summary.html">android.hardware.usb</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/inputmethodservice/package-summary.html">android.inputmethodservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/location/package-summary.html">android.location</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/media/package-summary.html">android.media</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/media/audiofx/package-summary.html">android.media.audiofx</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/media/effect/package-summary.html">android.media.effect</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/mtp/package-summary.html">android.mtp</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/package-summary.html">android.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/http/package-summary.html">android.net.http</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/net/nsd/package-summary.html">android.net.nsd</a></li> <li class="api apilevel-12"> <a href="../../../reference/android/net/rtp/package-summary.html">android.net.rtp</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/net/sip/package-summary.html">android.net.sip</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/net/wifi/package-summary.html">android.net.wifi</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/net/wifi/p2p/package-summary.html">android.net.wifi.p2p</a></li> <li class="api apilevel-16"> <a href="../../../reference/android/net/wifi/p2p/nsd/package-summary.html">android.net.wifi.p2p.nsd</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/nfc/package-summary.html">android.nfc</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/nfc/cardemulation/package-summary.html">android.nfc.cardemulation</a></li> <li class="api apilevel-10"> <a href="../../../reference/android/nfc/tech/package-summary.html">android.nfc.tech</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/opengl/package-summary.html">android.opengl</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/os/package-summary.html">android.os</a></li> <li class="api apilevel-9"> <a href="../../../reference/android/os/storage/package-summary.html">android.os.storage</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/preference/package-summary.html">android.preference</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/print/package-summary.html">android.print</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/print/pdf/package-summary.html">android.print.pdf</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/printservice/package-summary.html">android.printservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/provider/package-summary.html">android.provider</a></li> <li class="api apilevel-11"> <a href="../../../reference/android/renderscript/package-summary.html">android.renderscript</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/sax/package-summary.html">android.sax</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/security/package-summary.html">android.security</a></li> <li class="api apilevel-17"> <a href="../../../reference/android/service/dreams/package-summary.html">android.service.dreams</a></li> <li class="api apilevel-18"> <a href="../../../reference/android/service/notification/package-summary.html">android.service.notification</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/service/textservice/package-summary.html">android.service.textservice</a></li> <li class="api apilevel-7"> <a href="../../../reference/android/service/wallpaper/package-summary.html">android.service.wallpaper</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/speech/package-summary.html">android.speech</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/speech/tts/package-summary.html">android.speech.tts</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v13/app/package-summary.html">android.support.v13.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/accessibilityservice/package-summary.html">android.support.v4.accessibilityservice</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/app/package-summary.html">android.support.v4.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/package-summary.html">android.support.v4.content</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/content/pm/package-summary.html">android.support.v4.content.pm</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/database/package-summary.html">android.support.v4.database</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/graphics/drawable/package-summary.html">android.support.v4.graphics.drawable</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/hardware/display/package-summary.html">android.support.v4.hardware.display</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/media/package-summary.html">android.support.v4.media</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/net/package-summary.html">android.support.v4.net</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/os/package-summary.html">android.support.v4.os</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/print/package-summary.html">android.support.v4.print</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/text/package-summary.html">android.support.v4.text</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/util/package-summary.html">android.support.v4.util</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/package-summary.html">android.support.v4.view</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/view/accessibility/package-summary.html">android.support.v4.view.accessibility</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v4/widget/package-summary.html">android.support.v4.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/app/package-summary.html">android.support.v7.app</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/appcompat/package-summary.html">android.support.v7.appcompat</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/gridlayout/package-summary.html">android.support.v7.gridlayout</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/media/package-summary.html">android.support.v7.media</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/mediarouter/package-summary.html">android.support.v7.mediarouter</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/view/package-summary.html">android.support.v7.view</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v7/widget/package-summary.html">android.support.v7.widget</a></li> <li class="api apilevel-"> <a href="../../../reference/android/support/v8/renderscript/package-summary.html">android.support.v8.renderscript</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/telephony/package-summary.html">android.telephony</a></li> <li class="api apilevel-5"> <a href="../../../reference/android/telephony/cdma/package-summary.html">android.telephony.cdma</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/telephony/gsm/package-summary.html">android.telephony.gsm</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/package-summary.html">android.test</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/mock/package-summary.html">android.test.mock</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/test/suitebuilder/package-summary.html">android.test.suitebuilder</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/package-summary.html">android.text</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/text/format/package-summary.html">android.text.format</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/method/package-summary.html">android.text.method</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/style/package-summary.html">android.text.style</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/text/util/package-summary.html">android.text.util</a></li> <li class="api apilevel-19"> <a href="../../../reference/android/transition/package-summary.html">android.transition</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/util/package-summary.html">android.util</a></li> <li class="selected api apilevel-1"> <a href="../../../reference/android/view/package-summary.html">android.view</a></li> <li class="api apilevel-4"> <a href="../../../reference/android/view/accessibility/package-summary.html">android.view.accessibility</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/view/animation/package-summary.html">android.view.animation</a></li> <li class="api apilevel-3"> <a href="../../../reference/android/view/inputmethod/package-summary.html">android.view.inputmethod</a></li> <li class="api apilevel-14"> <a href="../../../reference/android/view/textservice/package-summary.html">android.view.textservice</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/webkit/package-summary.html">android.webkit</a></li> <li class="api apilevel-1"> <a href="../../../reference/android/widget/package-summary.html">android.widget</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/bytecode/package-summary.html">dalvik.bytecode</a></li> <li class="api apilevel-1"> <a href="../../../reference/dalvik/system/package-summary.html">dalvik.system</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/awt/font/package-summary.html">java.awt.font</a></li> <li class="api apilevel-3"> <a href="../../../reference/java/beans/package-summary.html">java.beans</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/io/package-summary.html">java.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/package-summary.html">java.lang</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/annotation/package-summary.html">java.lang.annotation</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/ref/package-summary.html">java.lang.ref</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/lang/reflect/package-summary.html">java.lang.reflect</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/math/package-summary.html">java.math</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/net/package-summary.html">java.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/package-summary.html">java.nio</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/channels/package-summary.html">java.nio.channels</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/channels/spi/package-summary.html">java.nio.channels.spi</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/charset/package-summary.html">java.nio.charset</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/nio/charset/spi/package-summary.html">java.nio.charset.spi</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/package-summary.html">java.security</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/acl/package-summary.html">java.security.acl</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/cert/package-summary.html">java.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/interfaces/package-summary.html">java.security.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/security/spec/package-summary.html">java.security.spec</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/sql/package-summary.html">java.sql</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/text/package-summary.html">java.text</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/package-summary.html">java.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/package-summary.html">java.util.concurrent</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/jar/package-summary.html">java.util.jar</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/logging/package-summary.html">java.util.logging</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/prefs/package-summary.html">java.util.prefs</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/regex/package-summary.html">java.util.regex</a></li> <li class="api apilevel-1"> <a href="../../../reference/java/util/zip/package-summary.html">java.util.zip</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/package-summary.html">javax.crypto</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/interfaces/package-summary.html">javax.crypto.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/crypto/spec/package-summary.html">javax.crypto.spec</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/microedition/khronos/egl/package-summary.html">javax.microedition.khronos.egl</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/microedition/khronos/opengles/package-summary.html">javax.microedition.khronos.opengles</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/net/package-summary.html">javax.net</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/net/ssl/package-summary.html">javax.net.ssl</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/package-summary.html">javax.security.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/callback/package-summary.html">javax.security.auth.callback</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/login/package-summary.html">javax.security.auth.login</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/auth/x500/package-summary.html">javax.security.auth.x500</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/security/cert/package-summary.html">javax.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/sql/package-summary.html">javax.sql</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/xml/package-summary.html">javax.xml</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/datatype/package-summary.html">javax.xml.datatype</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/namespace/package-summary.html">javax.xml.namespace</a></li> <li class="api apilevel-1"> <a href="../../../reference/javax/xml/parsers/package-summary.html">javax.xml.parsers</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/package-summary.html">javax.xml.transform</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/dom/package-summary.html">javax.xml.transform.dom</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/sax/package-summary.html">javax.xml.transform.sax</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/transform/stream/package-summary.html">javax.xml.transform.stream</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/validation/package-summary.html">javax.xml.validation</a></li> <li class="api apilevel-8"> <a href="../../../reference/javax/xml/xpath/package-summary.html">javax.xml.xpath</a></li> <li class="api apilevel-1"> <a href="../../../reference/junit/framework/package-summary.html">junit.framework</a></li> <li class="api apilevel-1"> <a href="../../../reference/junit/runner/package-summary.html">junit.runner</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/package-summary.html">org.apache.http</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/auth/package-summary.html">org.apache.http.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/auth/params/package-summary.html">org.apache.http.auth.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/package-summary.html">org.apache.http.client</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/entity/package-summary.html">org.apache.http.client.entity</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/methods/package-summary.html">org.apache.http.client.methods</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/params/package-summary.html">org.apache.http.client.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/protocol/package-summary.html">org.apache.http.client.protocol</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/client/utils/package-summary.html">org.apache.http.client.utils</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/package-summary.html">org.apache.http.conn</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/params/package-summary.html">org.apache.http.conn.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/routing/package-summary.html">org.apache.http.conn.routing</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/scheme/package-summary.html">org.apache.http.conn.scheme</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/ssl/package-summary.html">org.apache.http.conn.ssl</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/conn/util/package-summary.html">org.apache.http.conn.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/cookie/package-summary.html">org.apache.http.cookie</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/cookie/params/package-summary.html">org.apache.http.cookie.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/entity/package-summary.html">org.apache.http.entity</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/package-summary.html">org.apache.http.impl</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/auth/package-summary.html">org.apache.http.impl.auth</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/client/package-summary.html">org.apache.http.impl.client</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/conn/package-summary.html">org.apache.http.impl.conn</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/cookie/package-summary.html">org.apache.http.impl.cookie</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/entity/package-summary.html">org.apache.http.impl.entity</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/impl/io/package-summary.html">org.apache.http.impl.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/io/package-summary.html">org.apache.http.io</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/message/package-summary.html">org.apache.http.message</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/params/package-summary.html">org.apache.http.params</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/protocol/package-summary.html">org.apache.http.protocol</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/apache/http/util/package-summary.html">org.apache.http.util</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/json/package-summary.html">org.json</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/w3c/dom/package-summary.html">org.w3c.dom</a></li> <li class="api apilevel-8"> <a href="../../../reference/org/w3c/dom/ls/package-summary.html">org.w3c.dom.ls</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/package-summary.html">org.xml.sax</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/ext/package-summary.html">org.xml.sax.ext</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xmlpull/v1/package-summary.html">org.xmlpull.v1</a></li> <li class="api apilevel-1"> <a href="../../../reference/org/xmlpull/v1/sax2/package-summary.html">org.xmlpull.v1.sax2</a></li> </ul><br/> </div> <!-- end packages-nav --> </div> <!-- end resize-packages --> <div id="classes-nav" class="scroll-pane"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-11"><a href="../../../reference/android/view/ActionMode.Callback.html">ActionMode.Callback</a></li> <li class="api apilevel-16"><a href="../../../reference/android/view/ActionProvider.VisibilityListener.html">ActionProvider.VisibilityListener</a></li> <li class="api apilevel-16"><a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/CollapsibleActionView.html">CollapsibleActionView</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ContextMenu.html">ContextMenu</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ContextMenu.ContextMenuInfo.html">ContextMenu.ContextMenuInfo</a></li> <li class="api apilevel-3"><a href="../../../reference/android/view/GestureDetector.OnDoubleTapListener.html">GestureDetector.OnDoubleTapListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/GestureDetector.OnGestureListener.html">GestureDetector.OnGestureListener</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/InputQueue.Callback.html">InputQueue.Callback</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/KeyEvent.Callback.html">KeyEvent.Callback</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/LayoutInflater.Factory.html">LayoutInflater.Factory</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/LayoutInflater.Factory2.html">LayoutInflater.Factory2</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/LayoutInflater.Filter.html">LayoutInflater.Filter</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Menu.html">Menu</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/MenuItem.html">MenuItem</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/MenuItem.OnActionExpandListener.html">MenuItem.OnActionExpandListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/MenuItem.OnMenuItemClickListener.html">MenuItem.OnMenuItemClickListener</a></li> <li class="api apilevel-8"><a href="../../../reference/android/view/ScaleGestureDetector.OnScaleGestureListener.html">ScaleGestureDetector.OnScaleGestureListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/SubMenu.html">SubMenu</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/SurfaceHolder.html">SurfaceHolder</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/SurfaceHolder.Callback.html">SurfaceHolder.Callback</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/SurfaceHolder.Callback2.html">SurfaceHolder.Callback2</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/TextureView.SurfaceTextureListener.html">TextureView.SurfaceTextureListener</a></li> <li class="api apilevel-12"><a href="../../../reference/android/view/View.OnAttachStateChangeListener.html">View.OnAttachStateChangeListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.OnClickListener.html">View.OnClickListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.OnCreateContextMenuListener.html">View.OnCreateContextMenuListener</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/View.OnDragListener.html">View.OnDragListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.OnFocusChangeListener.html">View.OnFocusChangeListener</a></li> <li class="api apilevel-12"><a href="../../../reference/android/view/View.OnGenericMotionListener.html">View.OnGenericMotionListener</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/View.OnHoverListener.html">View.OnHoverListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.OnKeyListener.html">View.OnKeyListener</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/View.OnLayoutChangeListener.html">View.OnLayoutChangeListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.OnLongClickListener.html">View.OnLongClickListener</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/View.OnSystemUiVisibilityChangeListener.html">View.OnSystemUiVisibilityChangeListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.OnTouchListener.html">View.OnTouchListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewGroup.OnHierarchyChangeListener.html">ViewGroup.OnHierarchyChangeListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewManager.html">ViewManager</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewParent.html">ViewParent</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewStub.OnInflateListener.html">ViewStub.OnInflateListener</a></li> <li class="api apilevel-16"><a href="../../../reference/android/view/ViewTreeObserver.OnDrawListener.html">ViewTreeObserver.OnDrawListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewTreeObserver.OnGlobalFocusChangeListener.html">ViewTreeObserver.OnGlobalFocusChangeListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html">ViewTreeObserver.OnGlobalLayoutListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewTreeObserver.OnPreDrawListener.html">ViewTreeObserver.OnPreDrawListener</a></li> <li class="api apilevel-3"><a href="../../../reference/android/view/ViewTreeObserver.OnScrollChangedListener.html">ViewTreeObserver.OnScrollChangedListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewTreeObserver.OnTouchModeChangeListener.html">ViewTreeObserver.OnTouchModeChangeListener</a></li> <li class="api apilevel-18"><a href="../../../reference/android/view/ViewTreeObserver.OnWindowAttachListener.html">ViewTreeObserver.OnWindowAttachListener</a></li> <li class="api apilevel-18"><a href="../../../reference/android/view/ViewTreeObserver.OnWindowFocusChangeListener.html">ViewTreeObserver.OnWindowFocusChangeListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Window.Callback.html">Window.Callback</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/WindowManager.html">WindowManager</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-1"><a href="../../../reference/android/view/AbsSavedState.html">AbsSavedState</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/ActionMode.html">ActionMode</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/ActionProvider.html">ActionProvider</a></li> <li class="selected api apilevel-16"><a href="../../../reference/android/view/Choreographer.html">Choreographer</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ContextThemeWrapper.html">ContextThemeWrapper</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Display.html">Display</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/DragEvent.html">DragEvent</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/FocusFinder.html">FocusFinder</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/GestureDetector.html">GestureDetector</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/GestureDetector.SimpleOnGestureListener.html">GestureDetector.SimpleOnGestureListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Gravity.html">Gravity</a></li> <li class="api apilevel-3"><a href="../../../reference/android/view/HapticFeedbackConstants.html">HapticFeedbackConstants</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/InputDevice.html">InputDevice</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/InputDevice.MotionRange.html">InputDevice.MotionRange</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/InputEvent.html">InputEvent</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/InputQueue.html">InputQueue</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/KeyCharacterMap.html">KeyCharacterMap</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/KeyCharacterMap.KeyData.html">KeyCharacterMap.KeyData</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/KeyEvent.html">KeyEvent</a></li> <li class="api apilevel-5"><a href="../../../reference/android/view/KeyEvent.DispatcherState.html">KeyEvent.DispatcherState</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/LayoutInflater.html">LayoutInflater</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/MenuInflater.html">MenuInflater</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/MotionEvent.html">MotionEvent</a></li> <li class="api apilevel-9"><a href="../../../reference/android/view/MotionEvent.PointerCoords.html">MotionEvent.PointerCoords</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/MotionEvent.PointerProperties.html">MotionEvent.PointerProperties</a></li> <li class="api apilevel-3"><a href="../../../reference/android/view/OrientationEventListener.html">OrientationEventListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/OrientationListener.html">OrientationListener</a></li> <li class="api apilevel-8"><a href="../../../reference/android/view/ScaleGestureDetector.html">ScaleGestureDetector</a></li> <li class="api apilevel-8"><a href="../../../reference/android/view/ScaleGestureDetector.SimpleOnScaleGestureListener.html">ScaleGestureDetector.SimpleOnScaleGestureListener</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/SoundEffectConstants.html">SoundEffectConstants</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Surface.html">Surface</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/SurfaceView.html">SurfaceView</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/TextureView.html">TextureView</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/TouchDelegate.html">TouchDelegate</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/VelocityTracker.html">VelocityTracker</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.html">View</a></li> <li class="api apilevel-14"><a href="../../../reference/android/view/View.AccessibilityDelegate.html">View.AccessibilityDelegate</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.BaseSavedState.html">View.BaseSavedState</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/View.DragShadowBuilder.html">View.DragShadowBuilder</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/View.MeasureSpec.html">View.MeasureSpec</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewConfiguration.html">ViewConfiguration</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewDebug.html">ViewDebug</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewGroup.LayoutParams.html">ViewGroup.LayoutParams</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewGroup.MarginLayoutParams.html">ViewGroup.MarginLayoutParams</a></li> <li class="api apilevel-18"><a href="../../../reference/android/view/ViewGroupOverlay.html">ViewGroupOverlay</a></li> <li class="api apilevel-18"><a href="../../../reference/android/view/ViewOverlay.html">ViewOverlay</a></li> <li class="api apilevel-12"><a href="../../../reference/android/view/ViewPropertyAnimator.html">ViewPropertyAnimator</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewStub.html">ViewStub</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewTreeObserver.html">ViewTreeObserver</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Window.html">Window</a></li> <li class="api apilevel-18"><a href="../../../reference/android/view/WindowId.html">WindowId</a></li> <li class="api apilevel-18"><a href="../../../reference/android/view/WindowId.FocusObserver.html">WindowId.FocusObserver</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/WindowManager.LayoutParams.html">WindowManager.LayoutParams</a></li> </ul> </li> <li><h2>Enums</h2> <ul> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewDebug.HierarchyTraceType.html">ViewDebug.HierarchyTraceType</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/ViewDebug.RecyclerTraceType.html">ViewDebug.RecyclerTraceType</a></li> </ul> </li> <li><h2>Exceptions</h2> <ul> <li class="api apilevel-1"><a href="../../../reference/android/view/InflateException.html">InflateException</a></li> <li class="api apilevel-11"><a href="../../../reference/android/view/KeyCharacterMap.UnavailableException.html">KeyCharacterMap.UnavailableException</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/Surface.OutOfResourcesException.html">Surface.OutOfResourcesException</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/SurfaceHolder.BadSurfaceTypeException.html">SurfaceHolder.BadSurfaceTypeException</a></li> <li class="api apilevel-1"><a href="../../../reference/android/view/WindowManager.BadTokenException.html">WindowManager.BadTokenException</a></li> <li class="api apilevel-17"><a href="../../../reference/android/view/WindowManager.InvalidDisplayException.html">WindowManager.InvalidDisplayException</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none" class="scroll-pane"> <div id="tree-list"></div> </div><!-- end nav-tree --> </div><!-- end swapper --> <div id="nav-swap"> <a class="fullscreen">fullscreen</a> <a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a> </div> </div> <!-- end devdoc-nav --> </div> <!-- end side-nav --> <script type="text/javascript"> // init fullscreen based on user pref var fullscreen = readCookie("fullscreen"); if (fullscreen != 0) { if (fullscreen == "false") { toggleFullscreen(false); } else { toggleFullscreen(true); } } // init nav version for mobile if (isMobile) { swapNav(); // tree view should be used on mobile $('#nav-swap').hide(); } else { chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../"); } } // scroll the selected page into view $(document).ready(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); </script> <div class="col-12" id="doc-col"> <div id="api-info-block"> <div class="sum-details-links"> Summary: <a href="#nestedclasses">Nested Classes</a> &#124; <a href="#pubmethods">Methods</a> &#124; <a href="#inhmethods">Inherited Methods</a> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> </div><!-- end sum-details-links --> <div class="api-level"> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 16</a> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public final class <h1 itemprop="name">Choreographer</h1> extends <a href="../../../reference/java/lang/Object.html">Object</a><br/> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-16"> <table class="jd-inheritance-table"> <tr> <td colspan="2" class="jd-inheritance-class-cell"><a href="../../../reference/java/lang/Object.html">java.lang.Object</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="1" class="jd-inheritance-class-cell">android.view.Choreographer</td> </tr> </table> <div class="jd-descr"> <h2>Class Overview</h2> <p itemprop="articleBody">Coordinates the timing of animations, input and drawing. <p> The choreographer receives timing pulses (such as vertical synchronization) from the display subsystem then schedules work to occur as part of rendering the next display frame. </p><p> Applications typically interact with the choreographer indirectly using higher level abstractions in the animation framework or the view hierarchy. Here are some examples of things you can do using the higher-level APIs. </p> <ul> <li>To post an animation to be processed on a regular time basis synchronized with display frame rendering, use <code><a href="../../../reference/android/animation/ValueAnimator.html#start()">start()</a></code>.</li> <li>To post a <code><a href="../../../reference/java/lang/Runnable.html">Runnable</a></code> to be invoked once at the beginning of the next display frame, use <code><a href="../../../reference/android/view/View.html#postOnAnimation(java.lang.Runnable)">postOnAnimation(Runnable)</a></code>.</li> <li>To post a <code><a href="../../../reference/java/lang/Runnable.html">Runnable</a></code> to be invoked once at the beginning of the next display frame after a delay, use <code><a href="../../../reference/android/view/View.html#postOnAnimationDelayed(java.lang.Runnable, long)">postOnAnimationDelayed(Runnable, long)</a></code>.</li> <li>To post a call to <code><a href="../../../reference/android/view/View.html#invalidate()">invalidate()</a></code> to occur once at the beginning of the next display frame, use <code><a href="../../../reference/android/view/View.html#postInvalidateOnAnimation()">postInvalidateOnAnimation()</a></code> or <code><a href="../../../reference/android/view/View.html#postInvalidateOnAnimation(int, int, int, int)">postInvalidateOnAnimation(int, int, int, int)</a></code>.</li> <li>To ensure that the contents of a <code><a href="../../../reference/android/view/View.html">View</a></code> scroll smoothly and are drawn in sync with display frame rendering, do nothing. This already happens automatically. <code><a href="../../../reference/android/view/View.html#onDraw(android.graphics.Canvas)">onDraw(Canvas)</a></code> will be called at the appropriate time.</li> </ul> <p> However, there are a few cases where you might want to use the functions of the choreographer directly in your application. Here are some examples. </p> <ul> <li>If your application does its rendering in a different thread, possibly using GL, or does not use the animation framework or view hierarchy at all and you want to ensure that it is appropriately synchronized with the display, then use <code><a href="../../../reference/android/view/Choreographer.html#postFrameCallback(android.view.Choreographer.FrameCallback)">postFrameCallback(Choreographer.FrameCallback)</a></code>.</li> <li>... and that's about it.</li> </ul> <p> Each <code><a href="../../../reference/android/os/Looper.html">Looper</a></code> thread has its own choreographer. Other threads can post callbacks to run on the choreographer but they will run on the <code><a href="../../../reference/android/os/Looper.html">Looper</a></code> to which the choreographer belongs. </p> </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- ======== NESTED CLASS SUMMARY ======== --> <table id="nestedclasses" class="jd-sumtable"><tr><th colspan="12">Nested Classes</th></tr> <tr class="alt-color api apilevel-16" > <td class="jd-typecol"><nobr> interface</nobr></td> <td class="jd-linkcol"><a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a></td> <td class="jd-descrcol" width="100%">Implement this interface to receive a callback when a new display frame is being rendered.&nbsp;</td> </tr> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <tr class="alt-color api apilevel-16" > <td class="jd-typecol"><nobr> static <a href="../../../reference/android/view/Choreographer.html">Choreographer</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/view/Choreographer.html#getInstance()">getInstance</a></span>()</nobr> <div class="jd-descrdiv">Gets the choreographer for the calling thread.</div> </td></tr> <tr class=" api apilevel-16" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/view/Choreographer.html#postFrameCallback(android.view.Choreographer.FrameCallback)">postFrameCallback</a></span>(<a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a> callback)</nobr> <div class="jd-descrdiv">Posts a frame callback to run on the next frame.</div> </td></tr> <tr class="alt-color api apilevel-16" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/view/Choreographer.html#postFrameCallbackDelayed(android.view.Choreographer.FrameCallback, long)">postFrameCallbackDelayed</a></span>(<a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a> callback, long delayMillis)</nobr> <div class="jd-descrdiv">Posts a frame callback to run on the next frame after the specified delay.</div> </td></tr> <tr class=" api apilevel-16" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/android/view/Choreographer.html#removeFrameCallback(android.view.Choreographer.FrameCallback)">removeFrameCallback</a></span>(<a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a> callback)</nobr> <div class="jd-descrdiv">Removes a previously posted frame callback.</div> </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Object-trigger" src="../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From class <a href="../../../reference/java/lang/Object.html">java.lang.Object</a> <div id="inherited-methods-java.lang.Object"> <div id="inherited-methods-java.lang.Object-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Object-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/Object.html">Object</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#clone()">clone</a></span>()</nobr> <div class="jd-descrdiv">Creates and returns a copy of this <code>Object</code>.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> boolean</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../reference/java/lang/Object.html">Object</a> o)</nobr> <div class="jd-descrdiv">Compares this instance with the specified object and indicates if they are equal.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#finalize()">finalize</a></span>()</nobr> <div class="jd-descrdiv">Invoked when the garbage collector has detected that this instance is no longer reachable.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final <a href="../../../reference/java/lang/Class.html">Class</a>&lt;?&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#getClass()">getClass</a></span>()</nobr> <div class="jd-descrdiv">Returns the unique instance of <code><a href="../../../reference/java/lang/Class.html">Class</a></code> that represents this object's class.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#hashCode()">hashCode</a></span>()</nobr> <div class="jd-descrdiv">Returns an integer hash code for this object.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#notify()">notify</a></span>()</nobr> <div class="jd-descrdiv">Causes a thread which is waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#notifyAll()">notifyAll</a></span>()</nobr> <div class="jd-descrdiv">Causes all threads which are waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this object.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait()">wait</a></span>()</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long, int)">wait</a></span>(long millis, int nanos)</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../reference/java/lang/Object.html#wait(long)">wait</a></span>(long millis)</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires.</div> </td></tr> </table> </div> </div> </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- Fields --> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <h2>Public Methods</h2> <A NAME="getInstance()"></A> <div class="jd-details api apilevel-16"> <h4 class="jd-details-title"> <span class="normal"> public static <a href="../../../reference/android/view/Choreographer.html">Choreographer</a> </span> <span class="sympad">getInstance</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 16</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Gets the choreographer for the calling thread. Must be called from a thread that already has a <code><a href="../../../reference/android/os/Looper.html">Looper</a></code> associated with it.</p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Returns</h5> <ul class="nolist"><li>The choreographer for this thread.</li></ul> </div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Throws</h5> <table class="jd-tagtable"> <tr> <th><a href="../../../reference/java/lang/IllegalStateException.html">IllegalStateException</a></td> <td>if the thread does not have a looper. </td> </tr> </table> </div> </div> </div> <A NAME="postFrameCallback(android.view.Choreographer.FrameCallback)"></A> <div class="jd-details api apilevel-16"> <h4 class="jd-details-title"> <span class="normal"> public void </span> <span class="sympad">postFrameCallback</span> <span class="normal">(<a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a> callback)</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 16</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Posts a frame callback to run on the next frame. <p> The callback runs once then is automatically removed. </p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Parameters</h5> <table class="jd-tagtable"> <tr> <th>callback</td> <td>The frame callback to run during the next frame.</td> </tr> </table> </div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">See Also</h5> <ul class="nolist"><li><code><a href="../../../reference/android/view/Choreographer.html#postFrameCallbackDelayed(android.view.Choreographer.FrameCallback, long)">postFrameCallbackDelayed(Choreographer.FrameCallback, long)</a></code></li><li><code><a href="../../../reference/android/view/Choreographer.html#removeFrameCallback(android.view.Choreographer.FrameCallback)">removeFrameCallback(Choreographer.FrameCallback)</a></code></li> </ul> </div> </div> </div> <A NAME="postFrameCallbackDelayed(android.view.Choreographer.FrameCallback, long)"></A> <div class="jd-details api apilevel-16"> <h4 class="jd-details-title"> <span class="normal"> public void </span> <span class="sympad">postFrameCallbackDelayed</span> <span class="normal">(<a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a> callback, long delayMillis)</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 16</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Posts a frame callback to run on the next frame after the specified delay. <p> The callback runs once then is automatically removed. </p></p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Parameters</h5> <table class="jd-tagtable"> <tr> <th>callback</td> <td>The frame callback to run during the next frame.</td> </tr> <tr> <th>delayMillis</td> <td>The delay time in milliseconds.</td> </tr> </table> </div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">See Also</h5> <ul class="nolist"><li><code><a href="../../../reference/android/view/Choreographer.html#postFrameCallback(android.view.Choreographer.FrameCallback)">postFrameCallback(Choreographer.FrameCallback)</a></code></li><li><code><a href="../../../reference/android/view/Choreographer.html#removeFrameCallback(android.view.Choreographer.FrameCallback)">removeFrameCallback(Choreographer.FrameCallback)</a></code></li> </ul> </div> </div> </div> <A NAME="removeFrameCallback(android.view.Choreographer.FrameCallback)"></A> <div class="jd-details api apilevel-16"> <h4 class="jd-details-title"> <span class="normal"> public void </span> <span class="sympad">removeFrameCallback</span> <span class="normal">(<a href="../../../reference/android/view/Choreographer.FrameCallback.html">Choreographer.FrameCallback</a> callback)</span> </h4> <div class="api-level"> <div> Added in <a href="../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 16</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Removes a previously posted frame callback.</p></div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">Parameters</h5> <table class="jd-tagtable"> <tr> <th>callback</td> <td>The frame callback to remove.</td> </tr> </table> </div> <div class="jd-tagdata"> <h5 class="jd-tagtitle">See Also</h5> <ul class="nolist"><li><code><a href="../../../reference/android/view/Choreographer.html#postFrameCallback(android.view.Choreographer.FrameCallback)">postFrameCallback(Choreographer.FrameCallback)</a></code></li><li><code><a href="../../../reference/android/view/Choreographer.html#postFrameCallbackDelayed(android.view.Choreographer.FrameCallback, long)">postFrameCallbackDelayed(Choreographer.FrameCallback, long)</a></code></li> </ul> </div> </div> </div> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <A NAME="navbar_top"></A> <div id="footer" class="wrap" > <div id="copyright"> Except as noted, this content is licensed under <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. For details and restrictions, see the <a href="../../../license.html"> Content License</a>. </div> <div id="build_info"> Android 4.4&nbsp;r1 &mdash; <script src="../../../timestamp.js" type="text/javascript"></script> <script>document.write(BUILD_TIMESTAMP)</script> </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> <!-- jd-content --> </div><!-- end doc-content --> </div> <!-- end body-content --> </body> </html>
mit
dont-fear-the-repo/fear-the-repo
src/views/HomeView.js
3354
import React from 'react'; import { Link as RouterLink } from 'react-router'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import counterActions from 'actions/counter'; import Radium from 'radium'; import { Scroll, Link, Element, Events } from 'react-scroll'; import { FlatButton, Paper } from 'material-ui/lib'; import { styles } from 'styles/HomeViewStyles'; const mapStateToProps = (state) => ({ counter: state.counter, routerState: state.router }); const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(counterActions, dispatch) }); @Radium class HomeView extends React.Component { static propTypes = { actions: React.PropTypes.object, counter: React.PropTypes.number } render() { return ( <div className='landing main-body' style={styles.mainBody}> <div style={styles.heroDiv}> <img src={require('styles/assets/splash3.png')} style={styles.heroImg} draggable='false' /> <div style={styles.heroText}> a simple, intuitive, <br/>drag-and-drop resume builder </div> {Radium.getState(this.state, 'callToAction', 'hover')} <RouterLink to='/resume'> <div style={styles.callToAction} key='callToAction'> get started </div> </RouterLink> {Radium.getState(this.state, 'circle', 'hover')} <Link to='Features' spy={true} smooth={true} duration={800}> <div style={styles.circle} key='circle'> <img src={require('styles/assets/downArrow.png')} style={styles.downArrow} /> </div> </Link> <div style={styles.diagonalLine}></div> </div> <div style={styles.grayDivMiddle}> <div style={styles.copy}> <Element name='Features'> <div style={styles.wysiwyg}>what you see is what you get</div> <div style={styles.video}> <iframe src="https://player.vimeo.com/video/149104789?color=ff9f10&title=0&byline=0&portrait=0" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </div> </Element> <div style={styles.middleCopy}> <div>Import your information from LinkedIn</div> <div>Save your progress to the cloud</div> <div>Easily print or export to PDF when you're done</div> </div> <RouterLink to='/resume'> <div style={styles.getStartedButton}> get started </div> </RouterLink> </div> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(HomeView); /* Here lies the counter. It was a good counter; it incremented when clicked. But it was more than just a simple counter. It was a window into another world; a stateful lighthouse to our souls. The counter is dead. Long live the counter! <div style={{ margin: '20px' }}> <div style={{ margin: '5px' }}> For no reason, a counter: {this.props.counter} </div> <RaisedButton label='Increment' onClick={this.props.actions.increment} /> </div> */
mit
dipapaspyros/bdo_platform
uploader/static/css/uploader.css
468
#file-upload-picker { /*text-align: center;*/ margin: auto; margin-left: auto; } .label-radio { font-size: 30px; font-weight: bold; } #profile-dropdown{ width: 100px; } #download input{ width: 100%; } #download select{ width: 100%; } .nav>li { display: inline-block !important; } .nav-pills>li { float: none !important; width: 40%; } .nav-pills>li>a { font-size: 12pt !important; background-color: #d0d0d0; }
mit
piousbox/microsites2-cities
vendor/ruby/1.9.1/gems/devise-2.2.3/test/models/lockable_test.rb
8403
require 'test_helper' class LockableTest < ActiveSupport::TestCase def setup setup_mailer end test "should respect maximum attempts configuration" do user = create_user user.confirm! swap Devise, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end end test "should increment failed_attempts on successfull validation if the user is already locked" do user = create_user user.confirm! swap Devise, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end user.valid_for_authentication?{ true } assert_equal 4, user.reload.failed_attempts end test "should not touch failed_attempts if lock_strategy is none" do user = create_user user.confirm! swap Devise, :lock_strategy => :none, :maximum_attempts => 2 do 3.times { user.valid_for_authentication?{ false } } assert !user.access_locked? assert_equal 0, user.failed_attempts end end test 'should be valid for authentication with a unlocked user' do user = create_user user.lock_access! user.unlock_access! assert user.valid_for_authentication?{ true } end test "should verify whether a user is locked or not" do user = create_user assert_not user.access_locked? user.lock_access! assert user.access_locked? end test "active_for_authentication? should be the opposite of locked?" do user = create_user user.confirm! assert user.active_for_authentication? user.lock_access! assert_not user.active_for_authentication? end test "should unlock a user by cleaning locked_at, falied_attempts and unlock_token" do user = create_user user.lock_access! assert_not_nil user.reload.locked_at assert_not_nil user.reload.unlock_token user.unlock_access! assert_nil user.reload.locked_at assert_nil user.reload.unlock_token assert_equal 0, user.reload.failed_attempts end test "new user should not be locked and should have zero failed_attempts" do assert_not new_user.access_locked? assert_equal 0, create_user.failed_attempts end test "should unlock user after unlock_in period" do swap Devise, :unlock_in => 3.hours do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? Devise.unlock_in = 1.hour assert_not user.access_locked? end end test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do swap Devise, :unlock_strategy => :email do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? end end test "should set unlock_token when locking" do user = create_user assert_nil user.unlock_token user.lock_access! assert_not_nil user.unlock_token end test "should never generate the same unlock token for different users" do unlock_tokens = [] 3.times do user = create_user user.lock_access! token = user.unlock_token assert !unlock_tokens.include?(token) unlock_tokens << token end end test "should not generate unlock_token when :email is not an unlock strategy" do swap Devise, :unlock_strategy => :time do user = create_user user.lock_access! assert_nil user.unlock_token end end test "should send email with unlock instructions when :email is an unlock strategy" do swap Devise, :unlock_strategy => :email do user = create_user assert_email_sent do user.lock_access! end end end test "should not send email with unlock instructions when :email is not an unlock strategy" do swap Devise, :unlock_strategy => :time do user = create_user assert_email_not_sent do user.lock_access! end end end test 'should find and unlock a user automatically' do user = create_user user.lock_access! locked_user = User.unlock_access_by_token(user.unlock_token) assert_equal locked_user, user assert_not user.reload.access_locked? end test 'should return a new record with errors when a invalid token is given' do locked_user = User.unlock_access_by_token('invalid_token') assert_not locked_user.persisted? assert_equal "is invalid", locked_user.errors[:unlock_token].join end test 'should return a new record with errors when a blank token is given' do locked_user = User.unlock_access_by_token('') assert_not locked_user.persisted? assert_equal "can't be blank", locked_user.errors[:unlock_token].join end test 'should find a user to send unlock instructions' do user = create_user user.lock_access! unlock_user = User.send_unlock_instructions(:email => user.email) assert_equal unlock_user, user end test 'should return a new user if no email was found' do unlock_user = User.send_unlock_instructions(:email => "[email protected]") assert_not unlock_user.persisted? end test 'should add error to new user email if no email was found' do unlock_user = User.send_unlock_instructions(:email => "[email protected]") assert_equal 'not found', unlock_user.errors[:email].join end test 'should find a user to send unlock instructions by authentication_keys' do swap Devise, :authentication_keys => [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(:email => user.email, :username => user.username) assert_equal unlock_user, user end end test 'should require all unlock_keys' do swap Devise, :unlock_keys => [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(:email => user.email) assert_not unlock_user.persisted? assert_equal "can't be blank", unlock_user.errors[:username].join end end test 'should not be able to send instructions if the user is not locked' do user = create_user assert_not user.resend_unlock_token assert_not user.access_locked? assert_equal 'was not locked', user.errors[:email].join end test 'should unlock account if lock has expired and increase attempts on failure' do swap Devise, :unlock_in => 1.minute do user = create_user user.confirm! user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { false } assert_equal 1, user.failed_attempts end end test 'should unlock account if lock has expired on success' do swap Devise, :unlock_in => 1.minute do user = create_user user.confirm! user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { true } assert_equal 0, user.failed_attempts assert_nil user.locked_at end end test 'required_fields should contain the all the fields when all the strategies are enabled' do swap Devise, :unlock_strategy => :both do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at, :unlock_token ] end end end test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do swap Devise, :unlock_strategy => :time do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at ] end end end test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do swap Devise, :unlock_strategy => :email do swap Devise, :lock_strategy => :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :unlock_token ] end end end test 'should not return a locked unauthenticated message if in paranoid mode' do swap Devise, :paranoid => :true do user = create_user user.failed_attempts = Devise.maximum_attempts + 1 user.lock_access! assert_equal :invalid, user.unauthenticated_message end end end
mit
hoho/dosido
nodejs/deps/v8/tools/ignition/linux_perf_report.py
8176
#! /usr/bin/python2 # # Copyright 2016 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # import argparse import collections import re import subprocess import sys __DESCRIPTION = """ Processes a perf.data sample file and reports the hottest Ignition bytecodes, or write an input file for flamegraph.pl. """ __HELP_EPILOGUE = """ examples: # Get a flamegraph for Ignition bytecode handlers on Octane benchmark, # without considering the time spent compiling JS code, entry trampoline # samples and other non-Ignition samples. # $ tools/run-perf.sh out/x64.release/d8 \\ --ignition --noturbo --noopt run.js $ tools/ignition/linux_perf_report.py --flamegraph -o out.collapsed $ flamegraph.pl --colors js out.collapsed > out.svg # Same as above, but show all samples, including time spent compiling JS code, # entry trampoline samples and other samples. $ # ... $ tools/ignition/linux_perf_report.py \\ --flamegraph --show-all -o out.collapsed $ # ... # Same as above, but show full function signatures in the flamegraph. $ # ... $ tools/ignition/linux_perf_report.py \\ --flamegraph --show-full-signatures -o out.collapsed $ # ... # See the hottest bytecodes on Octane benchmark, by number of samples. # $ tools/run-perf.sh out/x64.release/d8 \\ --ignition --noturbo --noopt octane/run.js $ tools/ignition/linux_perf_report.py """ COMPILER_SYMBOLS_RE = re.compile( r"v8::internal::(?:\(anonymous namespace\)::)?Compile|v8::internal::Parser") JIT_CODE_SYMBOLS_RE = re.compile( r"(LazyCompile|Compile|Eval|Script):(\*|~)") GC_SYMBOLS_RE = re.compile( r"v8::internal::Heap::CollectGarbage") def strip_function_parameters(symbol): if symbol[-1] != ')': return symbol pos = 1 parenthesis_count = 0 for c in reversed(symbol): if c == ')': parenthesis_count += 1 elif c == '(': parenthesis_count -= 1 if parenthesis_count == 0: break else: pos += 1 return symbol[:-pos] def collapsed_callchains_generator(perf_stream, hide_other=False, hide_compiler=False, hide_jit=False, hide_gc=False, show_full_signatures=False): current_chain = [] skip_until_end_of_chain = False compiler_symbol_in_chain = False for line in perf_stream: # Lines starting with a "#" are comments, skip them. if line[0] == "#": continue line = line.strip() # Empty line signals the end of the callchain. if not line: if (not skip_until_end_of_chain and current_chain and not hide_other): current_chain.append("[other]") yield current_chain # Reset parser status. current_chain = [] skip_until_end_of_chain = False compiler_symbol_in_chain = False continue if skip_until_end_of_chain: continue # Trim the leading address and the trailing +offset, if present. symbol = line.split(" ", 1)[1].split("+", 1)[0] if not show_full_signatures: symbol = strip_function_parameters(symbol) # Avoid chains of [unknown] if (symbol == "[unknown]" and current_chain and current_chain[-1] == "[unknown]"): continue current_chain.append(symbol) if symbol.startswith("BytecodeHandler:"): current_chain.append("[interpreter]") yield current_chain skip_until_end_of_chain = True elif JIT_CODE_SYMBOLS_RE.match(symbol): if not hide_jit: current_chain.append("[jit]") yield current_chain skip_until_end_of_chain = True elif GC_SYMBOLS_RE.match(symbol): if not hide_gc: current_chain.append("[gc]") yield current_chain skip_until_end_of_chain = True elif symbol == "Stub:CEntryStub" and compiler_symbol_in_chain: if not hide_compiler: current_chain.append("[compiler]") yield current_chain skip_until_end_of_chain = True elif COMPILER_SYMBOLS_RE.match(symbol): compiler_symbol_in_chain = True elif symbol == "Builtin:InterpreterEntryTrampoline": if len(current_chain) == 1: yield ["[entry trampoline]"] else: # If we see an InterpreterEntryTrampoline which is not at the top of the # chain and doesn't have a BytecodeHandler above it, then we have # skipped the top BytecodeHandler due to the top-level stub not building # a frame. File the chain in the [misattributed] bucket. current_chain[-1] = "[misattributed]" yield current_chain skip_until_end_of_chain = True def calculate_samples_count_per_callchain(callchains): chain_counters = collections.defaultdict(int) for callchain in callchains: key = ";".join(reversed(callchain)) chain_counters[key] += 1 return chain_counters.items() def calculate_samples_count_per_handler(callchains): def strip_handler_prefix_if_any(handler): return handler if handler[0] == "[" else handler.split(":", 1)[1] handler_counters = collections.defaultdict(int) for callchain in callchains: handler = strip_handler_prefix_if_any(callchain[-1]) handler_counters[handler] += 1 return handler_counters.items() def write_flamegraph_input_file(output_stream, callchains): for callchain, count in calculate_samples_count_per_callchain(callchains): output_stream.write("{}; {}\n".format(callchain, count)) def write_handlers_report(output_stream, callchains): handler_counters = calculate_samples_count_per_handler(callchains) samples_num = sum(counter for _, counter in handler_counters) # Sort by decreasing number of samples handler_counters.sort(key=lambda entry: entry[1], reverse=True) for bytecode_name, count in handler_counters: output_stream.write( "{}\t{}\t{:.3f}%\n".format(bytecode_name, count, 100. * count / samples_num)) def parse_command_line(): command_line_parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__DESCRIPTION, epilog=__HELP_EPILOGUE) command_line_parser.add_argument( "perf_filename", help="perf sample file to process (default: perf.data)", nargs="?", default="perf.data", metavar="<perf filename>" ) command_line_parser.add_argument( "--flamegraph", "-f", help="output an input file for flamegraph.pl, not a report", action="store_true", dest="output_flamegraph" ) command_line_parser.add_argument( "--hide-other", help="Hide other samples", action="store_true" ) command_line_parser.add_argument( "--hide-compiler", help="Hide samples during compilation", action="store_true" ) command_line_parser.add_argument( "--hide-jit", help="Hide samples from JIT code execution", action="store_true" ) command_line_parser.add_argument( "--hide-gc", help="Hide samples from garbage collection", action="store_true" ) command_line_parser.add_argument( "--show-full-signatures", "-s", help="show full signatures instead of function names", action="store_true" ) command_line_parser.add_argument( "--output", "-o", help="output file name (stdout if omitted)", type=argparse.FileType('wt'), default=sys.stdout, metavar="<output filename>", dest="output_stream" ) return command_line_parser.parse_args() def main(): program_options = parse_command_line() perf = subprocess.Popen(["perf", "script", "--fields", "ip,sym", "-i", program_options.perf_filename], stdout=subprocess.PIPE) callchains = collapsed_callchains_generator( perf.stdout, program_options.hide_other, program_options.hide_compiler, program_options.hide_jit, program_options.hide_gc, program_options.show_full_signatures) if program_options.output_flamegraph: write_flamegraph_input_file(program_options.output_stream, callchains) else: write_handlers_report(program_options.output_stream, callchains) if __name__ == "__main__": main()
mit
jbrantly/ts-loader
test/comparison-tests/conditionalRequire/expectedOutput-2.8/bundle.js
3132
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; eval("\nexports.__esModule = true;\nconsole.log('do something');\n// The DEBUG constant will be inlined by webpack's DefinePlugin (see config)\n// The whole if-statement can then be removed by UglifyJS\nif (false) { var debug; }\nconsole.log('do something else');\n\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
mit
fidmor89/appInsights-Concrete
appinsights/vendor/microsoft/application-insights/ApplicationInsights/Channel/Contracts/Utils.php
3254
<?php namespace ApplicationInsights\Channel\Contracts; /** * Contains utilities for contract classes */ class Utils { /** * Removes NULL and empty collections * @param array $sourceArray * @return array */ public static function removeEmptyValues($sourceArray) { $newArray = array(); foreach ($sourceArray as $key => $value) { if ((is_array($value) && sizeof($value) == 0) || ($value == NULL && is_bool($value) == false)) { continue; } $newArray[$key] = $value; } return $newArray; } /** * Serialization helper. * @param array Items to serialize * @return array JSON serialized items, nested */ public static function getUnderlyingData($dataItems) { $queueToEncode = array(); foreach ($dataItems as $key => $dataItem) { if (method_exists($dataItem, 'jsonSerialize') == true) { $queueToEncode[$key] = Utils::getUnderlyingData($dataItem->jsonSerialize()); } else if (is_array($dataItem)) { $queueToEncode[$key] = Utils::getUnderlyingData($dataItem); } else { $queueToEncode[$key] = $dataItem; } } return $queueToEncode; } /** * Converts milliseconds to a timespan string as accepted by the backend * @param int $milliseconds * @return string */ public static function convertMillisecondsToTimeSpan($milliseconds) { if ($milliseconds == NULL || $milliseconds < 0) { $milliseconds = 0; } $ms = $milliseconds % 1000; $sec = floor($milliseconds / 1000) % 60; $min = floor($milliseconds / (1000 * 60)) % 60; $hour = floor($milliseconds / (1000 * 60 * 60)) % 24; $ms = strlen($ms) == 1 ? '00' . $ms : (strlen($ms) === 2 ? "0" . $ms : $ms); $sec = strlen($sec) < 2 ? '0' . $sec : $sec; $min = strlen($min) < 2 ? '0' . $min : $min; $hour = strlen($hour) < 2 ? '0' . $hour : $hour; return $hour . ":" . $min . ":" . $sec . "." . $ms; } /** * Returns the proper ISO string for Application Insights service to accept. * @param mixed $time * @return string */ public static function returnISOStringForTime($time = null) { if ($time == NULL) { return gmdate('c') . 'Z'; } else { return gmdate('c', $time) . 'Z'; } } /** * Returns a Guid on all flavors of PHP. Copied from the PHP manual: http://php.net/manual/en/function.com-create-guid.php * @return mixed */ public static function returnGuid() { if (function_exists('com_create_guid') === true) { return trim(com_create_guid(), '{}'); } return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); } }
mit
jdanyow/aurelia-plunker
jspm_packages/npm/[email protected]/modules/_classof.js
427
/* */ var cof = require("./_cof"), TAG = require("./_wks")('toStringTag'), ARG = cof(function() { return arguments; }()) == 'Arguments'; module.exports = function(it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' : typeof(T = (O = Object(it))[TAG]) == 'string' ? T : ARG ? cof(O) : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; };
mit
trex2000/Arobs-Academy
Doxygen Generated/html/search/functions_1.js
1903
var searchData= [ ['analogread',['analogRead',['../_arduino_8h.html#a13782c0f73097cea014616d749e7c52d',1,'analogRead(uint8_t):&#160;wiring_analog.c'],['../wiring__analog_8c.html#a2eda513a6bb35bf13675a24711d4e864',1,'analogRead(uint8_t pin):&#160;wiring_analog.c']]], ['analogreference',['analogReference',['../_arduino_8h.html#a529863849f86a63b517cd96cbcd47705',1,'analogReference(uint8_t mode):&#160;wiring_analog.c'],['../wiring__analog_8c.html#a529863849f86a63b517cd96cbcd47705',1,'analogReference(uint8_t mode):&#160;wiring_analog.c']]], ['analogwrite',['analogWrite',['../_arduino_8h.html#a428477da35f3b1cf51bc2653125d9d9d',1,'analogWrite(uint8_t, int):&#160;wiring_analog.c'],['../wiring__analog_8c.html#a62a628c40d93ea1823a1cdb8cae9e7be',1,'analogWrite(uint8_t pin, int val):&#160;wiring_analog.c']]], ['atexit',['atexit',['../_arduino_8h.html#a2f34e9ad40b966beef5bda170015d19b',1,'atexit(void(*func)()) __attribute__((weak)):&#160;main.cpp'],['../main_8cpp.html#a7962f8536e3c743c8380411e184c7e2f',1,'atexit(void(*func)()):&#160;main.cpp']]], ['attachinterrupt',['attachInterrupt',['../_arduino_8h.html#a3ed3d1d750935833a6f9b0363a5e6f13',1,'attachInterrupt(uint8_t, void(*)(void), int mode):&#160;WInterrupts.c'],['../_w_interrupts_8c.html#ad0d73becebba7c663f8e9ed73efee544',1,'attachInterrupt(uint8_t interruptNum, void(*userFunc)(void), int mode):&#160;WInterrupts.c']]], ['available',['available',['../class_client.html#aebd60457902debb30b07971a16f24ebd',1,'Client::available()'],['../class_hardware_serial.html#aeec8f4dbef97221a6041d6cdc6e9b716',1,'HardwareSerial::available()'],['../class_stream.html#aebd60457902debb30b07971a16f24ebd',1,'Stream::available()'],['../class_u_d_p.html#aebd60457902debb30b07971a16f24ebd',1,'UDP::available()']]], ['availableforwrite',['availableForWrite',['../class_hardware_serial.html#a4afe5933dbdb0ad962857d00e04c3bfc',1,'HardwareSerial']]] ];
mit
FaHeymann/lerna
test/helpers/serializePlaceholders.js
1443
/* eslint node/no-unsupported-features: ["error", { version: 4 }] */ // this file is not transpiled by Jest when configured in "snapshotSerializers" "use strict"; const _ = require("lodash"); const normalizeNewline = require("normalize-newline"); const constants = require("./constants"); const VERSION_REGEX = new RegExp(`^(?:((?:.*?version )|\\^)|v?)${constants.LERNA_VERSION}`, "gm"); const VERSION_REPLACEMENT = `$1${constants.__TEST_VERSION__}`; // TODO: maybe even less naïve regex? function needsReplacement(str) { return ( str.indexOf(constants.__TEST_VERSION__) === -1 ); } function stableVersion(str) { return str.replace(VERSION_REGEX, VERSION_REPLACEMENT); } const stabilizeString = _.flow([ normalizeNewline, stableVersion, ]); /** A snapshot serializer that replaces all instances of unstable version number with __TEST_VERSION__ when found in snapshotted strings or object properties. @see http://facebook.github.io/jest/docs/expect.html#expectaddsnapshotserializerserializer **/ module.exports = { test(thing) { return _.isString(thing) && needsReplacement(thing) || ( _.isPlainObject(thing) && _.isString(thing.lerna) && needsReplacement(thing.lerna) ); }, print(thing, serialize) { if (_.isString(thing)) { thing = stabilizeString(thing); } else if (_.isPlainObject(thing)) { thing.lerna = stableVersion(thing.lerna); } return serialize(thing); }, };
mit
decentraland/bronzeage-node
lib/primitives/address.js
15225
/*! * address.js - address object for decentraland * Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * Copyright (c) 2016-2017, Manuel Araoz (MIT License). * https://github.com/decentraland/decentraland-node */ 'use strict'; var networks = require('../protocol/networks'); var constants = require('../protocol/constants'); var util = require('../utils/util'); var crypto = require('../crypto/crypto'); var assert = require('assert'); var BufferReader = require('../utils/reader'); var StaticWriter = require('../utils/staticwriter'); var base58 = require('../utils/base58'); var scriptTypes = constants.scriptTypes; /** * Represents an address. * @exports Address * @constructor * @param {Object} options * @param {Buffer|Hash} options.hash - Address hash. * @param {AddressType} options.type - Address type * `{witness,}{pubkeyhash,scripthash}`. * @param {Number} [options.version=-1] - Witness program version. * @property {Buffer} hash * @property {AddressType} type * @property {Number} version */ function Address(options) { if (!(this instanceof Address)) return new Address(options); this.hash = constants.ZERO_HASH160; this.type = scriptTypes.PUBKEYHASH; this.version = -1; var Network = require('../protocol/network'); this.network = Network.primary; if (options) this.fromOptions(options); } /** * Address types. * @enum {Number} */ Address.types = scriptTypes; /** * Inject properties from options object. * @private * @param {Object} options */ Address.prototype.fromOptions = function fromOptions(options) { if (typeof options === 'string') return this.fromBase58(options); if (Buffer.isBuffer(options)) return this.fromRaw(options); return this.fromHash( options.hash, options.type, options.version, options.network ); }; /** * Insantiate address from options. * @param {Object} options * @returns {Address} */ Address.fromOptions = function fromOptions(options) { return new Address().fromOptions(options); }; /** * Get the address hash. * @param {String?} enc - Can be `"hex"` or `null`. * @returns {Hash|Buffer} */ Address.prototype.getHash = function getHash(enc) { if (enc === 'hex') return this.hash.toString(enc); return this.hash; }; /** * Get a network address prefix for the address. * @returns {Number} */ Address.prototype.getPrefix = function getPrefix(network) { if (!network) network = this.network; var Network = require('../protocol/network'); network = Network.get(network); return Address.getPrefix(this.type, network); }; /** * Verify an address network (compares prefixes). * @returns {Boolean} */ Address.prototype.verifyNetwork = function verifyNetwork(network) { assert(network); return this.getPrefix() === this.getPrefix(network); }; /** * Get the address type as a string. * @returns {AddressType} */ Address.prototype.getType = function getType() { return constants.scriptTypesByVal[this.type].toLowerCase(); }; /** * Calculate size of serialized address. * @returns {Number} */ Address.prototype.getSize = function getSize() { var size = 5 + this.hash.length; if (this.version !== -1) size += 2; return size; }; /** * Compile the address object to its raw serialization. * @returns {Buffer} * @throws Error on bad hash/prefix. */ Address.prototype.toRaw = function toRaw(network) { var size = this.getSize(); var bw = new StaticWriter(size); var prefix = this.getPrefix(network); assert(prefix !== -1, 'Not a valid address prefix.'); bw.writeU8(prefix); if (this.version !== -1) { bw.writeU8(this.version); bw.writeU8(0); } bw.writeBytes(this.hash); bw.writeChecksum(); return bw.render(); }; /** * Compile the address object to a base58 address. * @returns {Base58Address} * @throws Error on bad hash/prefix. */ Address.prototype.toBase58 = function toBase58(network) { return base58.encode(this.toRaw(network)); }; /** * Convert the Address to a string. * @returns {Base58Address} */ Address.prototype.toString = function toString() { return this.toBase58(); }; /** * Inspect the Address. * @returns {Object} */ Address.prototype.inspect = function inspect() { return '<Address:' + ' type=' + this.getType() + ' version=' + this.version + ' base58=' + this.toBase58() + '>'; }; /** * Inject properties from serialized data. * @private * @param {Buffer} data * @throws Parse error */ Address.prototype.fromRaw = function fromRaw(data) { var br = new BufferReader(data, true); var i, prefix, network, type, version, hash; prefix = br.readU8(); for (i = 0; i < networks.types.length; i++) { network = networks[networks.types[i]]; type = Address.getType(prefix, network); if (type !== -1) break; } assert(i < networks.types.length, 'Unknown address prefix.'); if (data.length > 25) { version = br.readU8(); assert(br.readU8() === 0, 'Address version padding is non-zero.'); } else { version = -1; } hash = br.readBytes(br.left() - 4); br.verifyChecksum(); return this.fromHash(hash, type, version, network.type); }; /** * Create an address object from a serialized address. * @param {Buffer} data * @returns {Address} * @throws Parse error. */ Address.fromRaw = function fromRaw(data) { return new Address().fromRaw(data); }; /** * Inject properties from base58 address. * @private * @param {Base58Address} data * @throws Parse error */ Address.prototype.fromBase58 = function fromBase58(data) { assert(typeof data === 'string'); return this.fromRaw(base58.decode(data)); }; /** * Create an address object from a base58 address. * @param {Base58Address} address * @returns {Address} * @throws Parse error. */ Address.fromBase58 = function fromBase58(address) { return new Address().fromBase58(address); }; /** * Inject properties from output script. * @private * @param {Script} script */ Address.prototype.fromScript = function fromScript(script) { if (script.isPubkey()) { this.hash = crypto.hash160(script.get(0)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isPubkeyhash()) { this.hash = script.get(2); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthash()) { this.hash = script.get(1); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } if (script.isWitnessPubkeyhash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (script.isWitnessScripthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } if (script.isWitnessMasthash()) { this.hash = script.get(1); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 1; return this; } // Put this last: it's the slowest to check. if (script.isMultisig()) { this.hash = script.hash160(); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Inject properties from witness. * @private * @param {Witness} witness */ Address.prototype.fromWitness = function fromWitness(witness) { // We're pretty much screwed here // since we can't get the version. if (witness.isPubkeyhashInput()) { this.hash = crypto.hash160(witness.get(1)); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (witness.isScripthashInput()) { this.hash = crypto.sha256(witness.get(witness.length - 1)); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; } }; /** * Inject properties from input script. * @private * @param {Script} script */ Address.prototype.fromInputScript = function fromInputScript(script) { if (script.isPubkeyhashInput()) { this.hash = crypto.hash160(script.get(1)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthashInput()) { this.hash = crypto.hash160(script.get(script.length - 1)); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; } }; /** * Create an Address from a witness. * Attempt to extract address * properties from a witness. * @param {Witness} * @returns {Address|null} */ Address.fromWitness = function fromWitness(witness) { return new Address().fromWitness(witness); }; /** * Create an Address from an input script. * Attempt to extract address * properties from an input script. * @param {Script} * @returns {Address|null} */ Address.fromInputScript = function fromInputScript(script) { return new Address().fromInputScript(script); }; /** * Create an Address from an output script. * Parse an output script and extract address * properties. Converts pubkey and multisig * scripts to pubkeyhash and scripthash addresses. * @param {Script} * @returns {Address|null} */ Address.fromScript = function fromScript(script) { return new Address().fromScript(script); }; /** * Inject properties from a hash. * @private * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @throws on bad hash size */ Address.prototype.fromHash = function fromHash(hash, type, version, network) { if (typeof hash === 'string') hash = new Buffer(hash, 'hex'); if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type == null) type = scriptTypes.PUBKEYHASH; if (version == null) version = -1; var Network = require('../protocol/network'); network = Network.get(network); assert(Buffer.isBuffer(hash)); assert(util.isNumber(type)); assert(util.isNumber(version)); assert(Address.getPrefix(type, network) !== -1, 'Not a valid address type.'); if (version === -1) { assert(!Address.isWitness(type), 'Wrong version (witness)'); assert(hash.length === 20, 'Hash is the wrong size.'); } else { assert(Address.isWitness(type), 'Wrong version (non-witness).'); assert(version >= 0 && version <= 16, 'Bad program version.'); if (version === 0 && type === scriptTypes.WITNESSPUBKEYHASH) assert(hash.length === 20, 'Hash is the wrong size.'); else if (version === 0 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); else if (version === 1 && type === scriptTypes.WITNESSSCRIPTHASH) assert(hash.length === 32, 'Hash is the wrong size.'); } this.hash = hash; this.type = type; this.version = version; this.network = network; return this; }; /** * Create a naked address from hash/type/version. * @param {Buffer|Hash} hash * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromHash = function fromHash(hash, type, version, network) { return new Address().fromHash(hash, type, version, network); }; /** * Inject properties from data. * @private * @param {Buffer|Buffer[]} data * @param {AddressType} type * @param {Number} [version=-1] */ Address.prototype.fromData = function fromData(data, type, version, network) { if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type === scriptTypes.WITNESSSCRIPTHASH) { if (version === 0) { assert(Buffer.isBuffer(data)); data = crypto.sha256(data); } else if (version === 1) { assert(Array.isArray(data)); throw new Error('MASTv2 creation not implemented.'); } else { throw new Error('Cannot create from version=' + version); } } else if (type === scriptTypes.WITNESSPUBKEYHASH) { if (version !== 0) throw new Error('Cannot create from version=' + version); assert(Buffer.isBuffer(data)); data = crypto.hash160(data); } else { data = crypto.hash160(data); } return this.fromHash(data, type, version, network); }; /** * Create an Address from data/type/version. * @param {Buffer|Buffer[]} data - Data to be hashed. * Normally a buffer, but can also be an array of * buffers for MAST. * @param {AddressType} type * @param {Number} [version=-1] * @returns {Address} * @throws on bad hash size */ Address.fromData = function fromData(data, type, version, network) { return new Address().fromData(data, type, version, network); }; /** * Validate an address, optionally test against a type. * @param {Base58Address} address * @param {AddressType} * @returns {Boolean} */ Address.validate = function validate(address, type) { if (!address) return false; if (!Buffer.isBuffer(address) && typeof address !== 'string') return false; try { address = Address.fromBase58(address); } catch (e) { return false; } if (typeof type === 'string') type = scriptTypes[type.toUpperCase()]; if (type && address.type !== type) return false; return true; }; /** * Get the hex hash of a base58 * address or address object. * @param {Base58Address|Address} data * @returns {Hash|null} */ Address.getHash = function getHash(data, enc) { var hash; if (typeof data === 'string') { if (data.length === 40 || data.length === 64) return enc === 'hex' ? data : new Buffer(data, 'hex'); try { hash = Address.fromBase58(data).hash; } catch (e) { return; } } else if (Buffer.isBuffer(data)) { hash = data; } else if (data instanceof Address) { hash = data.hash; } else { return; } return enc === 'hex' ? hash.toString('hex') : hash; }; /** * Get a network address prefix for a specified address type. * @param {AddressType} type * @returns {Number} */ Address.getPrefix = function getPrefix(type, network) { var prefixes = network.addressPrefix; switch (type) { case scriptTypes.PUBKEYHASH: return prefixes.pubkeyhash; case scriptTypes.SCRIPTHASH: return prefixes.scripthash; case scriptTypes.WITNESSPUBKEYHASH: return prefixes.witnesspubkeyhash; case scriptTypes.WITNESSSCRIPTHASH: return prefixes.witnessscripthash; default: return -1; } }; /** * Get an address type for a specified network address prefix. * @param {Number} prefix * @returns {AddressType} */ Address.getType = function getType(prefix, network) { var prefixes = network.addressPrefix; switch (prefix) { case prefixes.pubkeyhash: return scriptTypes.PUBKEYHASH; case prefixes.scripthash: return scriptTypes.SCRIPTHASH; case prefixes.witnesspubkeyhash: return scriptTypes.WITNESSPUBKEYHASH; case prefixes.witnessscripthash: return scriptTypes.WITNESSSCRIPTHASH; default: return -1; } }; /** * Test whether an address type is a witness program. * @param {AddressType} type * @returns {Boolean} */ Address.isWitness = function isWitness(type) { switch (type) { case scriptTypes.WITNESSPUBKEYHASH: return true; case scriptTypes.WITNESSSCRIPTHASH: return true; default: return false; } }; /* * Expose */ module.exports = Address;
mit
dotnetcore/CAP
samples/Sample.RabbitMQ.MySql/AppDbContext.cs
689
using Microsoft.EntityFrameworkCore; namespace Sample.RabbitMQ.MySql { public class Person { public int Id { get; set; } public string Name { get; set; } public override string ToString() { return $"Name:{Name}, Id:{Id}"; } } public class AppDbContext : DbContext { public const string ConnectionString = ""; public DbSet<Person> Persons { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseMySql(ConnectionString, new MariaDbServerVersion(ServerVersion.AutoDetect(ConnectionString))); } } }
mit
MarinAtanasov/AppBrix
Modules/AppBrix.Cloning/CloningModule.cs
1625
// Copyright (c) MarinAtanasov. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the project root for license information. using AppBrix.Cloning.Impl; using AppBrix.Container; using AppBrix.Lifecycle; using AppBrix.Modules; using System; using System.Collections.Generic; namespace AppBrix.Cloning; /// <summary> /// A module used for registering a default object cloner. /// The object cloner is used for creating deep and shallow copies of objects. /// </summary> public sealed class CloningModule : ModuleBase { #region Properties /// <summary> /// Gets the types of the modules which are direct dependencies for the current module. /// This is used to determine the order in which the modules are loaded. /// </summary> public override IEnumerable<Type> Dependencies => new[] { typeof(ContainerModule) }; #endregion #region Public and overriden methods /// <summary> /// Initializes the module. /// Automatically called by <see cref="ModuleBase.Initialize"/> /// </summary> /// <param name="context">The initialization context.</param> protected override void Initialize(IInitializeContext context) { this.App.Container.Register(this); this.App.Container.Register(this.cloner); } /// <summary> /// Uninitializes the module. /// Automatically called by <see cref="ModuleBase.Uninitialize"/> /// </summary> protected override void Uninitialize() { } #endregion #region Private fields and constants private readonly Cloner cloner = new Cloner(); #endregion }
mit
flowtype/flow-typed
definitions/npm/@reach/portal_v0.2.x/flow_v0.84.x-/portal_v0.2.x.js
145
// @flow declare module '@reach/portal' { declare export default React$ComponentType<{| children: React$Node, type?: string, |}>; }
mit
Nebulis/angular2-migration-sample
step/step8/app/index.html
1281
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angular2 Migration</title> <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css"> <link rel="stylesheet" href="css/app.css"> <script src="../node_modules/systemjs/dist/system.src.js"></script> <script src="bower_components/jquery/dist/jquery.js"></script> <script src="bower_components/angular/angular.js"></script> <script src="../node_modules/es6-shim/es6-shim.js"></script> <script src="../node_modules/es6-promise/dist/es6-promise.js"></script> <script src="../node_modules/angular2/bundles/angular2-polyfills.js"></script> <script src="../node_modules/angular2/bundles/angular2.dev.js"></script> <script src="../node_modules/angular2/bundles/upgrade.dev.js"></script> <script src="../node_modules/rxjs/bundles/Rx.js"></script> <script src="../node_modules/angular2/bundles/http.dev.js"></script> <script> System.config({ packages: {'js': {defaultExtension: 'js'}} }); System.import('js/app'); </script> </head> <body> <header> <img src="img/Logo_arrondi_Horizontal2.png" /> <h1>Zenika Brewery !!</h1> <img src="img/Logo_arrondi_Horizontal2.png" /> </header> <app class="flex-container"></app> </body> </html>
mit
cartman300/Vermin
V/Parser.cs
3763
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.InteropServices; using System.Globalization; using System.Linq.Expressions; using Mono.Linq.Expressions; namespace V { public enum Keyword : int { _TypesStart, // Types begin Void, Int, UInt, String, Float, Double, _TypesEnd, // Types end _KeywordsStart, // Keywords begin Null, Return, _KeywordsEnd, // Keywords end } public enum Symbol : int { _Null, LParen, RParen, LCurvy, RCurvy, Comma, Semicolon, Assign, } public static class KeywordExtensions { public static bool IsBetween(this Keyword K, Keyword Start, Keyword End) { return (int)K > (int)Start && (int)K < (int)End; } public static bool IsType(this Keyword K) { return K.IsBetween(Keyword._TypesStart, Keyword._TypesEnd); } } public static class TokenExtensions { public static bool IsType(this Token T) { return T.Type == TokenType.Keyword && ((Keyword)T.Id).IsType(); } public static Type ToType(this Token T) { if (!T.IsType()) throw new Exception("Token is not a type token"); Keyword K = (Keyword)T.Id; switch (K) { case Keyword.Void: return typeof(void); case Keyword.Int: return typeof(int); case Keyword.UInt: return typeof(uint); case Keyword.String: return typeof(string); case Keyword.Double: return typeof(double); case Keyword.Float: return typeof(float); default: throw new Exception("Unknown type keyword " + K); } } public static bool IsIdentifier(this Token T) { return T.Type == TokenType.Identifier; } public static bool IsSymbol(this Token T, Symbol S) { return T.Type == TokenType.Symbol && ((Symbol)T.Id) == S; } public static bool IsKeyword(this Token T, Keyword K) { return T.Type == TokenType.Keyword && ((Keyword)T.Id) == K; } } public class Parser { LexerBehavior LB; LexerSettings LS; Token[] Tokens; int Idx; public Parser() { LB = LexerBehavior.SkipComments | LexerBehavior.SkipWhiteSpaces | LexerBehavior.Default; LS = LexerSettings.Default; LS.Options = LexerOptions.StringDoubleQuote | LexerOptions.StringEscaping; LS.Keywords = new Dictionary<string, int>(); string[] KeywordNames = Enum.GetNames(typeof(Keyword)); for (int i = 0; i < KeywordNames.Length; i++) { if (KeywordNames[i].StartsWith("_")) continue; LS.Keywords.Add(KeywordNames[i].ToLower(), (int)(Keyword)Enum.Parse(typeof(Keyword), KeywordNames[i])); } LS.Symbols = new Dictionary<string, int>(); LS.Symbols.Add("(", (int)Symbol.LParen); LS.Symbols.Add(")", (int)Symbol.RParen); LS.Symbols.Add("{", (int)Symbol.LCurvy); LS.Symbols.Add("}", (int)Symbol.RCurvy); LS.Symbols.Add(",", (int)Symbol.Comma); LS.Symbols.Add(";", (int)Symbol.Semicolon); LS.Symbols.Add("=", (int)Symbol.Assign); } Token Peek(int N = 0) { if (Idx + N >= Tokens.Length) return Token.Null; return Tokens[Idx + N]; } Symbol PeekSymbol(int N = 0) { Token T = Peek(N); if (T.Type != TokenType.Symbol) return Symbol._Null; return (Symbol)T.Id; } Token Next() { Token N = Peek(); Console.WriteLine(N); Idx++; return N; } public void Parse(string Src) { Parse(new StringReader(Src)); } public void Parse(TextReader TR) { Lexer L = new Lexer(TR, LB, LS); Tokens = L.ToArray(); Idx = 0; while (Peek() != Token.Null) Next(); /*List<Expression> Program = new List<Expression>(); while (Peek() != Token.Null) Program.Add(ParseAny()); Console.WriteLine(); foreach (var E in Program) Console.WriteLine(E.ToCSharpCode());*/ } } }
mit
JuliaPackageMirrors/DocOpt.jl
examples/options_shortcut_example.jl
531
const doc = """Example of program which uses [options] shortcut in pattern. Usage: options_shortcut_example.jl [options] <port> Options: -h --help show this help message and exit --version show version and exit -n, --number N use N as a number -t, --timeout TIMEOUT set timeout TIMEOUT seconds --apply apply changes to database -q operate in quiet mode """ using DocOpt arguments = docopt(doc, version="1.0.0rc2") dump(arguments)
mit
smedefind/optoro_zookeeper
spec/helpers.rb
606
shared_context 'optoro_zookeeper' do before do Chef::Recipe.any_instance.stub(:query_role).and_return('kitchen_role') Chef::Recipe.any_instance.stub(:query_role_credentials).and_return('{ "Code" : "Success", "LastUpdated" : "2015-03-09T14:48:17Z", "Type" : "AWS-HMAC", "AccessKeyId" : "ACCESSKEY", "SecretAccessKey" : "SECRETKEY", "Token" : "TOKEN", "Expiration" : "2015-03-09T21:14:00Z" }') allow(Chef::EncryptedDataBagItem).to receive(:load).with('aws', 'aws_keys').and_return('id' => 'aws_keys', 'exhibitor_access_key_id' => 'ACCESS', 'exhibitor_secret_access_key' => 'SECRET') end end
mit
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Pentax/FlashStatus.php
1553
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Pentax; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class FlashStatus extends AbstractTag { protected $Id = 0; protected $Name = 'FlashStatus'; protected $FullName = 'Pentax::FlashInfo'; protected $GroupName = 'Pentax'; protected $g0 = 'MakerNotes'; protected $g1 = 'Pentax'; protected $g2 = 'Camera'; protected $Type = 'int8u'; protected $Writable = true; protected $Description = 'Flash Status'; protected $flag_Permanent = true; protected $Values = array( 0 => array( 'Id' => 0, 'Label' => 'Off', ), 1 => array( 'Id' => 1, 'Label' => 'Off (1)', ), 2 => array( 'Id' => 2, 'Label' => 'External, Did not fire', ), 6 => array( 'Id' => 6, 'Label' => 'External, Fired', ), 8 => array( 'Id' => 8, 'Label' => 'Internal, Did not fire (0x08)', ), 9 => array( 'Id' => 9, 'Label' => 'Internal, Did not fire', ), 13 => array( 'Id' => 13, 'Label' => 'Internal, Fired', ), ); }
mit
juhuaguai/duilib
include/Control/UIGifAnim.h
1406
#ifndef GifAnimUI_h__ #define GifAnimUI_h__ #pragma once namespace DuiLib { #define EVENT_TIME_ID 100 class DUILIB_API CGifAnimUI : public CLabelUI { public: CGifAnimUI(void); ~CGifAnimUI(void); LPCTSTR GetClass() const; LPVOID GetInterface(LPCTSTR pstrName); virtual void DoEvent(TEventUI& event); virtual void SetVisible(bool bVisible = true ); virtual void SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue); virtual void SetBkImage(const CDuiString& strImage); virtual void PaintBkImage(HDC hDC); virtual void SetAutoPlay(bool bIsAuto = true ); virtual bool IsAutoPlay() const; virtual void SetAutoSize(bool bIsAuto = true ); virtual bool IsAutoSize() const; virtual void Play(); virtual void Pause(); virtual void Stop(); virtual void OnTimer( UINT_PTR idEvent ); virtual bool LoadFromFile(LPCTSTR pstrGifPath); virtual bool LoadFromMemory( LPVOID pBuf,size_t dwSize,DWORD dwMask ); protected: CDuiPtrArray m_Frames; UINT m_nFramePosition; // µ±Ç°·Åµ½µÚ¼¸Ö¡ int m_nFrameWidth; int m_nFrameHeight; int m_nLoopCout; //²¥·Å¼¸´Î 0ÎÞÏÞÑ­»·//stbimgÀïÃæ£¬½âÎögifÊ±ËÆºõûÓжÁÈ¡Õâ¸öÖµ int m_nLoopedNum; CDuiString m_sBkImage; bool m_bIsAutoPlay; // ÊÇ·ñ×Ô¶¯²¥·Ågif bool m_bIsAutoSize; // ÊÇ·ñ×Ô¶¯¸ù¾ÝͼƬÉèÖôóС bool m_bIsPlaying; }; } #endif // GifAnimUI_h__
mit
robrua/Orianna
orianna/src/main/java/com/merakianalytics/orianna/types/core/searchable/SearchableObject.java
155
package com.merakianalytics.orianna.types.core.searchable; public abstract interface SearchableObject { public boolean contains(final Object item); }
mit
yogeshsaroya/new-cdnjs
ajax/libs/highlight.js/7.5/languages/actionscript.min.js
128
version https://git-lfs.github.com/spec/v1 oid sha256:90773470146a0daefafb65539bea2a9c6537067655a435ffce48433658e3d73a size 943
mit
fabiensebban/magento
dev/tests/functional/tests/app/Mage/Catalog/Test/Handler/CatalogAttributeSet/CatalogAttributeSetInterface.php
1196
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Tests * @package Tests_Functional * @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ namespace Mage\Catalog\Test\Handler\CatalogAttributeSet; use Magento\Mtf\Handler\HandlerInterface; /** * Interface CatalogCategoryEntityInterface. */ interface CatalogAttributeSetInterface extends HandlerInterface { // }
mit
selvasingh/azure-sdk-for-java
sdk/containerregistry/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/containerregistry/v2019_04_01/OS.java
1118
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.containerregistry.v2019_04_01; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for OS. */ public final class OS extends ExpandableStringEnum<OS> { /** Static value Windows for OS. */ public static final OS WINDOWS = fromString("Windows"); /** Static value Linux for OS. */ public static final OS LINUX = fromString("Linux"); /** * Creates or finds a OS from its string representation. * @param name a name to look for * @return the corresponding OS */ @JsonCreator public static OS fromString(String name) { return fromString(name, OS.class); } /** * @return known OS values */ public static Collection<OS> values() { return values(OS.class); } }
mit
johncosta/private-readthedocs.org
readthedocs/templates/post_commit.html
379
{% extends "base.html" %} {% block title %}Build Started {% endblock %} {% block content %} {% if built %} {{ project }} is now building.<br><br> Check it out <a href="{{ project.get_absolute_url }}">over here</a> {% else %} This is a post-commit hook. Set it up in your project admin to POST here, for us to update your doc changes automatically. {% endif %} {% endblock %}
mit
BogdanLivadariu/bootstraped-multi-test-results-report
bootstraped-multi-test-results-report/src/main/java/com/github/bogdanlivadariu/jenkins/reporting/testng/TestNGTestReportBuildStepDescriptor.java
507
package com.github.bogdanlivadariu.jenkins.reporting.testng; import hudson.model.AbstractProject; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Publisher; public class TestNGTestReportBuildStepDescriptor extends BuildStepDescriptor<Publisher> { @Override public String getDisplayName() { return "Publish TestNG reports generated with handlebars"; } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } }
mit
jawadaspose/Aspose.Email-for-.NET
Examples/CSharp/SMTP/SendingEMLFilesWithSMTP.cs
1239
using System; using System.Diagnostics; using Aspose.Email.Mail; namespace Aspose.Email.Examples.CSharp.Email.SMTP { class SendingEMLFilesWithSMTP { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_SMTP(); string dstEmail = dataDir + "Message.eml"; // Create an instance of the MailMessage class MailMessage message = new MailMessage(); // Import from EML format message = MailMessage.Load(dstEmail, new EmlLoadOptions()); // Create an instance of SmtpClient class SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "[email protected]", "your.password"); client.SecurityOptions = SecurityOptions.Auto; try { // Client.Send will send this message client.Send(message); Console.WriteLine("Message sent"); } catch (Exception ex) { Trace.WriteLine(ex.ToString()); } Console.WriteLine(Environment.NewLine + "Email sent using EML file successfully. " + dstEmail); } } }
mit
BernardoSilva/mongrate
test/Mongrate/Tests/Command/TestMigrationCommandTest.php
3547
<?php namespace Mongrate\Tests\Command; use Mongrate\Command\TestMigrationCommand; use Mongrate\Enum\DirectionEnum; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; class TestMigrationCommandTest extends BaseCommandTest { public function testExecute_upAndDown() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute(['command' => $command->getName(), 'name' => 'UpdateAddressStructure']); $this->assertEquals( "Testing UpdateAddressStructure going up.\n" . "Test passed.\n" . "Testing UpdateAddressStructure going down.\n" . "Test passed.\n", $commandTester->getDisplay() ); } public function testExecute_up() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute([ 'command' => $command->getName(), 'name' => 'UpdateAddressStructure', 'direction' => DirectionEnum::UP]); $this->assertEquals( "Testing UpdateAddressStructure going up.\n" . "Test passed.\n", $commandTester->getDisplay() ); } public function testExecute_down() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute([ 'command' => $command->getName(), 'name' => 'UpdateAddressStructure', 'direction' => DirectionEnum::DOWN]); $this->assertEquals( "Testing UpdateAddressStructure going down.\n" . "Test passed.\n", $commandTester->getDisplay() ); } /** * @expectedException Mongrate\Exception\MigrationDoesntExist * @expectedExceptionMessage There is no migration called "Elvis" in "resources/examples/Elvis/Migration.php" */ public function testExecute_migrationDoesntExist() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); $commandTester->execute(['command' => $command->getName(), 'name' => 'Elvis']); } public function testExecute_hasMongoObjectsInYml() { $application = new Application(); $application->add(new TestMigrationCommand(null, $this->parametersFromYmlFile)); $command = $application->find('test'); $commandTester = new CommandTester($command); // First run should go up. $commandTester->execute([ 'command' => $command->getName(), 'name' => 'DeleteOldLogs', 'direction' => DirectionEnum::UP]); $this->assertEquals( "Testing DeleteOldLogs going up.\n" . "Test passed.\n", $commandTester->getDisplay() ); } }
mit
rainlike/justshop
vendor/ocramius/proxy-manager/src/ProxyManager/ProxyGenerator/NullObject/MethodGenerator/StaticProxyConstructor.php
2514
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ declare(strict_types=1); namespace ProxyManager\ProxyGenerator\NullObject\MethodGenerator; use ProxyManager\Generator\MethodGenerator; use ProxyManager\ProxyGenerator\Util\Properties; use ReflectionClass; use ReflectionProperty; /** * The `staticProxyConstructor` implementation for null object proxies * * @author Marco Pivetta <[email protected]> * @license MIT */ class StaticProxyConstructor extends MethodGenerator { /** * Constructor * * @param ReflectionClass $originalClass Reflection of the class to proxy * * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ public function __construct(ReflectionClass $originalClass) { parent::__construct('staticProxyConstructor', [], static::FLAG_PUBLIC | static::FLAG_STATIC); $nullableProperties = array_map( function (ReflectionProperty $publicProperty) : string { return '$instance->' . $publicProperty->getName() . ' = null;'; }, Properties::fromReflectionClass($originalClass)->getPublicProperties() ); $this->setDocBlock('Constructor for null object initialization'); $this->setBody( 'static $reflection;' . "\n\n" . '$reflection = $reflection ?: $reflection = new \ReflectionClass(__CLASS__);' . "\n" . '$instance = (new \ReflectionClass(get_class()))->newInstanceWithoutConstructor();' . "\n\n" . ($nullableProperties ? implode("\n", $nullableProperties) . "\n\n" : '') . 'return $instance;' ); } }
mit
johan12345/opacclient
opacclient/libopac/src/main/java/de/geeksfactory/opacclient/objects/Copy.java
11432
/** * Copyright (C) 2016 by Johan von Forstner under the MIT license: * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.geeksfactory.opacclient.objects; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; /** * Represents a copy of a medium ({@link DetailedItem}) available in a library. */ public class Copy { private String barcode; private String location; private String department; private String branch; private String issue; private String status; private LocalDate returnDate; private String reservations; private String shelfmark; private String resInfo; private String url; /** * @return The barcode of a copy. Optional. */ public String getBarcode() { return barcode; } /** * @param barcode The barcode of a copy. Optional. */ public void setBarcode(String barcode) { this.barcode = barcode; } /** * @return The location (like "third floor") of a copy. Optional. */ public String getLocation() { return location; } /** * @param location The location (like "third floor") of a copy. Optional. */ public void setLocation(String location) { this.location = location; } /** * @return The department (like "music library") of a copy. Optional. */ public String getDepartment() { return department; } /** * @param department The department (like "music library") of a copy. Optional. */ public void setDepartment(String department) { this.department = department; } /** * @return The branch a copy is in. Should be set, if your library has more than one branch. */ public String getBranch() { return branch; } /** * @param branch The branch a copy is in. Should be set, if your library has more than one * branch. */ public void setBranch(String branch) { this.branch = branch; } /** * @return The issue, e.g. when the item represents a year of magazines, this is the magazine number. */ public String getIssue() { return issue; } /** * @param issue The issue, e.g. when the item represents a year of magazines, this is the magazine number. */ public void setIssue(String issue) { this.issue = issue; } /** * @return Current status of a copy ("lent", "free", ...). Should be set. */ public String getStatus() { return status; } /** * @param status Current status of a copy ("lent", "free", ...). Should be set. */ public void setStatus(String status) { this.status = status; } /** * @return Expected date of return if a copy is lent out. Optional. */ public LocalDate getReturnDate() { return returnDate; } /** * @param returndate Expected date of return if a copy is lent out. Optional. */ public void setReturnDate(LocalDate returndate) { this.returnDate = returndate; } /** * @return Number of pending reservations if a copy is currently lent out. Optional. */ public String getReservations() { return reservations; } /** * @param reservations Number of pending reservations if a copy is currently lent out. * Optional. */ public void setReservations(String reservations) { this.reservations = reservations; } /** * @return Identification in the libraries' shelf system. Optional. */ public String getShelfmark() { return shelfmark; } /** * @param shelfmark Identification in the libraries' shelf system. Optional. */ public void setShelfmark(String shelfmark) { this.shelfmark = shelfmark; } /** * @return Reservation information for copy-based reservations. Intended for use in your {@link * de.geeksfactory.opacclient.apis.OpacApi#reservation(DetailedItem, Account, int, String)} * implementation. */ public String getResInfo() { return resInfo; } /** * @param resInfo Reservation information for copy-based reservations. Intended for use in your * {@link de.geeksfactory.opacclient.apis.OpacApi#reservation (DetailedItem, * Account, int, String)} implementation. */ public void setResInfo(String resInfo) { this.resInfo = resInfo; } /** * @return URL to an online copy */ public String getUrl() { return url; } /** * @param url URL to an online copy */ public void setUrl(String url) { this.url = url; } /** * Set property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above * @param value the value to set. Dates must be in ISO-8601 format (yyyy-MM-dd). */ public void set(String key, String value) { switch (key) { case "barcode": setBarcode(value); break; case "location": setLocation(value); break; case "department": setDepartment(value); break; case "branch": setBranch(value); break; case "status": setStatus(value); break; case "returndate": setReturnDate(new LocalDate(value)); break; case "reservations": setReservations(value); break; case "signature": setShelfmark(value); break; case "resinfo": setResInfo(value); break; case "url": setUrl(value); break; default: throw new IllegalArgumentException("key unknown"); } } /** * Set property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * For "returndate", the given {@link DateTimeFormatter} will be used to parse the date. * * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above * @param value the value to set. Dates must be in a format parseable by the given {@link * DateTimeFormatter}, otherwise an {@link IllegalArgumentException} will be * thrown. * @param fmt the {@link DateTimeFormatter} to use for parsing dates */ public void set(String key, String value, DateTimeFormatter fmt) { if (key.equals("returndate")) { if (!value.isEmpty()) { setReturnDate(fmt.parseLocalDate(value)); } } else { set(key, value); } } /** * Get property using the following keys: barcode, location, department, branch, status, * returndate, reservations, signature, resinfo, url * * Dates will be returned in ISO-8601 format (yyyy-MM-dd). If you supply an invalid key, an * {@link IllegalArgumentException} will be thrown. * * This method is used to simplify refactoring of old APIs from the Map&lt;String, String&gt; data * structure to this class. If you are creating a new API, you probably don't need to use it. * * @param key one of the keys mentioned above */ public String get(String key) { switch (key) { case "barcode": return getBarcode(); case "location": return getLocation(); case "department": return getDepartment(); case "branch": return getBranch(); case "status": return getStatus(); case "returndate": return getReturnDate() != null ? ISODateTimeFormat.date().print(getReturnDate()) : null; case "reservations": return getReservations(); case "signature": return getShelfmark(); case "resinfo": return getResInfo(); case "url": return getUrl(); default: throw new IllegalArgumentException("key unknown"); } } /** * @return boolean value indicating if this copy contains any data or not. */ public boolean notEmpty() { return getBarcode() != null || getLocation() != null || getDepartment() != null || getBranch() != null || getStatus() != null || getReturnDate() != null || getReservations() != null || getShelfmark() != null || getResInfo() != null || getIssue() != null || getUrl() != null; } @Override public String toString() { return "Copy{" + "barcode='" + barcode + '\'' + ", location='" + location + '\'' + ", department='" + department + '\'' + ", branch='" + branch + '\'' + ", status='" + status + '\'' + ", returnDate=" + returnDate + ", reservations='" + reservations + '\'' + ", shelfmark='" + shelfmark + '\'' + ", issue='" + issue + '\'' + ", resInfo='" + resInfo + '\'' + ", url='" + url + '\'' + '}'; } }
mit
purnama/birokrazy
src/main/java/id/birokrazy/model/Department.java
5175
package id.birokrazy.model; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Type; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Indexed; import javax.persistence.*; import java.util.List; /** * @author Arthur Purnama ([email protected]) */ @Entity @Indexed public class Department { @Id @GeneratedValue private Long id; @Version @Column(columnDefinition = "bigint default 0") private Long version; @Column(nullable = false, unique = true) private String uniqueName; @Column(nullable = false) @Field private String name; @Column private String description; @Column() @Type(type = "text") private String content; @Column(nullable = false) private Double rating; @Column(nullable = false) private Long reviews; @Column(nullable = false) private String address; @Column private String addressAdd; @Column private String district; @Column(nullable = false) private String zipCode; @Column(nullable = false) private String city; @Column(nullable = false) private String state; @Column private String telephone; @Column private String email; @Column private String openingHour; @Column private String longitude; @Column private String latitude; @OneToMany(mappedBy = "department") @OrderBy("id desc") @JsonIgnore private List<Review> reviewList; @ManyToMany(mappedBy = "departmentList") @OrderBy("id desc") @JsonIgnore private List<CivilService> civilServiceList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Double getRating() { return rating; } public void setRating(Double rating) { this.rating = rating; } public Long getReviews() { return reviews; } public void setReviews(Long reviews) { this.reviews = reviews; } public List<Review> getReviewList() { return reviewList; } public void setReviewList(List<Review> reviewList) { this.reviewList = reviewList; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getAddressAdd() { return addressAdd; } public void setAddressAdd(String addressAdd) { this.addressAdd = addressAdd; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public List<CivilService> getCivilServiceList() { return civilServiceList; } public void setCivilServiceList(List<CivilService> civilServiceList) { this.civilServiceList = civilServiceList; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getOpeningHour() { return openingHour; } public void setOpeningHour(String openingHour) { this.openingHour = openingHour; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getUniqueName() { return uniqueName; } public void setUniqueName(String uniqueName) { this.uniqueName = uniqueName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } @Field public String getLocation() { return address + " " + addressAdd + " " + district + " " + city + " " + state + " " + zipCode; } @Field public String getLocationName() { return district + ", " + city + " (" + zipCode + "), " + state; } }
mit
COOLHEMANTJAIN/MAILDETECTIVE
maildetective1.0/src/check/email/EMAILRDF.java
3829
/* The MIT License (MIT) Copyright (c) IIIT-DELHI authors: HEMANT JAIN "[email protected]" ANIRUDH NAIN Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ //To define all the properties needed to make the rdf of the email package check.email; import com.hp.hpl.jena.rdf.model.*; public class EMAILRDF { //Create a default model private static Model m = ModelFactory.createDefaultModel(); //Subject of the mail public static final Property MSGID = m.createProperty("MESSAGEID:" ); public static final Property MAILID = m.createProperty("MAILID:" ); public static final Property SUBJECT = m.createProperty("SUB:" ); //Sender of the mail public static final Property FROM = m.createProperty("FROM:" ); public static final Property FROMFULL = m.createProperty("FROMFULL:" ); public static final Property TOFULL = m.createProperty("TOFULL:" ); public static final Property EMAILID = m.createProperty("EMAILID:" ); //Receiver of the mail public static final Property TO = m.createProperty("TO:" ); //Return path public static final Property RETURN_PATH = m.createProperty("RETURNPATH:" ); //main contents of the mail public static final Property CONTENT = m.createProperty("CONTENT:" ); //format of the mail public static final Property FORMAT = m.createProperty("FORMAT:" ); //content type like html etc public static final Property CONTENT_TYPE = m.createProperty("CONTENTTYPE:" ); //encoding in bits public static final Property ENCODING = m.createProperty("ENCODING:" ); //date of the email public static final Property DATE = m.createProperty("DATE:" ); //CC of email public static final Property CC = m.createProperty("CC:" ); //BCC of email public static final Property BCC = m.createProperty("BCC:" ); //NAME OF THE SENDER public static final Property ATTACHEMENT_NAME = m.createProperty("ATTACHEMENTNAME:" ); public static final Property ATTACHEMENT_NO = m.createProperty("ATTACHEMENTNO:" ); //SIZE OF MAIL public static final Property MAIL_SIZE = m.createProperty("MAILSIZE:" ); //SIZE OF THE ATTACHEMENT of email public static final Property ATTACHEMENT_SIZE = m.createProperty("ATTACHEMENTSIZE:" ); //MAIL TO WHICH PARTICULAR MAIL HAVE REPLIED public static final Property IN_REPLYTO = m.createProperty("REPLIEDTO:" ); public static final Property IN_REPLYTONAME = m.createProperty("REPLIEDTONAME:" ); //FOLDER IN WHICH email EXISTS public static final Property FOLDER_NAME = m.createProperty("FOLDERNAME:" ); //UID of email public static final Property UID = m.createProperty("UID:" ); //name os receiver of email public static final Property REC_NAME = m.createProperty("RECIEVERS_NAME:" ); //name of sender of email public static final Property SEND_NAME = m.createProperty("SENDERNAME:" ); }
mit
chrisuehlinger/crocus
public/css/style.css
3683
@import url(https://fonts.googleapis.com/css?family=Pacifico); body { margin: 0; font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; } header { background: rgba(200, 200, 200, 0.5); width: 100%; position: fixed; top: 0; z-index: 100; box-shadow: 0px 5px 10px 5px rgba(200, 200, 200, 0.5); } header nav { text-align: center; display: flex; } h1 { font-family: 'Pacifico', cursive; font-size: 48px; margin: 0 20px; color: #A100FF; vertical-align: middle; } .twitter-typeahead { flex-grow: 5; margin: 0 5px; z-index: 101; } .twitter-typeahead .tt-menu { min-width: 100%; background: #fff; text-align: left; border: 1px solid black; border-radius: 5px; font-size: 20px; max-height: 500px; overflow: auto; } .twitter-typeahead .tt-menu .tt-suggestion { padding: 5px; } .twitter-typeahead .tt-menu .tt-suggestion.tt-cursor { background: #ddd; } #pathForm { display: flex; align-items: center; flex-grow: 5; margin-top: 20px; } #pathForm input { width: 100%; font-size: 20px; padding: 5px; border: none; box-sizing: border-box; } #pathForm button { vertical-align: middle; background: #ddd; border: 1px solid #999; margin: 10px; margin-right: 20px; padding: 5px 7px; border-radius: 5px; color: #A100FF; } .breadcrumbs { margin-top: 0px; padding: 0 20px 10px; } .breadcrumbs .crumb-wrapper { display: inline-block; vertical-align: middle; position: relative; margin: 5px 2px; padding-left: 15px; box-sizing: border-box; } .breadcrumbs .crumb-wrapper:before, .breadcrumbs .crumb-wrapper:after { content: ''; position: absolute; width: 0; height: 0; z-index: 100; left: 0px; border-style: solid; } .breadcrumbs .crumb-wrapper:before { border-width: 0 15px 15px 0; border-color: transparent #A100FF transparent transparent; top: 0; } .breadcrumbs .crumb-wrapper:after { border-width: 0 0 15px 15px; border-color: transparent transparent #A100FF transparent; bottom: 0; } .breadcrumbs .crumb-wrapper .crumb { display: inline-block; background: #A100FF; color: #fff; height: 20px; padding: 5px; z-index: 100; position: relative; } .breadcrumbs .crumb-wrapper .crumb:after { position: absolute; top: 0; right: -15px; content: ''; width: 0; height: 0; border-style: solid; border-width: 15px 0 15px 15px; border-color: transparent transparent transparent #A100FF; z-index: 100; } .breadcrumbs .size-label { display: inline-block; vertical-align: middle; margin-left: 20px; font-weight: 700; } main { position: relative; margin-top: 200px; } main .error-message { background: #ddd; font-size: 24px; font-family: Helvetica, sans-serif; padding: 30px; margin: 30px; border-radius: 10px; } main svg { position: absolute; top: 0; display: block; margin: 0px auto; } path { stroke: #fff; fill-rule: evenodd; fill: transparent; } .highlightable path.highlight { fill: rgba(255, 255, 255, 0.5); } .loading-indicator { position: fixed; top: 0; bottom: 0; left: 0; right: 0; display: flex; justify-content: center; align-items: center; z-index: 101; } .loading-indicator i { display: flex; justify-content: center; align-items: center; height: 200px; width: 200px; text-align: center; background: rgba(150, 150, 150, 0.25); border-radius: 200px; }
mit
davehorton/drachtio-server
deps/boost_1_77_0/doc/html/boost/accumulators/tag/wei_1_3_2_6_3_59_1_1_23_39.html
4533
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Struct template weighted_pot_tail_mean_prob</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp" title="Header &lt;boost/accumulators/statistics_fwd.hpp&gt;"> <link rel="prev" href="weighted_pot_tail_mean.html" title="Struct template weighted_pot_tail_mean"> <link rel="next" href="weighted_sum_of_variates.html" title="Struct template weighted_sum_of_variates"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="weighted_pot_tail_mean.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="weighted_sum_of_variates.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.accumulators.tag.wei_1_3_2_6_3_59_1_1_23_39"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template weighted_pot_tail_mean_prob</span></h2> <p>boost::accumulators::tag::weighted_pot_tail_mean_prob</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp" title="Header &lt;boost/accumulators/statistics_fwd.hpp&gt;">boost/accumulators/statistics_fwd.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> LeftRight<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="wei_1_3_2_6_3_59_1_1_23_39.html" title="Struct template weighted_pot_tail_mean_prob">weighted_pot_tail_mean_prob</a> <span class="special">:</span> <span class="keyword">public</span> boost::accumulators::depends_on&lt; weighted_peaks_over_threshold_prob&lt; LeftRight &gt;, weighted_pot_quantile_prob&lt; LeftRight &gt; &gt; <span class="special">{</span> <span class="special">}</span><span class="special">;</span></pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="weighted_pot_tail_mean.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics_fwd_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="weighted_sum_of_variates.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
mit
wf9a5m75/chainer-gogh
chainer-gogh.py
7054
import argparse import os import sys import numpy as np from PIL import Image import chainer from chainer import cuda import chainer.functions as F from chainer.functions import caffe from chainer import Variable, optimizers import pickle def subtract_mean(x0): x = x0.copy() x[0,0,:,:] -= 104 x[0,1,:,:] -= 117 x[0,2,:,:] -= 123 return x def add_mean(x0): x = x0.copy() x[0,0,:,:] += 104 x[0,1,:,:] += 117 x[0,2,:,:] += 123 return x def image_resize(img_file, width): gogh = Image.open(img_file) orig_w, orig_h = gogh.size[0], gogh.size[1] if orig_w>orig_h: new_w = width new_h = width*orig_h/orig_w gogh = np.asarray(gogh.resize((new_w,new_h)))[:,:,:3].transpose(2, 0, 1)[::-1].astype(np.float32) gogh = gogh.reshape((1,3,new_h,new_w)) print("image resized to: ", gogh.shape) hoge= np.zeros((1,3,width,width), dtype=np.float32) hoge[0,:,width-new_h:,:] = gogh[0,:,:,:] gogh = subtract_mean(hoge) else: new_w = width*orig_w/orig_h new_h = width gogh = np.asarray(gogh.resize((new_w,new_h)))[:,:,:3].transpose(2, 0, 1)[::-1].astype(np.float32) gogh = gogh.reshape((1,3,new_h,new_w)) print("image resized to: ", gogh.shape) hoge= np.zeros((1,3,width,width), dtype=np.float32) hoge[0,:,:,width-new_w:] = gogh[0,:,:,:] gogh = subtract_mean(hoge) return xp.asarray(gogh), new_w, new_h def save_image(img, width, new_w, new_h, it): def to_img(x): im = np.zeros((new_h,new_w,3)) im[:,:,0] = x[2,:,:] im[:,:,1] = x[1,:,:] im[:,:,2] = x[0,:,:] def clip(a): return 0 if a<0 else (255 if a>255 else a) im = np.vectorize(clip)(im).astype(np.uint8) Image.fromarray(im).save(args.out_dir+"/im_%05d.png"%it) if args.gpu>=0: img_cpu = add_mean(img.get()) else: img_cpu = add_mean(img) if width==new_w: to_img(img_cpu[0,:,width-new_h:,:]) else: to_img(img_cpu[0,:,:,width-new_w:]) def nin_forward(x): y0 = F.relu(model.conv1(x)) y1 = model.cccp2(F.relu(model.cccp1(y0))) x1 = F.relu(model.conv2(F.average_pooling_2d(F.relu(y1), 3, stride=2))) y2 = model.cccp4(F.relu(model.cccp3(x1))) x2 = F.relu(model.conv3(F.average_pooling_2d(F.relu(y2), 3, stride=2))) y3 = model.cccp6(F.relu(model.cccp5(x2))) x3 = F.relu(getattr(model,"conv4-1024")(F.dropout(F.average_pooling_2d(F.relu(y3), 3, stride=2), train=False))) return [y0,x1,x2,x3] def vgg_forward(x): y1 = model.conv1_2(F.relu(model.conv1_1(x))) x1 = F.average_pooling_2d(F.relu(y1), 2, stride=2) y2 = model.conv2_2(F.relu(model.conv2_1(x1))) x2 = F.average_pooling_2d(F.relu(y2), 2, stride=2) y3 = model.conv3_3(F.relu(model.conv3_2(F.relu(model.conv3_1(x2))))) x3 = F.average_pooling_2d(F.relu(y3), 2, stride=2) y4 = model.conv4_3(F.relu(model.conv4_2(F.relu(model.conv4_1(x3))))) # x4 = F.average_pooling_2d(F.relu(y4), 2, stride=2) # y5 = model.conv5_3(F.relu(model.conv5_2(F.relu(model.conv5_1(x4))))) return [y1,y2,y3,y4] def get_matrix(y): ch = y.data.shape[1] wd = y.data.shape[2] gogh_y = F.reshape(y, (ch,wd**2)) gogh_matrix = F.matmul(gogh_y, gogh_y, transb=True)/np.float32(ch*wd**2) return gogh_matrix class Clip(chainer.Function): def forward(self, x): x = x[0] ret = cuda.elementwise( 'T x','T ret', ''' ret = x<-100?-100:(x>100?100:x); ''','clip')(x) return ret def generate_image(img_orig, img_style, width, nw, nh, max_iter, lr, alpha, beta, img_gen=None): mid_orig = nin_forward(Variable(img_orig)) style_mats = [get_matrix(y) for y in nin_forward(Variable(img_style))] if img_gen is None: if args.gpu >= 0: img_gen = xp.random.uniform(-20,20,(1,3,width,width),dtype=np.float32) else: img_gen = np.random.uniform(-20,20,(1,3,width,width)).astype(np.float32) x = Variable(img_gen) xg = xp.zeros_like(x.data) optimizer = optimizers.Adam(alpha=lr) optimizer.setup((img_gen,xg)) for i in range(max_iter): x = Variable(img_gen) y = nin_forward(x) optimizer.zero_grads() L = Variable(xp.zeros((), dtype=np.float32)) for l in range(4): ch = y[l].data.shape[1] wd = y[l].data.shape[2] gogh_y = F.reshape(y[l], (ch,wd**2)) gogh_matrix = F.matmul(gogh_y, gogh_y, transb=True)/np.float32(ch*wd**2) L1 = np.float32(alpha[l])*F.mean_squared_error(y[l], Variable(mid_orig[l].data)) L2 = np.float32(beta[l])*F.mean_squared_error(gogh_matrix, Variable(style_mats[l].data))/np.float32(4) L += L1+L2 if i%100==0: print i,l,L1.data,L2.data L.backward() xg += x.grad optimizer.update() tmp_shape = img_gen.shape if args.gpu >= 0: img_gen += Clip().forward(img_gen).reshape(tmp_shape) - img_gen else: def clip(x): return -100 if x<-100 else (100 if x>100 else x) img_gen += np.vectorize(clip)(img_gen).reshape(tmp_shape) - img_gen if i%50==0: save_image(img_gen, W, nw, nh, i) parser = argparse.ArgumentParser( description='A Neural Algorithm of Artistic Style') parser.add_argument('--model', '-m', default='nin_imagenet.caffemodel', help='model file') parser.add_argument('--orig_img', '-i', default='orig.png', help='Original image') parser.add_argument('--style_img', '-s', default='style.png', help='Style image') parser.add_argument('--out_dir', '-o', default='output', help='Output directory') parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)') parser.add_argument('--iter', default=5000, type=int, help='number of iteration') parser.add_argument('--lr', default=4.0, type=float, help='learning rate') parser.add_argument('--lam', default=0.005, type=float, help='original image weight / style weight ratio') parser.add_argument('--width', '-w', default=435, type=int, help='image width, height') args = parser.parse_args() try: os.mkdir(args.out_dir) except: pass if args.gpu >= 0: cuda.check_cuda_available() cuda.get_device(args.gpu).use() xp = cuda.cupy else: xp = np chainer.Function.type_check_enable = False print "load model... %s"%args.model func = caffe.CaffeFunction(args.model) model = func.fs if args.gpu>=0: model.to_gpu() W = args.width img_gogh,_,_ = image_resize(args.style_img, W) img_hongo,nw,nh = image_resize(args.orig_img, W) generate_image(img_hongo, img_gogh, W, nw, nh, img_gen=None, max_iter=args.iter, lr=args.lr, alpha=[args.lam * x for x in [0,0,1,1]], beta=[1,1,1,1])
mit
andrewjadams3/Klassewerk
app/assets/javascripts/controllers/submissions_response_controller.js
648
App.SubmissionsResponseController = Ember.ObjectController.extend({ actions: { saveNotes: function() { var onSuccess = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box'>Your notes were saved!<a class='close'>&times;</a></div>"); }; var onFail = function(post) { $(".alert-box").remove(); $("textarea").before("<div data-alert class='alert-box alert'>Uh oh! Something went wrong...<a class='close'>&times;</a></div>"); }; var model = this.get('model'); model.save().then(onSuccess, onFail); return model; } } });
mit
j-froehlich/magento2_wk
vendor/magento/framework/App/Test/Unit/SetupInfoTest.php
5963
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\App\Test\Unit; use \Magento\Framework\App\SetupInfo; class SetupInfoTest extends \PHPUnit_Framework_TestCase { /** * A default fixture * * @var array */ private static $fixture = ['DOCUMENT_ROOT' => '/doc/root', 'SCRIPT_FILENAME' => '/doc/root/dir/file.php']; /** * @param array $server * @param string $expectedError * @dataProvider constructorExceptionsDataProvider */ public function testConstructorExceptions($server, $expectedError) { $this->setExpectedException('\InvalidArgumentException', $expectedError); new SetupInfo($server); } public function constructorExceptionsDataProvider() { $docRootErr = 'DOCUMENT_ROOT variable is unavailable.'; $projectRootErr = 'Project root cannot be automatically detected.'; return [ [[], $docRootErr], [['DOCUMENT_ROOT' => ''], $docRootErr], [['DOCUMENT_ROOT' => '/foo'], $projectRootErr], [['DOCUMENT_ROOT' => '/foo', 'SCRIPT_FILENAME' => ''], $projectRootErr], ]; } /** * @param array $server * @param string $expected * @dataProvider getUrlDataProvider */ public function testGetUrl($server, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->getUrl()); } /** * @return array */ public function getUrlDataProvider() { return [ [ self::$fixture, '/setup/' ], [ self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => 'install'], '/install/', ], [ self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL => 'http://example.com/'], 'http://example.com/', ], ]; } /** * @param array $server * @param string $expected * @dataProvider getProjectUrlDataProvider */ public function testGetProjectUrl($server, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->getProjectUrl()); } /** * @return array */ public function getProjectUrlDataProvider() { return [ [self::$fixture, ''], [self::$fixture + ['HTTP_HOST' => ''], ''], [ ['DOCUMENT_ROOT' => '/foo/bar', 'SCRIPT_FILENAME' => '/other/baz.php', 'HTTP_HOST' => 'example.com'], 'http://example.com/' ], [self::$fixture + ['HTTP_HOST' => 'example.com'], 'http://example.com/dir/'], [ ['DOCUMENT_ROOT' => '/foo/bar', 'SCRIPT_FILENAME' => '/foo/bar/baz.php', 'HTTP_HOST' => 'example.com'], 'http://example.com/' ], ]; } /** * @param array $server * @param string $projectRoot * @param string $expected * @dataProvider getDirDataProvider */ public function testGetDir($server, $projectRoot, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->getDir($projectRoot)); } /** * @return array */ public function getDirDataProvider() { return [ [ self::$fixture, '/test/root', '/test/root/setup', ], [ self::$fixture, '/test/root/', '/test/root/setup', ], [ self::$fixture + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '/install/'], '/test/', '/test/install', ], ]; } /** * @param array $server * @param bool $expected * @dataProvider isAvailableDataProvider */ public function testIsAvailable($server, $expected) { $info = new SetupInfo($server); $this->assertEquals($expected, $info->isAvailable()); } /** * @return array */ public function isAvailableDataProvider() { $server = ['DOCUMENT_ROOT' => __DIR__, 'SCRIPT_FILENAME' => __FILE__]; return [ 'root = doc root, but no "setup" sub-directory' => [ $server, // it will look for "setup/" sub-directory, but won't find anything false ], 'root = doc root, nonexistent sub-directory' => [ $server + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => 'nonexistent'], false ], 'root = doc root, existent sub-directory' => [ $server + [SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files'], true ], 'root within doc root, existent sub-directory' => [ [ 'DOCUMENT_ROOT' => dirname(__DIR__), 'SCRIPT_FILENAME' => __FILE__, SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files' ], true ], 'root outside of doc root, existent sub-directory' => [ [ 'DOCUMENT_ROOT' => __DIR__, 'SCRIPT_FILENAME' => dirname(dirname(__DIR__)) . '/foo.php', SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => basename(__DIR__) ], false ], 'root within doc root, existent sub-directory, trailing slash' => [ [ 'DOCUMENT_ROOT' => dirname(__DIR__) . DIRECTORY_SEPARATOR, 'SCRIPT_FILENAME' => __FILE__, SetupInfo::PARAM_NOT_INSTALLED_URL_PATH => '_files' ], true ], ]; } }
mit
MVC-todo-list/starter-todo4
application/controllers/Views.php
2696
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Views extends Application { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/ * - or - * http://example.com/welcome/index * * So any other public methods not prefixed with an underscore will * map to /welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->data['pagetitle'] = 'Ordered TODO List'; $tasks = $this->tasks->all(); // get all the tasks $this->data['content'] = 'Ok'; // so we don't need pagebody $this->data['leftside'] = $this->makePrioritizedPanel($tasks); $this->data['rightside'] = $this->makeCategorizedPanel($tasks); $this->render('template_secondary'); } function makePrioritizedPanel($tasks) { $parms = ['display_tasks' => []]; // extract the undone tasks foreach ($tasks as $task) { if ($task->status != 2) $undone[] = $task; } // order them by priority usort($undone, "orderByPriority"); // substitute the priority name foreach ($undone as $task) $task->priority = $this->app->priority($task->priority); foreach ($undone as $task) $converted[] = (array) $task; // and then pass them on $parms = ['display_tasks' => $converted]; // INSERT the next two lines $role = $this->session->userdata('userrole'); $parms['completer'] = ($role == ROLE_OWNER) ? '/views/complete' : '#'; return $this->parser->parse('by_priority', $parms, true); } function makeCategorizedPanel($tasks) { $parms = ['display_tasks' => $this->tasks->getCategorizedTasks()]; return $this->parser->parse('by_category', $parms, true); } // complete flagged items function complete() { $role = $this->session->userdata('userrole'); if ($role != ROLE_OWNER) redirect('/work'); // loop over the post fields, looking for flagged tasks foreach ($this->input->post() as $key => $value) { if (substr($key, 0, 4) == 'task') { // find the associated task $taskid = substr($key, 4); $task = $this->tasks->get($taskid); $task->status = 2; // complete $this->tasks->update($task); } } $this->index(); } } // return -1, 0, or 1 of $a's priority is higher, equal to, or lower than $b's function orderByPriority($a, $b) { if ($a->priority > $b->priority) return -1; elseif ($a->priority < $b->priority) return 1; else return 0; } ?>
mit
derberg/zlicz
test/testCases/walkDir/walkDirBlacklistDirs.js
1491
'use strict'; const helpers = require('../../../src/helpers'); const assert = require('assert'); const arghun = require('../../../'); const opt = { blDir: ['even-more', 'crap', 'A-characters'] }; const expected = { './test/testData/testDirectory/B-characters': 6, './test/testData/testDirectory/B-characters/more-B': 3, './test/testData/testDirectory/B-characters/more-B/inside-B': 2, './test/testData/testDirectory/B-characters/more-B/inside-B/custom': 4, './test/testData/testDirectory/B-characters/my-man': 1, './test/testData/testDirectory/C-characters': 6, './test/testData/testDirectory/C-characters/my-man': 2, './test/testData/testDirectory/D-characters': 7, './test/testData/testDirectory/D-characters/more-and-more-D': 6, './test/testData/testDirectory/D-characters/my-man': 1, './test/testData/testDirectory/E-characters': 12, './test/testData/testDirectory/F-characters': 5, './test/testData/testDirectory/F-characters/moremoremore': 3, './test/testData/testDirectory/F-characters/my-man': 1, './test/testData/testDirectory/G-characters': 7 }; async function walkDirBlacklistDirs(path) { try { const result = await arghun.walkDir(path, opt); assert.deepEqual(result, expected, 'walkDir failed with dirs blacklist'); helpers.log('walkDir with dirs blacklist - successful'); } catch(err) { helpers.log(err); throw new Error(err); } } module.exports = walkDirBlacklistDirs;
mit
Matt-Jensen/ember-cli-g-maps
tests/dummy/app/pods/heatmap/route.js
499
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller) { controller.set('setupRoutes', [ { label: false, links: [ { href: 'heatmap.index', text: 'Setup' }, { href: 'heatmap.properties', text: 'Properties' }, { href: 'heatmap.marker', text: 'Heatmap Marker' } ] } ]); } });
mit
wyrover/SharpDX
Source/SharpDX.Direct2D1/WIC/ImageEncoder.cs
1969
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if DIRECTX11_1 namespace SharpDX.WIC { public partial class ImageEncoder { /// <summary> /// Creates a new image encoder object. /// </summary> /// <param name="factory">The WIC factory.</param> /// <param name="d2dDevice">The <see cref="Direct2D1.Device" /> object on which the corresponding image encoder is created.</param> /// <msdn-id>hh880849</msdn-id> /// <unmanaged>HRESULT IWICImagingFactory2::CreateImageEncoder([In] ID2D1Device* pD2DDevice,[In] IWICImageEncoder** ppWICImageEncoder)</unmanaged> /// <unmanaged-short>IWICImagingFactory2::CreateImageEncoder</unmanaged-short> public ImageEncoder(ImagingFactory2 factory, Direct2D1.Device d2dDevice) { factory.CreateImageEncoder(d2dDevice, this); } } } #endif
mit
dblock/dotnetinstaller
dotNetInstaller/ComponentsList.cpp
5456
#include "StdAfx.h" #include "ComponentsList.h" #include "dotNetInstallerDlg.h" CComponentsList::CComponentsList() : m_pConfiguration(NULL) , m_pExecuteCallback(NULL) { } IMPLEMENT_DYNAMIC(CComponentsList, CCheckListBox) BEGIN_MESSAGE_MAP(CComponentsList, CCheckListBox) ON_CONTROL_REFLECT(CLBN_CHKCHANGE, OnCheckChange) ON_WM_LBUTTONDBLCLK() END_MESSAGE_MAP() void CComponentsList::OnCheckChange() { this->Invalidate(); } void CComponentsList::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC); if (((LONG)(lpDrawItemStruct->itemID) >= 0) && (lpDrawItemStruct->itemAction & (ODA_DRAWENTIRE | ODA_SELECT))) { int cyItem = GetItemHeight(lpDrawItemStruct->itemID); BOOL fDisabled = !IsWindowEnabled() || !IsEnabled(lpDrawItemStruct->itemID); COLORREF newTextColor = fDisabled ? RGB(0, 0, 0) : GetSysColor(COLOR_WINDOWTEXT); // light gray COLORREF oldTextColor = pDC->SetTextColor(newTextColor); COLORREF newBkColor = GetSysColor(COLOR_WINDOW); COLORREF oldBkColor = pDC->SetBkColor(newBkColor); if (newTextColor == newBkColor) newTextColor = RGB(0xC0, 0xC0, 0xC0); // dark gray if (!fDisabled && ((lpDrawItemStruct->itemState & ODS_SELECTED) != 0)) { pDC->SetTextColor(GetSysColor(COLOR_HIGHLIGHTTEXT)); pDC->SetBkColor(GetSysColor(COLOR_HIGHLIGHT)); } if (m_cyText == 0) VERIFY(cyItem >= CalcMinimumItemHeight()); CString strText; GetText(lpDrawItemStruct->itemID, strText); pDC->ExtTextOut(lpDrawItemStruct->rcItem.left + 5, lpDrawItemStruct->rcItem.top + max(0, (cyItem - m_cyText) / 2), ETO_OPAQUE, &(lpDrawItemStruct->rcItem), strText, strText.GetLength(), NULL); int nCheck = GetCheck(lpDrawItemStruct->itemID); if (fDisabled && nCheck == 0) { CRect checkbox(0, lpDrawItemStruct->rcItem.top, lpDrawItemStruct->rcItem.left, lpDrawItemStruct->rcItem.bottom); COLORREF newBkColor = GetSysColor(COLOR_WINDOW); CBrush brush(newBkColor); pDC->FillRect(& checkbox, & brush); } pDC->SetTextColor(oldTextColor); pDC->SetBkColor(oldBkColor); } if ((lpDrawItemStruct->itemAction & ODA_FOCUS) != 0) pDC->DrawFocusRect(&(lpDrawItemStruct->rcItem)); } void CComponentsList::PreDrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CCheckListBox::PreDrawItem(lpDrawItemStruct); } void CComponentsList::AddComponent(const ComponentPtr& component) { int id = AddString(component->description.c_str()); SetItemDataPtr(id, get(component)); if (component->checked) SetCheck(id, 1); if (component->disabled) Enable(id, 0); CDC * pDC = GetDC(); ASSERT(pDC); CSize size = pDC->GetTextExtent(component->GetDisplayName().c_str()); if ((size.cx > 0) && (GetHorizontalExtent() < size.cx)) { SetHorizontalExtent(size.cx); } ReleaseDC(pDC); } void CComponentsList::OnLButtonDblClk(UINT nFlags, CPoint point) { if (nFlags & MK_CONTROL && nFlags && MK_LBUTTON) { BOOL bOutside = false; UINT uiItem = ItemFromPoint(point, bOutside); if (! bOutside) { ComponentPtr component = m_pConfiguration->GetComponentPtr(static_cast<Component*>(GetItemDataPtr(uiItem))); Exec(component); if (m_pExecuteCallback) { m_pExecuteCallback->LoadComponentsList(false); } } } else if (nFlags & MK_SHIFT && nFlags && MK_LBUTTON) { BOOL bOutside = false; UINT uiItem = ItemFromPoint(point, bOutside); if (! bOutside) { ComponentPtr component = m_pConfiguration->GetComponentPtr(static_cast<Component*>(GetItemDataPtr(uiItem))); SetCheck(uiItem, ! GetCheck(uiItem)); } } } void CComponentsList::Exec(const ComponentPtr& component) { try { if (m_pExecuteCallback) { m_pExecuteCallback->OnExecBegin(); } LOG(L"--- Component '" << component->id << L"' (" << component->GetDisplayName() << L"): EXECUTING"); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecBegin(component)) return; component->Exec(); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecWait(component)) return; component->Wait(); LOG(L"*** Component '" << component->id << L"' (" << component->GetDisplayName() << L"): SUCCESS"); if (m_pExecuteCallback && ! m_pExecuteCallback->OnComponentExecSuccess(component)) return; } catch(std::exception& ex) { LOG(L"*** Component '" << component->id << L"' (" << component->GetDisplayName() << L"): ERROR - " << DVLib::string2wstring(ex.what())); DniMessageBox::Show(DVLib::string2wstring(ex.what()).c_str(), MB_OK | MB_ICONSTOP); } } void CComponentsList::SetExecuteCallback(CdotNetInstallerDlg * pExec) { m_pExecuteCallback = pExec; } void CComponentsList::Load(InstallConfiguration * pConfiguration) { m_pConfiguration = pConfiguration; }
mit
bugix/java-plist-serializer
src/main/java/pl/maciejwalkowiak/plist/handler/MapHandler.java
1980
/* * Copyright (c) 2012 Maciej Walkowiak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package pl.maciejwalkowiak.plist.handler; import pl.maciejwalkowiak.plist.PlistSerializerImpl; import pl.maciejwalkowiak.plist.XMLHelper; import java.util.Map; /** * @author Maciej Walkowiak */ public class MapHandler extends AbstractHandler { public MapHandler(PlistSerializerImpl plistSerializer) { super(plistSerializer); } @Override String doHandle(Object object) { Map<String, Object> map = (Map<String, Object>) object; StringBuilder result = new StringBuilder(); for (Map.Entry<String, Object> entry : map.entrySet()) { result.append(XMLHelper.wrap(plistSerializer.getNamingStrategy().fieldNameToKey(entry.getKey())).with("key")); result.append(plistSerializer.serialize(entry.getValue())); } return XMLHelper.wrap(result).with("dict"); } public boolean supports(Object object) { return object instanceof Map; } }
mit
sharonikechi/babaomo
BabaOmo/Resources.Designer.cs
3160
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BabaOmo { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BabaOmo.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized resource of type System.Byte[]. /// </summary> internal static byte[] NIG_Data { get { object obj = ResourceManager.GetObject("NIG_Data", resourceCulture); return ((byte[])(obj)); } } } }
mit
FoundOPS/phonegap-android-meteor-boilerplate
meteor/todolist.css
189
/* CSS declarations go here */ * { font-family: Helvetica, arial, sans-serif; font-size: 16px; } input { } .todolist { padding: 5px; } .todolist .item { border: solid green 1px; }
mit
DeviceConnect/DeviceConnect-Android
dConnectSDK/dConnectLibStreaming/libmedia/src/main/java/org/deviceconnect/android/libmedia/streaming/mpeg2ts/FrameType.java
380
package org.deviceconnect.android.libmedia.streaming.mpeg2ts; /** * フレームのタイプを定義します. */ enum FrameType { /** * 音声のフレームタイプを定義. */ AUDIO, /** * 映像のフレームタイプを定義. */ VIDEO, /** * 音声と映像の混合のフレームタイプを定義. */ MIXED }
mit
svgorbunov/Mariculture
src/main/java/mariculture/core/helpers/BlockHelper.java
7041
package mariculture.core.helpers; import java.util.Random; import mariculture.core.tile.base.TileMultiBlock; import mariculture.core.util.Fluids; import mariculture.core.util.IItemDropBlacklist; import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; public class BlockHelper { public static boolean isWater(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Blocks.water; } public static boolean isHPWater(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Fluids.getFluidBlock("hp_water"); } public static boolean isLava(World world, int x, int y, int z) { return world.getBlock(x, y, z) == Blocks.lava; } public static boolean isFishLiveable(World world, int x, int y, int z) { if (world.provider.isHellWorld) return isLava(world, x, y, z); return isWater(world, x, y, z); } public static boolean isFishable(World world, int x, int y, int z) { return isWater(world, x, y, z) || isLava(world, x, y, z) && world.provider.isHellWorld; } public static boolean isAir(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.isAirBlock(x, y, z); } catch (Exception e) {} } return false; } public static void setBlock(World world, int x, int y, int z, Block block, int meta) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { world.setBlock(x, y, z, block, meta, 3); } catch (Exception e) {} } } public static Block getBlock(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.getBlock(x, y, z); } catch (Exception e) {} } return Blocks.stone; } public static int getMeta(World world, int x, int y, int z) { if (world.getChunkProvider().chunkExists(x >> 4, z >> 4)) { try { return world.getBlockMetadata(x, y, z); } catch (Exception e) {} } return -1; } public static boolean chunkExists(World world, int x, int z) { return world.getChunkProvider().chunkExists(x >> 4, z >> 4); } public static String getName(ItemStack stack) { return stack != null ? stack.getItem().getItemStackDisplayName(stack) : ""; } public static String getName(TileEntity tile) { return tile != null ? getName(new ItemStack(tile.getBlockType(), 1, tile.getBlockMetadata())) : ""; } public static ForgeDirection rotate(ForgeDirection dir, int num) { if (dir == ForgeDirection.NORTH) return ForgeDirection.EAST; if (dir == ForgeDirection.EAST) return num == 2 ? ForgeDirection.NORTH : ForgeDirection.SOUTH; if (dir == ForgeDirection.SOUTH) return ForgeDirection.WEST; if (dir == ForgeDirection.WEST) return num == 6 ? ForgeDirection.UP : ForgeDirection.NORTH; if (dir == ForgeDirection.UP) return ForgeDirection.DOWN; return ForgeDirection.NORTH; } public static ForgeDirection rotate(ForgeDirection dir) { return rotate(dir, 6); } public static void dropItems(World world, int x, int y, int z) { Random rand = world.rand; TileEntity tile = world.getTileEntity(x, y, z); if (!(tile instanceof IInventory)) return; if (tile instanceof TileMultiBlock) { TileMultiBlock multi = (TileMultiBlock) tile; if (multi.master != null) if (!multi.isMaster()) return; } IInventory inventory = (IInventory) tile; for (int i = 0; i < inventory.getSizeInventory(); i++) { boolean drop = true; if (tile instanceof IItemDropBlacklist) { drop = ((IItemDropBlacklist) tile).doesDrop(i); } if (drop) { ItemStack item = inventory.getStackInSlot(i); if (item != null && item.stackSize > 0) { item = item.copy(); inventory.decrStackSize(i, 1); float rx = rand.nextFloat() * 0.6F + 0.1F; float ry = rand.nextFloat() * 0.6F + 0.1F; float rz = rand.nextFloat() * 0.6F + 0.1F; EntityItem entity_item = new EntityItem(world, x + rx, y + ry, z + rz, new ItemStack(item.getItem(), item.stackSize, item.getItemDamage())); if (item.hasTagCompound()) { entity_item.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy()); } float factor = 0.05F; entity_item.motionX = rand.nextGaussian() * factor; entity_item.motionY = rand.nextGaussian() * factor + 0.2F; entity_item.motionZ = rand.nextGaussian() * factor; world.spawnEntityInWorld(entity_item); item.stackSize = 0; } } } } private static boolean removeBlock(World world, EntityPlayerMP player, int x, int y, int z) { Block block = world.getBlock(x, y, z); int l = world.getBlockMetadata(x, y, z); block.onBlockHarvested(world, x, y, z, l, player); boolean flag = block.removedByPlayer(world, player, x, y, z, true); if (flag) { block.onBlockDestroyedByPlayer(world, x, y, z, l); } return flag; } public static void destroyBlock(World world, int x, int y, int z) { destroyBlock(world, x, y, z, null, null); } public static void destroyBlock(World world, int x, int y, int z, Block required, ItemStack held) { if (!(world instanceof WorldServer)) return; Block block = world.getBlock(x, y, z); if (required != null && block != required) return; if (block.getBlockHardness(world, x, y, z) < 0.0F) return; FakePlayer player = PlayerHelper.getFakePlayer(world); if (player != null && held != null) { player.setCurrentItemOrArmor(0, held.copy()); } int l = world.getBlockMetadata(x, y, z); world.playAuxSFXAtEntity(player, 2001, x, y, z, Block.getIdFromBlock(block) + (world.getBlockMetadata(x, y, z) << 12)); boolean flag = removeBlock(world, player, x, y, z); if (flag) { block.harvestBlock(world, player, x, y, z, l); } return; } }
mit
c933103/KC3Kai
src/pages/strategy/tabs/aircraft/aircraft.js
10605
(function(){ "use strict"; KC3StrategyTabs.aircraft = new KC3StrategyTab("aircraft"); KC3StrategyTabs.aircraft.definition = { tabSelf: KC3StrategyTabs.aircraft, squadNames: {}, _items: {}, _holders: {}, _slotNums: {}, /* INIT Prepares static data needed ---------------------------------*/ init :function(){ }, /* RELOAD Prepares latest player data ---------------------------------*/ reload :function(){ var self = this; this._items = {}; this._holders = {}; this._slotNums = {}; KC3ShipManager.load(); KC3GearManager.load(); PlayerManager.loadBases(); // Get squad names if(typeof localStorage.planes == "undefined"){ localStorage.planes = "{}"; } this.squadNames = JSON.parse(localStorage.planes); // Compile equipment holders var ctr, ThisItem, MasterItem, ThisShip, MasterShip; for(ctr in KC3ShipManager.list){ this.checkShipSlotForItemHolder(0, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(1, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(2, KC3ShipManager.list[ctr]); this.checkShipSlotForItemHolder(3, KC3ShipManager.list[ctr]); // No plane is able to be equipped in ex-slot for now } for(ctr in PlayerManager.bases){ this.checkLbasSlotForItemHolder(PlayerManager.bases[ctr]); } for(ctr in PlayerManager.baseConvertingSlots){ this._holders["s"+PlayerManager.baseConvertingSlots[ctr]] = "LbasMoving"; } // Compile ships on Index var thisType, thisSlotitem, thisGearInstance; function GetMyHolder(){ return self._holders["s"+this.itemId]; } function NoHolder(){ return false; } for(ctr in KC3GearManager.list){ ThisItem = KC3GearManager.list[ctr]; MasterItem = ThisItem.master(); if(!MasterItem) continue; //if(KC3GearManager.carrierBasedAircraftType3Ids.indexOf(MasterItem.api_type[3]) == -1) continue; // Add holder to the item object temporarily via function return if(typeof this._holders["s"+ThisItem.itemId] != "undefined"){ ThisItem.MyHolder = GetMyHolder; }else{ ThisItem.MyHolder = NoHolder; } // Check if slotitem_type is filled if(typeof this._items["t"+MasterItem.api_type[3]] == "undefined"){ this._items["t"+MasterItem.api_type[3]] = []; } thisType = this._items["t"+MasterItem.api_type[3]]; // Check if slotitem_id is filled if(typeof this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] == "undefined"){ this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id] = { id: ThisItem.masterId, type_id: MasterItem.api_type[3], english: ThisItem.name(), japanese: MasterItem.api_name, stats: { fp: MasterItem.api_houg, tp: MasterItem.api_raig, aa: MasterItem.api_tyku, ar: MasterItem.api_souk, as: MasterItem.api_tais, ev: MasterItem.api_houk, ls: MasterItem.api_saku, dv: MasterItem.api_baku, ht: MasterItem.api_houm, rn: MasterItem.api_leng, or: MasterItem.api_distance }, instances: [] }; } thisSlotitem = this._items["t"+MasterItem.api_type[3]]["s"+MasterItem.api_id]; thisSlotitem.instances.push(ThisItem); } // sort this_items var sortMasterItem = function(a, b){ var attr; switch( i ){ case 't6': case 6: attr = 'aa'; break; case 't7': case 7: attr = 'dv'; break; case 't8': case 8: attr = 'tp'; break; case 't9': case 9: attr = 'ls'; break; case 't10': case 10: attr = 'dv'; break; default: attr = 'aa'; break; } if( b.stats[attr] == a.stats[attr] ) return b.stats.ht - a.stats.ht; return b.stats[attr] - a.stats[attr]; }; var sortSlotItem = function(a,b){ return b.ace - a.ace; }; for( var i in this._items ){ // make elements in this._items true Array for( var j in this._items[i] ){ // sort item by ace this._items[i][j].instances.sort(sortSlotItem); this._items[i].push( this._items[i][j] ); delete this._items[i][j]; } // sort MasterItem by stat this._items[i].sort(sortMasterItem); } }, /* Check a ship's equipment slot of an item is equipped --------------------------------------------*/ checkShipSlotForItemHolder :function(slot, ThisShip){ if(ThisShip.items[slot] > 0){ this._holders["s"+ThisShip.items[slot]] = ThisShip; this._slotNums["s"+ThisShip.items[slot]] = slot; } }, /* Check LBAS slot of an aircraft is equipped --------------------------------------------*/ checkLbasSlotForItemHolder :function(LandBase){ for(var squad in LandBase.planes){ if(LandBase.planes[squad].api_slotid > 0){ this._holders["s"+LandBase.planes[squad].api_slotid] = LandBase; } } }, /* EXECUTE Places data onto the interface ---------------------------------*/ execute :function(){ var self = this; $(".tab_aircraft .item_type").on("click", function(){ KC3StrategyTabs.gotoTab(null, $(this).data("type")); }); $(".tab_aircraft .item_list").on("change", ".instance_name input", function(){ self.squadNames["p"+$(this).attr("data-gearId")] = $(this).val(); localStorage.planes = JSON.stringify(self.squadNames); }); if(!!KC3StrategyTabs.pageParams[1]){ this.showType(KC3StrategyTabs.pageParams[1]); } else { this.showType($(".tab_aircraft .item_type").first().data("type")); } }, /* Show slotitem type --------------------------------------------*/ showType :function(type_id){ $(".tab_aircraft .item_type").removeClass("active"); $(".tab_aircraft .item_type[data-type={0}]".format(type_id)).addClass("active"); $(".tab_aircraft .item_list").html(""); var ctr, ThisType, ItemElem, ThisSlotitem; var gearClickFunc = function(e){ KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt")); }; var lbasPlanesFilter = function(s){ return s.api_slotid === ThisPlane.itemId; }; for(ctr in this._items["t"+type_id]){ ThisSlotitem = this._items["t"+type_id][ctr]; ItemElem = $(".tab_aircraft .factory .slotitem").clone().appendTo(".tab_aircraft .item_list"); $(".icon img", ItemElem).attr("src", "../../assets/img/items/"+type_id+".png"); $(".icon img", ItemElem).attr("alt", ThisSlotitem.id); $(".icon img", ItemElem).click(gearClickFunc); $(".english", ItemElem).text(ThisSlotitem.english); $(".japanese", ItemElem).text(ThisSlotitem.japanese); this.slotitem_stat(ItemElem, ThisSlotitem, "fp"); this.slotitem_stat(ItemElem, ThisSlotitem, "tp"); this.slotitem_stat(ItemElem, ThisSlotitem, "aa"); this.slotitem_stat(ItemElem, ThisSlotitem, "ar"); this.slotitem_stat(ItemElem, ThisSlotitem, "as"); this.slotitem_stat(ItemElem, ThisSlotitem, "ev"); this.slotitem_stat(ItemElem, ThisSlotitem, "ls"); this.slotitem_stat(ItemElem, ThisSlotitem, "dv"); this.slotitem_stat(ItemElem, ThisSlotitem, "ht"); this.slotitem_stat(ItemElem, ThisSlotitem, "rn"); this.slotitem_stat(ItemElem, ThisSlotitem, "or"); var PlaneCtr, ThisPlane, PlaneBox, rankLines, ThisCapacity; for(PlaneCtr in ThisSlotitem.instances){ ThisPlane = ThisSlotitem.instances[PlaneCtr]; PlaneBox = $(".tab_aircraft .factory .instance").clone(); $(".instances", ItemElem).append(PlaneBox); $(".instance_icon img", PlaneBox).attr("src", "../../assets/img/items/"+type_id+".png"); if(ThisPlane.stars > 0){ $(".instance_star span", PlaneBox).text( ThisPlane.stars > 9 ? "m" : ThisPlane.stars); } else { $(".instance_star img", PlaneBox).hide(); } if(ThisPlane.ace > 0){ $(".instance_chev img", PlaneBox).attr("src", "../../assets/img/client/achev/"+ThisPlane.ace+".png"); }else{ $(".instance_chev img", PlaneBox).hide(); } $(".instance_name input", PlaneBox).attr("data-gearId", ThisPlane.itemId); if(typeof this.squadNames["p"+ThisPlane.itemId] != "undefined"){ $(".instance_name input", PlaneBox).val( this.squadNames["p"+ThisPlane.itemId] ); } if(ThisPlane.MyHolder()){ if(ThisPlane.MyHolder() instanceof KC3LandBase){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS World "+ThisPlane.MyHolder().map ); $(".holder_level", PlaneBox).text( "#"+ThisPlane.MyHolder().rid ); ThisCapacity = ThisPlane.MyHolder().planes .filter(lbasPlanesFilter)[0].api_max_count; } else if(ThisPlane.MyHolder() === "LbasMoving"){ $(".holder_pic img", PlaneBox).attr("src", "../../../../assets/img/items/33.png" ); $(".holder_name", PlaneBox).text( "LBAS Moving" ); $(".holder_level", PlaneBox).text( "" ); ThisCapacity = ""; } else { $(".holder_pic img", PlaneBox).attr("src", KC3Meta.shipIcon(ThisPlane.MyHolder().masterId) ); $(".holder_name", PlaneBox).text( ThisPlane.MyHolder().name() ); $(".holder_level", PlaneBox).text("Lv."+ThisPlane.MyHolder().level); ThisCapacity = ThisPlane.MyHolder().slots[ this._slotNums["s"+ThisPlane.itemId] ]; } if(ThisCapacity > 0){ // Compute for veteranized fighter power var MyFighterPowerText = ""; if(ConfigManager.air_formula == 1){ MyFighterPowerText = ThisPlane.fighterPower(ThisCapacity); }else{ MyFighterPowerText = "~"+ThisPlane.fighterVeteran(ThisCapacity); } $(".instance_aaval", PlaneBox).text( MyFighterPowerText ); } $(".instance_aaval", PlaneBox).addClass("activeSquad"); $(".instance_slot", PlaneBox).text(ThisCapacity); }else{ $(".holder_pic", PlaneBox).hide(); $(".holder_name", PlaneBox).hide(); $(".holder_level", PlaneBox).hide(); $(".instance_aaval", PlaneBox).addClass("reserveSquad"); $(".instance_aaval", PlaneBox).text( ThisSlotitem.stats.aa ); } } } }, /* Determine if an item has a specific stat --------------------------------------------*/ slotitem_stat :function(ItemElem, SlotItem, statName){ if(SlotItem.stats[statName] !== 0 && (statName !== "or" || (statName === "or" && KC3GearManager.landBasedAircraftType3Ids.indexOf(SlotItem.type_id)>-1) ) ){ $(".stats .item_"+statName+" span", ItemElem).text(SlotItem.stats[statName]); }else{ $(".stats .item_"+statName, ItemElem).hide(); } } }; })();
mit
dolymood/angular-packages
angular-1.3.18/docs/partials/api/ng/service/$anchorScroll.html
8098
<a href='https://github.com/angular/angular.js/edit//src/ng/anchorScroll.js?message=docs($anchorScroll)%3A%20describe%20your%20change...#L32' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit">&nbsp;</i>Improve this Doc</a> <a href='https://github.com/angular/angular.js/tree/v1.3.18/src/ng/anchorScroll.js#L32' class='view-source pull-right btn btn-primary'> <i class="glyphicon glyphicon-zoom-in">&nbsp;</i>View Source </a> <header class="api-profile-header"> <h1 class="api-profile-header-heading">$anchorScroll</h1> <ol class="api-profile-header-structure naked-list step-list"> <li> <a href="api/ng/provider/$anchorScrollProvider">- $anchorScrollProvider</a> </li> <li> - service in module <a href="api/ng">ng</a> </li> </ol> </header> <div class="api-profile-description"> <p>When called, it checks the current value of <a href="api/ng/service/$location#hash">$location.hash()</a> and scrolls to the related element, according to the rules specified in the <a href="http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document">Html5 spec</a>.</p> <p>It also watches the <a href="api/ng/service/$location#hash">$location.hash()</a> and automatically scrolls to match any anchor whenever it changes. This can be disabled by calling <a href="api/ng/provider/$anchorScrollProvider#disableAutoScrolling">$anchorScrollProvider.disableAutoScrolling()</a>.</p> <p>Additionally, you can use its <a href="api/ng/service/$anchorScroll#yOffset">yOffset</a> property to specify a vertical scroll-offset (either fixed or dynamic).</p> </div> <div> <h2 id="dependencies">Dependencies</h2> <ul> <li><a href="api/ng/service/$window"><code>$window</code></a></li><li><a href="api/ng/service/$location"><code>$location</code></a></li><li><a href="api/ng/service/$rootScope"><code>$rootScope</code></a></li> </ul> <h2 id="usage">Usage</h2> <p><code>$anchorScroll();</code></p> <h2>Properties</h2> <ul class="properties"> <li id="yOffset"> <h3><code>yOffset</code></h3> <table class="variables-matrix return-arguments"> <tr> <td><a href="" class="label type-hint type-hint-number">number</a><a href="" class="label type-hint type-hint-function">function()</a><a href="" class="label type-hint type-hint-jqlite">jqLite</a></td> <td><p>If set, specifies a vertical scroll-offset. This is often useful when there are fixed positioned elements at the top of the page, such as navbars, headers etc.</p> <p><code>yOffset</code> can be specified in various ways:</p> <ul> <li><strong>number</strong>: A fixed number of pixels to be used as offset.<br /><br /></li> <li><strong>function</strong>: A getter function called everytime <code>$anchorScroll()</code> is executed. Must return a number representing the offset (in pixels).<br /><br /></li> <li><strong>jqLite</strong>: A jqLite/jQuery element to be used for specifying the offset. The distance from the top of the page to the element&#39;s bottom will be used as offset.<br /> <strong>Note</strong>: The element will be taken into account only as long as its <code>position</code> is set to <code>fixed</code>. This option is useful, when dealing with responsive navbars/headers that adjust their height and/or positioning according to the viewport&#39;s size.</li> </ul> <p><br /></p> <div class="alert alert-warning"> In order for <code>yOffset</code> to work properly, scrolling should take place on the document&#39;s root and not some child element. </div></td> </tr> </table> </li> </ul> <h2 id="example">Example</h2><p> <div> <a ng-click="openPlunkr('examples/example-example49', $event)" class="btn pull-right"> <i class="glyphicon glyphicon-edit">&nbsp;</i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example49" module="anchorScrollExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code>&lt;div id=&quot;scrollArea&quot; ng-controller=&quot;ScrollController&quot;&gt;&#10; &lt;a ng-click=&quot;gotoBottom()&quot;&gt;Go to bottom&lt;/a&gt;&#10; &lt;a id=&quot;bottom&quot;&gt;&lt;/a&gt; You&#39;re at the bottom!&#10;&lt;/div&gt;</code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>angular.module(&#39;anchorScrollExample&#39;, [])&#10;.controller(&#39;ScrollController&#39;, [&#39;$scope&#39;, &#39;$location&#39;, &#39;$anchorScroll&#39;,&#10; function ($scope, $location, $anchorScroll) {&#10; $scope.gotoBottom = function() {&#10; // set the location.hash to the id of&#10; // the element you wish to scroll to.&#10; $location.hash(&#39;bottom&#39;);&#10;&#10; // call $anchorScroll()&#10; $anchorScroll();&#10; };&#10; }]);</code></pre> </div> <div class="runnable-example-file" name="style.css" language="css" type="css"> <pre><code>#scrollArea {&#10; height: 280px;&#10; overflow: auto;&#10;}&#10;&#10;#bottom {&#10; display: block;&#10; margin-top: 2000px;&#10;}</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example49/index.html" name="example-example49"></iframe> </div> </div> </p> <p><hr /> The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). See <a href="api/ng/service/$anchorScroll#yOffset">$anchorScroll.yOffset</a> for more details.</p> <p> <div> <a ng-click="openPlunkr('examples/example-example50', $event)" class="btn pull-right"> <i class="glyphicon glyphicon-edit">&nbsp;</i> Edit in Plunker</a> <div class="runnable-example" path="examples/example-example50" module="anchorScrollOffsetExample"> <div class="runnable-example-file" name="index.html" language="html" type="html"> <pre><code>&lt;div class=&quot;fixed-header&quot; ng-controller=&quot;headerCtrl&quot;&gt;&#10; &lt;a href=&quot;&quot; ng-click=&quot;gotoAnchor(x)&quot; ng-repeat=&quot;x in [1,2,3,4,5]&quot;&gt;&#10; Go to anchor {{x}}&#10; &lt;/a&gt;&#10;&lt;/div&gt;&#10;&lt;div id=&quot;anchor{{x}}&quot; class=&quot;anchor&quot; ng-repeat=&quot;x in [1,2,3,4,5]&quot;&gt;&#10; Anchor {{x}} of 5&#10;&lt;/div&gt;</code></pre> </div> <div class="runnable-example-file" name="script.js" language="js" type="js"> <pre><code>angular.module(&#39;anchorScrollOffsetExample&#39;, [])&#10;.run([&#39;$anchorScroll&#39;, function($anchorScroll) {&#10; $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels&#10;}])&#10;.controller(&#39;headerCtrl&#39;, [&#39;$anchorScroll&#39;, &#39;$location&#39;, &#39;$scope&#39;,&#10; function ($anchorScroll, $location, $scope) {&#10; $scope.gotoAnchor = function(x) {&#10; var newHash = &#39;anchor&#39; + x;&#10; if ($location.hash() !== newHash) {&#10; // set the $location.hash to `newHash` and&#10; // $anchorScroll will automatically scroll to it&#10; $location.hash(&#39;anchor&#39; + x);&#10; } else {&#10; // call $anchorScroll() explicitly,&#10; // since $location.hash hasn&#39;t changed&#10; $anchorScroll();&#10; }&#10; };&#10; }&#10;]);</code></pre> </div> <div class="runnable-example-file" name="style.css" language="css" type="css"> <pre><code>body {&#10; padding-top: 50px;&#10;}&#10;&#10;.anchor {&#10; border: 2px dashed DarkOrchid;&#10; padding: 10px 10px 200px 10px;&#10;}&#10;&#10;.fixed-header {&#10; background-color: rgba(0, 0, 0, 0.2);&#10; height: 50px;&#10; position: fixed;&#10; top: 0; left: 0; right: 0;&#10;}&#10;&#10;.fixed-header &gt; a {&#10; display: inline-block;&#10; margin: 5px 15px;&#10;}</code></pre> </div> <iframe class="runnable-example-frame" src="examples/example-example50/index.html" name="example-example50"></iframe> </div> </div> </p> </div>
mit
JamesLongman/ava-bot
lib/ava.js
455
'use strict'; /* This is the primary module of the Ava bot, if you are not using docker to run the bot you can use another method to run this file as long as you make sure you have the correct dependencies */ const bot = require('./bot.js'); const log = require('./logger.js')(module); log.info('======== ava.js running ========'); // This step serves the important purpose of allowing a specific function to be called to start the bot bot.startup();
mit
ericstj/standard
docs/comparisons/netstandard2.0_vs_netcoreapp2.0/System.Collections.ObjectModel.md
240
# System.Collections.ObjectModel ``` diff namespace System.Collections.ObjectModel { public abstract class KeyedCollection<TKey, TItem> : Collection<TItem> { + public bool TryGetValue(TKey key, out TItem item); } } ```
mit
edspencer/jaml
src/Jaml.js
1100
/** * @class Jaml * @author Ed Spencer (http://edspencer.net) * Jaml is a simple JavaScript library which makes HTML generation easy and pleasurable. * Examples: http://edspencer.github.com/jaml * Introduction: http://edspencer.net/2009/11/jaml-beautiful-html-generation-for-javascript.html */ Jaml = function() { return { templates: {}, /** * Registers a template by name * @param {String} name The name of the template * @param {Function} template The template function */ register: function(name, template) { this.templates[name] = template; }, /** * Renders the given template name with an optional data object * @param {String} name The name of the template to render * @param {Object} thisObj Optional data object * @param {Object} data Optional data object */ render: function(name, thisObj, data) { var template = this.templates[name], renderer = new Jaml.Template(template); return renderer.render.apply(renderer, Array.prototype.slice.call(arguments, 1)); } }; }();
mit