answer
stringlengths
15
1.25M
'use strict'; module.exports = require('../is-windows') ? require('./windows/relative').tests : require('./posix/relative').tests;
using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Management.Automation.Host; using System.Management.Automation.Internal.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Management.Automation.Internal; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation { #region Event Args <summary> Possible actions for the debugger after hitting a breakpoint/step </summary> public enum <API key> { <summary> Continue running until the next breakpoint, or the end of the script </summary> Continue = 0, <summary> Step to next statement, going into functions, scripts, etc </summary> StepInto = 1, <summary> Step to next statement, going over functions, scripts, etc </summary> StepOut = 2, <summary> Step to next statement after the current function, script, etc </summary> StepOver = 3, <summary> Stop executing the script </summary> Stop = 4, }; <summary> Arguments for the DebuggerStop event. </summary> public class <API key> : EventArgs { <summary> Initializes the <API key> </summary> internal <API key>(InvocationInfo invocationInfo, List<Breakpoint> breakpoints) { this.InvocationInfo = invocationInfo; this.Breakpoints = new ReadOnlyCollection<Breakpoint>(breakpoints); this.ResumeAction = <API key>.Continue; } <summary> Constructor. </summary> <param name="invocationInfo"></param> <param name="breakpoints"></param> <param name="resumeAction"></param> public <API key>( InvocationInfo invocationInfo, Collection<Breakpoint> breakpoints, <API key> resumeAction) { this.InvocationInfo = invocationInfo; this.Breakpoints = new ReadOnlyCollection<Breakpoint>(breakpoints); this.ResumeAction = resumeAction; } <summary> Invocation info of the code being executed </summary> public InvocationInfo InvocationInfo { get; internal set; } <summary> The breakpoint(s) hit </summary> <remarks> Note there may be more than one breakpoint on the same object (line, variable, command). A single event is raised for all these breakpoints. </remarks> public ReadOnlyCollection<Breakpoint> Breakpoints { get; private set; } <summary> This property must be set in the event handler to indicate the debugger what it should do next </summary> <remarks> The default action is DebuggerAction.Continue. DebuggerAction.StepToLine is only valid when debugging an script. </remarks> public <API key> ResumeAction { get; set; } }; <summary> Kinds of breakpoint updates </summary> public enum <API key> { <summary> A breakpoint was set </summary> Set = 0, <summary> A breakpoint was removed </summary> Removed = 1, <summary> A breakpoint was enabled </summary> Enabled = 2, <summary> A breakpoint was disabled </summary> Disabled = 3 }; <summary> Arguments for the BreakpointUpdated event. </summary> public class <API key> : EventArgs { <summary> Initializes the <API key> </summary> internal <API key>(Breakpoint breakpoint, <API key> updateType, int breakpointCount) { this.Breakpoint = breakpoint; this.UpdateType = updateType; this.BreakpointCount = breakpointCount; } <summary> Gets the breakpoint that was updated </summary> public Breakpoint Breakpoint { get; private set; } <summary> Gets the type of update </summary> public <API key> UpdateType { get; private set; } <summary> Gets the current breakpoint count </summary> public int BreakpointCount { get; private set; } }; #region PSJobStartEventArgs <summary> Arguments for the script job start callback event. </summary> public sealed class PSJobStartEventArgs : EventArgs { <summary> Job to be started </summary> public Job Job { get; private set; } <summary> Job debugger </summary> public Debugger Debugger { get; private set; } <summary> Job is run asynchronously </summary> public bool IsAsync { get; private set; } <summary> Constructor </summary> <param name="job">Started job</param> <param name="debugger">Debugger</param> <param name="isAsync">Job started asynchronously</param> public PSJobStartEventArgs(Job job, Debugger debugger, bool isAsync) { this.Job = job; this.Debugger = debugger; this.IsAsync = isAsync; } } #endregion #region DebugSource <summary> Contains debugger script and script file information. </summary> public sealed class DebugSource { <summary> Full script. </summary> public string Script { get; private set; } <summary> Script file for script or null. </summary> public string ScriptFile { get; private set; } <summary> Xaml definition for Workflow script or null. </summary> public string XamlDefinition { get; private set; } <summary> Constructor. </summary> <param name="script">Script text</param> <param name="scriptFile">Script file</param> <param name="xamlDefinition">Xaml definition</param> public DebugSource( string script, string scriptFile, string xamlDefinition) { Script = script; ScriptFile = scriptFile; XamlDefinition = xamlDefinition; } private DebugSource() { } } #endregion #endregion #region Enums <summary> Defines debugging mode. </summary> [Flags] public enum DebugModes { <summary> PowerShell script debugging is disabled. </summary> None = 0x0, <summary> Default setting for original PowerShell script debugging. Compatible with PowerShell Versions 2 and 3. </summary> Default = 0x1, <summary> PowerShell script debugging including workflow script. </summary> LocalScript = 0x2, <summary> PowerShell remote script and workflow debugging. </summary> RemoteScript = 0x4 }; <summary> Defines unhandled breakpoint processing behavior </summary> internal enum <API key> { <summary> Ignore unhandled breakpoint events. </summary> Ignore = 1, <summary> Wait on unhandled breakpoint events until a handler is available. </summary> Wait } #endregion #region Debugger base class <summary> Base class for all PowerShell debuggers. </summary> public abstract class Debugger { #region Events <summary> Event raised when the debugger hits a breakpoint or a step </summary> public event EventHandler<<API key>> DebuggerStop; <summary> Event raised when a breakpoint is updated </summary> public event EventHandler<<API key>> BreakpointUpdated; <summary> Event raised when nested debugging is cancelled. </summary> internal event EventHandler<EventArgs> <API key>; #endregion #region Properties <summary> True when the debugger is stopped. </summary> protected bool DebuggerStopped { get; private set; } <summary> IsPushed </summary> internal virtual bool IsPushed { get { return false; } } <summary> IsRemote </summary> internal virtual bool IsRemote { get { return false; } } <summary> Returns true if the debugger is preserving a DebuggerStopEvent event. Use <API key>() to allow event to process. </summary> internal virtual bool <API key> { get { throw new <API key>(); } } <summary> Returns true if debugger has been set to stepInto mode. </summary> internal virtual bool <API key> { get { throw new <API key>(); } } <summary> Returns true if there is a handler for debugger stops. </summary> internal bool <API key> { get { return (DebuggerStop != null); } } <summary> <API key> </summary> internal virtual <API key> <API key> { get { throw new <API key>(); } set { throw new <API key>(); } } <summary> DebuggerMode </summary> public DebugModes DebugMode { get; protected set; } = DebugModes.Default; <summary> Returns true if debugger has breakpoints set and is currently active. </summary> public virtual bool IsActive { get { return false; } } <summary> InstanceId </summary> public virtual Guid InstanceId { get { return s_instanceId; } } <summary> True when debugger is stopped at a breakpoint. </summary> public virtual bool InBreakpoint { get { return DebuggerStopped; } } #endregion #region Protected Methods <summary> <API key> </summary> <param name="args"><API key></param> [SuppressMessage("Microsoft.Design", "CA1030:<API key>")] protected void <API key>(<API key> args) { try { DebuggerStopped = true; DebuggerStop.SafeInvoke<<API key>>(this, args); } finally { DebuggerStopped = false; } } <summary> <API key> </summary> <returns>True if event subscription exists</returns> protected bool <API key>() { return (DebuggerStop != null); } <summary> <API key> </summary> <param name="args"><API key></param> [SuppressMessage("Microsoft.Design", "CA1030:<API key>")] protected void <API key>(<API key> args) { BreakpointUpdated.SafeInvoke<<API key>>(this, args); } <summary> <API key> </summary> <returns>True if event subscription exists</returns> protected bool <API key>() { return (BreakpointUpdated != null); } #endregion #region Public Methods <summary> Evaluates provided command either as a debugger specific command or a PowerShell command. </summary> <param name="command">PowerShell command</param> <param name="output">Output</param> <returns><API key></returns> public abstract <API key> ProcessCommand(PSCommand command, PSDataCollection<PSObject> output); <summary> Sets the debugger resume action. </summary> <param name="resumeAction"><API key></param> public abstract void SetDebuggerAction(<API key> resumeAction); <summary> Stops a running command. </summary> public abstract void StopProcessCommand(); <summary> Returns current debugger stop event arguments if debugger is in debug stop state. Otherwise returns null. </summary> <returns><API key></returns> public abstract <API key> GetDebuggerStopArgs(); <summary> Sets the parent debugger and breakpoints. </summary> <param name="parent">Parent debugger</param> <param name="breakPoints">List of breakpoints</param> <param name="startAction">Debugger mode</param> <param name="host">host</param> <param name="path">Current path</param> public virtual void SetParent( Debugger parent, IEnumerable<Breakpoint> breakPoints, <API key>? startAction, PSHost host, PathInfo path) { throw new <API key>(); } <summary> Sets the parent debugger, breakpoints, function source and other debugging context information. </summary> <param name="parent">Parent debugger</param> <param name="breakPoints">List of breakpoints</param> <param name="startAction">Debugger mode</param> <param name="host">PowerShell host</param> <param name="path">Current path</param> <param name="functionSourceMap">Function to source map</param> public virtual void SetParent( Debugger parent, IEnumerable<Breakpoint> breakPoints, <API key>? startAction, PSHost host, PathInfo path, Dictionary<string, DebugSource> functionSourceMap) { throw new <API key>(); } <summary> Sets the debugger mode. </summary> public virtual void SetDebugMode(DebugModes mode) { this.DebugMode = mode; } <summary> Returns IEnumerable of CallStackFrame objects. </summary> <returns></returns> public virtual IEnumerable<CallStackFrame> GetCallStack() { return new Collection<CallStackFrame>(); } <summary> Adds the provided set of breakpoints to the debugger. </summary> <param name="breakpoints">Breakpoints.</param> public virtual void SetBreakpoints(IEnumerable<Breakpoint> breakpoints) { throw new <API key>(); } <summary> Resets the command processor source information so that it is updated with latest information on the next debug stop. </summary> public virtual void <API key>() { throw new <API key>(); } <summary> Sets debugger stepping mode. </summary> <param name="enabled">True if stepping is to be enabled</param> public virtual void SetDebuggerStepMode(bool enabled) { throw new <API key>(); } #endregion #region Internal Methods <summary> Passes the debugger command to the internal script debugger command processor. This is used internally to handle debugger commands such as list, help, etc. </summary> <param name="command">Command string</param> <param name="output">Output collection</param> <returns>DebuggerCommand containing information on whether and how the command was processed.</returns> internal virtual DebuggerCommand <API key>(string command, IList<PSObject> output) { throw new <API key>(); } <summary> Creates a source list based on root script debugger source information if available, with the current source line highlighted. This is used internally for nested runspace debugging where the runspace command is run in context of a parent script. </summary> <param name="lineNum">Current source line</param> <param name="output">Output collection</param> <returns>True if source listed successfully</returns> internal virtual bool <API key>(int lineNum, IList<PSObject> output) { throw new <API key>(); } <summary> Sets up debugger to debug provided job or its child jobs. </summary> <param name="job"> Job object that is either a debuggable job or a container of debuggable child jobs. </param> internal virtual void DebugJob(Job job) { throw new <API key>(); } <summary> Removes job from debugger job list and pops the its debugger from the active debugger stack. </summary> <param name="job">Job</param> internal virtual void StopDebugJob(Job job) { throw new <API key>(); } <summary> <API key>. </summary> <returns>Array of stack frame objects of active debugger</returns> internal virtual CallStackFrame[] <API key>() { throw new <API key>(); } <summary> Method to add the provided runspace information to the debugger for monitoring of debugger events. This is used to implement nested debugging of runspaces. </summary> <param name="args"><API key></param> internal virtual void <API key>(<API key> args) { throw new <API key>(); } <summary> Method to end the monitoring of a runspace for debugging events. </summary> <param name="args"><API key></param> internal virtual void <API key>(<API key> args) { throw new <API key>(); } <summary> If a debug stop event is currently pending then this method will release the event to continue processing. </summary> internal virtual void <API key>() { throw new <API key>(); } <summary> Sets up debugger to debug provided Runspace in a nested debug session. </summary> <param name="runspace">Runspace to debug</param> internal virtual void DebugRunspace(Runspace runspace) { throw new <API key>(); } <summary> Removes the provided Runspace from the nested "active" debugger state. </summary> <param name="runspace">Runspace</param> internal virtual void StopDebugRunspace(Runspace runspace) { throw new <API key>(); } <summary> Raises the <API key> event. </summary> internal void <API key>() { // Raise event on worker thread. Threading.ThreadPool.QueueUserWorkItem( (state) => { try { <API key>.SafeInvoke<EventArgs>(this, null); } catch (Exception e) { <API key>.<API key>(e); } }); } #endregion #region Members internal const string <API key> = "Debugger:<API key>"; internal const string <API key> = "Debugger:<API key>"; private static readonly Guid s_instanceId = new Guid(); #endregion } #endregion #region ScriptDebugger class <summary> Holds the debugging information for a Monad Shell session </summary> internal sealed class ScriptDebugger : Debugger, IDisposable { #region constructors internal ScriptDebugger(ExecutionContext context) { _context = context; _inBreakpoint = false; _idToBreakpoint = new Dictionary<int, Breakpoint>(); _pendingBreakpoints = new List<LineBreakpoint>(); _boundBreakpoints = new Dictionary<string, Tuple<WeakReference, List<LineBreakpoint>>>(StringComparer.OrdinalIgnoreCase); _commandBreakpoints = new List<CommandBreakpoint>(); <API key> = new Dictionary<string, List<VariableBreakpoint>>(StringComparer.OrdinalIgnoreCase); _steppingMode = SteppingMode.None; _callStack = new CallStackList { _callStackList = new List<CallStackInfo>() }; _runningJobs = new Dictionary<Guid, PSJobStartEventArgs>(); _activeDebuggers = new ConcurrentStack<Debugger>(); <API key> = new ConcurrentStack<<API key>>(); _syncObject = new object(); <API key> = new object(); _runningRunspaces = new Dictionary<Guid, <API key>>(); } <summary> Static constructor </summary> static ScriptDebugger() { <API key> = StringUtil.Format(@"""[{0}:", DebuggerStrings.<API key>); } #endregion constructors #region properties <summary> True when debugger is stopped at a breakpoint. </summary> public override bool InBreakpoint { get { if (_inBreakpoint) { return _inBreakpoint; } Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { return activeDebugger.InBreakpoint; } return false; } } internal override bool IsPushed { get { return (_activeDebuggers.Count > 0); } } <summary> Returns true if the debugger is preserving a DebuggerStopEvent event. Use <API key>() to allow event to process. </summary> internal override bool <API key> { get { return ((<API key> != null) && !<API key>.IsSet); } } <summary> Returns true if debugger has been set to stepInto mode. </summary> internal override bool <API key> { get { return ((_context._debuggingMode == (int)InternalDebugMode.Enabled) && (<API key> == <API key>.StepInto) && (_steppingMode != SteppingMode.None)); } } private bool? _isLocalSession; private bool IsLocalSession { get { if (_isLocalSession == null) { // Remote debug sessions always have a ServerRemoteHost. Otherwise it is a local session. _isLocalSession = !(((_context.InternalHost.ExternalHost != null) && (_context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost))); } return _isLocalSession.Value; } } #endregion properties #region internal methods #region Reset Debugger <summary> Resets debugger to initial state. </summary> internal void ResetDebugger() { SetDebugMode(DebugModes.None); <API key>(InternalDebugMode.Disabled); _steppingMode = SteppingMode.None; _inBreakpoint = false; _idToBreakpoint.Clear(); _pendingBreakpoints.Clear(); _boundBreakpoints.Clear(); _commandBreakpoints.Clear(); <API key>.Clear(); <API key>.Clear(); _callStack.Clear(); _overOrOutFrame = null; _commandProcessor = new <API key>(); <API key> = null; _inBreakpoint = false; _psDebuggerCommand = null; <API key> = false; _isLocalSession = null; _nestedDebuggerStop = false; _writeWFErrorOnce = false; <API key>.Clear(); <API key> = <API key>.Continue; <API key> = <API key>.Continue; <API key> = <API key>.Continue; _nestedRunningFrame = null; _nestedDebuggerStop = false; <API key> = 0; <API key> = false; ClearRunningJobList(); <API key>(); _activeDebuggers.Clear(); <API key>(); SetDebugMode(DebugModes.Default); } #endregion #region Call stack management // Called from generated code on entering the script function, called once for each dynamicparam, begin, or end // block, and once for each object written to the pipeline. Also called when entering a trap. internal void EnterScriptFunction(FunctionContext functionContext) { Diagnostics.Assert(functionContext._executionContext == _context, "Wrong debugger is being used."); var invocationInfo = (InvocationInfo)functionContext._localsTuple.<API key>(AutomaticVariable.MyInvocation); var newCallStackInfo = new CallStackInfo { InvocationInfo = invocationInfo, File = functionContext._file, DebuggerStepThrough = functionContext.<API key>, FunctionContext = functionContext, IsFrameHidden = functionContext._debuggerHidden, }; _callStack.Add(newCallStackInfo); if (_context._debuggingMode > 0) { var scriptCommandInfo = invocationInfo.MyCommand as ExternalScriptInfo; if (scriptCommandInfo != null) { RegisterScriptFile(scriptCommandInfo); } bool checkLineBp = CheckCommand(invocationInfo); SetupBreakpoints(functionContext); if (functionContext.<API key> && _overOrOutFrame == null && _steppingMode == SteppingMode.StepIn) { // Treat like step out, but only if we're not already stepping out ResumeExecution(<API key>.StepOut); } if (checkLineBp) { OnSequencePointHit(functionContext); } if (_context.PSDebugTraceLevel > 1 && !functionContext.<API key> && !functionContext._debuggerHidden) { <API key>(functionContext); } } } private void SetupBreakpoints(FunctionContext functionContext) { var scriptDebugData = <API key>.GetValue(functionContext._sequencePoints, _ => Tuple.Create(new List<LineBreakpoint>(), new BitArray(functionContext._sequencePoints.Length))); functionContext._boundBreakpoints = scriptDebugData.Item1; functionContext._breakPoints = scriptDebugData.Item2; <API key>(functionContext); } // Called after exiting the script function, called once for each dynamicparam, begin, or end // block, and once for each object written to the pipeline. Also called when leaving a trap. internal void ExitScriptFunction() { // If it's stepping over to exit the current frame, we need to clear the _overOrOutFrame, // so that we will stop at the next statement in the outer frame. if (_callStack.Last() == _overOrOutFrame) { _overOrOutFrame = null; } _callStack.RemoveAt(_callStack.Count - 1); // Don't disable step mode if the user enabled runspace debugging (<API key> == Wait) if ((_callStack.Count == 0) && (<API key> != <API key>.Wait)) { // If we've popped the last entry, don't step into anything else (like prompt, suggestions, etc.) _steppingMode = SteppingMode.None; <API key> = <API key>.Continue; <API key> = <API key>.Continue; } } internal void RegisterScriptFile(ExternalScriptInfo scriptCommandInfo) { RegisterScriptFile(scriptCommandInfo.Path, scriptCommandInfo.ScriptContents); } internal void RegisterScriptFile(string path, string scriptContents) { Tuple<WeakReference, List<LineBreakpoint>> boundBreakpoints; if (!_boundBreakpoints.TryGetValue(path, out boundBreakpoints)) { _boundBreakpoints.Add(path, Tuple.Create(new WeakReference(scriptContents), new List<LineBreakpoint>())); } else { // If script contents have changed, or if the file got collected, we must rebind the breakpoints. string oldScriptContents; boundBreakpoints.Item1.TryGetTarget(out oldScriptContents); if (oldScriptContents == null || !oldScriptContents.Equals(scriptContents, StringComparison.Ordinal)) { <API key>(boundBreakpoints.Item2); _boundBreakpoints[path] = Tuple.Create(new WeakReference(scriptContents), new List<LineBreakpoint>()); } } } #endregion Call stack management #region adding breakpoints internal void AddBreakpointCommon(Breakpoint breakpoint) { if (_context._debuggingMode == 0) { <API key>(InternalDebugMode.Enabled); } _idToBreakpoint[breakpoint.Id] = breakpoint; OnBreakpointUpdated(new <API key>(breakpoint, <API key>.Set, _idToBreakpoint.Count)); } private Breakpoint <API key>(CommandBreakpoint breakpoint) { AddBreakpointCommon(breakpoint); _commandBreakpoints.Add(breakpoint); return breakpoint; } internal Breakpoint <API key>(string path, string command, ScriptBlock action) { WildcardPattern pattern = WildcardPattern.Get(command, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); return <API key>(new CommandBreakpoint(path, pattern, command, action)); } internal Breakpoint <API key>(string command, ScriptBlock action) { WildcardPattern pattern = WildcardPattern.Get(command, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); return <API key>(new CommandBreakpoint(null, pattern, command, action)); } private Breakpoint AddLineBreakpoint(LineBreakpoint breakpoint) { AddBreakpointCommon(breakpoint); _pendingBreakpoints.Add(breakpoint); return breakpoint; } private void AddNewBreakpoint(Breakpoint breakpoint) { LineBreakpoint lineBreakpoint = breakpoint as LineBreakpoint; if (lineBreakpoint != null) { AddLineBreakpoint(lineBreakpoint); return; } CommandBreakpoint cmdBreakpoint = breakpoint as CommandBreakpoint; if (cmdBreakpoint != null) { <API key>(cmdBreakpoint); return; } VariableBreakpoint varBreakpoint = breakpoint as VariableBreakpoint; if (varBreakpoint != null) { <API key>(varBreakpoint); } } internal Breakpoint NewLineBreakpoint(string path, int line, ScriptBlock action) { Diagnostics.Assert(path != null, "caller to verify path is not null"); return AddLineBreakpoint(new LineBreakpoint(path, line, action)); } internal Breakpoint <API key>(string path, int line, int column, ScriptBlock action) { Diagnostics.Assert(path != null, "caller to verify path is not null"); return AddLineBreakpoint(new LineBreakpoint(path, line, column, action)); } internal VariableBreakpoint <API key>(VariableBreakpoint breakpoint) { AddBreakpointCommon(breakpoint); List<VariableBreakpoint> breakpoints; if (!<API key>.TryGetValue(breakpoint.Variable, out breakpoints)) { breakpoints = new List<VariableBreakpoint>(); <API key>.Add(breakpoint.Variable, breakpoints); } breakpoints.Add(breakpoint); return breakpoint; } internal Breakpoint <API key>(string path, string variableName, VariableAccessMode accessMode, ScriptBlock action) { return <API key>(new VariableBreakpoint(path, variableName, accessMode, action)); } internal Breakpoint <API key>(string variableName, VariableAccessMode accessMode, ScriptBlock action) { return <API key>(new VariableBreakpoint(null, variableName, accessMode, action)); } <summary> Raises the BreakpointUpdated event </summary> <param name="e"></param> private void OnBreakpointUpdated(<API key> e) { <API key>(e); } #endregion adding breakpoints #region removing breakpoints // This is the implementation of the Remove-PSBreakpoint cmdlet. internal void RemoveBreakpoint(Breakpoint breakpoint) { _idToBreakpoint.Remove(breakpoint.Id); breakpoint.RemoveSelf(this); if (_idToBreakpoint.Count == 0) { // The last breakpoint was removed, turn off debugging. <API key>(InternalDebugMode.Disabled); } OnBreakpointUpdated(new <API key>(breakpoint, <API key>.Removed, _idToBreakpoint.Count)); } internal void <API key>(VariableBreakpoint breakpoint) { <API key>[breakpoint.Variable].Remove(breakpoint); } internal void <API key>(CommandBreakpoint breakpoint) { _commandBreakpoints.Remove(breakpoint); } internal void <API key>(LineBreakpoint breakpoint) { _pendingBreakpoints.Remove(breakpoint); Tuple<WeakReference, List<LineBreakpoint>> value; if (_boundBreakpoints.TryGetValue(breakpoint.Script, out value)) { value.Item2.Remove(breakpoint); } } #endregion removing breakpoints #region finding breakpoints // The bit array is used to detect if a breakpoint is set or not for a given scriptblock. This bit array // is checked when hitting sequence points. Enabling/disabling a line breakpoint is as simple as flipping // the bit. private readonly <API key><IScriptExtent[], Tuple<List<LineBreakpoint>, BitArray>> <API key> = new <API key><IScriptExtent[], Tuple<List<LineBreakpoint>, BitArray>>(); <summary> Checks for command breakpoints </summary> internal bool CheckCommand(InvocationInfo invocationInfo) { var functionContext = _callStack.LastFunctionContext(); if (functionContext != null && functionContext._debuggerHidden) { // Never stop in DebuggerHidden scripts, don't even call the actions on breakpoints. return false; } List<Breakpoint> breakpoints = _commandBreakpoints.Where(bp => bp.Enabled && bp.Trigger(invocationInfo)).ToList<Breakpoint>(); bool checkLineBp = true; if (breakpoints.Any()) { breakpoints = TriggerBreakpoints(breakpoints); if (breakpoints.Any()) { var breakInvocationInfo = functionContext != null ? new InvocationInfo(invocationInfo.MyCommand, functionContext.CurrentPosition) : null; OnDebuggerStop(breakInvocationInfo, breakpoints); checkLineBp = false; } } return checkLineBp; } internal void CheckVariableRead(string variableName) { var <API key> = <API key>(variableName, read: true); if (<API key> != null && <API key>.Any()) { <API key>(<API key>); } } internal void CheckVariableWrite(string variableName) { var <API key> = <API key>(variableName, read: false); if (<API key> != null && <API key>.Any()) { <API key>(<API key>); } } private List<VariableBreakpoint> <API key>(string variableName, bool read) { Diagnostics.Assert(_context._debuggingMode == 1, "breakpoints only hit when debugging mode is 1"); var functionContext = _callStack.LastFunctionContext(); if (functionContext != null && functionContext._debuggerHidden) { // Never stop in DebuggerHidden scripts, don't even call the action on any breakpoint. return null; } try { <API key>(InternalDebugMode.Disabled); List<VariableBreakpoint> breakpoints; if (!<API key>.TryGetValue(variableName, out breakpoints)) { // $PSItem is an alias for $_. We don't use PSItem internally, but a user might // have set a bp on $PSItem, so look for that if appropriate. if (SpecialVariables.IsUnderbar(variableName)) { <API key>.TryGetValue(SpecialVariables.PSItem, out breakpoints); } } if (breakpoints == null) return null; var callStackInfo = _callStack.Last(); var currentScriptFile = (callStackInfo != null) ? callStackInfo.File : null; return breakpoints.Where(bp => bp.Trigger(currentScriptFile, read: read)).ToList(); } finally { <API key>(InternalDebugMode.Enabled); } } internal void <API key>(List<VariableBreakpoint> breakpoints) { var functionContext = _callStack.LastFunctionContext(); var invocationInfo = functionContext != null ? new InvocationInfo(null, functionContext.CurrentPosition, _context) : null; OnDebuggerStop(invocationInfo, breakpoints.ToList<Breakpoint>()); } <summary> Get a breakpoint by id, primarily for Enable/Disable/Remove-PSBreakpoint cmdlets. </summary> internal Breakpoint GetBreakpoint(int id) { Breakpoint breakpoint; _idToBreakpoint.TryGetValue(id, out breakpoint); return breakpoint; } <summary> Returns breakpoints primarily for the Get-PSBreakpoint cmdlet. </summary> internal List<Breakpoint> GetBreakpoints() { return (from bp in _idToBreakpoint.Values orderby bp.Id select bp).ToList(); } // Return the line breakpoints bound in a specific script block (used when a sequence point // is hit, to find which breakpoints are set on that sequence point.) internal List<LineBreakpoint> GetBoundBreakpoints(IScriptExtent[] sequencePoints) { Tuple<List<LineBreakpoint>, BitArray> tuple; if (<API key>.TryGetValue(sequencePoints, out tuple)) { return tuple.Item1; } return null; } #endregion finding breakpoints #region triggering breakpoints private List<Breakpoint> TriggerBreakpoints(List<Breakpoint> breakpoints) { Diagnostics.Assert(_context._debuggingMode == 1, "breakpoints only hit when debugging mode == 1"); List<Breakpoint> breaks = new List<Breakpoint>(); try { <API key>(InternalDebugMode.InScriptStop); foreach (Breakpoint breakpoint in breakpoints) { if (breakpoint.Enabled) { try { // Ensure that code being processed during breakpoint triggers // act like they are broken into the debugger. _inBreakpoint = true; if (breakpoint.Trigger() == Breakpoint.BreakpointAction.Break) { breaks.Add(breakpoint); } } finally { _inBreakpoint = false; } } } } finally { <API key>(InternalDebugMode.Enabled); } return breaks; } #endregion triggering breakpoints #region enabling/disabling breakpoints <summary> Implementation of Enable-PSBreakpoint cmdlet. </summary> internal void EnableBreakpoint(Breakpoint bp) { bp.SetEnabled(true); OnBreakpointUpdated(new <API key>(bp, <API key>.Enabled, _idToBreakpoint.Count)); } <summary> Implementation of <API key> cmdlet. </summary> internal void DisableBreakpoint(Breakpoint bp) { bp.SetEnabled(false); OnBreakpointUpdated(new <API key>(bp, <API key>.Disabled, _idToBreakpoint.Count)); } #endregion enabling/disabling breakpoints internal void OnSequencePointHit(FunctionContext functionContext) { if (_context.<API key> && !_callStack.Last().IsFrameHidden && !functionContext.<API key>) { TraceLine(functionContext.CurrentPosition); } // If a nested debugger received a stop debug command then all debugging // should stop. if (_nestedDebuggerStop) { _nestedDebuggerStop = false; <API key> = <API key>.Continue; ResumeExecution(<API key>.Stop); } #if !CORECLR // Workflow Not Supported on OneCore PS // Lazily subscribe to workflow start engine event for workflow debugging. if (!<API key> && IsJobDebuggingMode()) { <API key>(); } #endif UpdateBreakpoints(functionContext); if (_steppingMode == SteppingMode.StepIn && (_overOrOutFrame == null || _callStack.Last() == _overOrOutFrame)) { if (!_callStack.Last().IsFrameHidden) { _overOrOutFrame = null; StopOnSequencePoint(functionContext, <API key>); } else if (_overOrOutFrame == null) { // Treat like step out, but only if we're not already stepping out ResumeExecution(<API key>.StepOut); } } else { if (functionContext._breakPoints[functionContext.<API key>]) { var breakpoints = (from breakpoint in functionContext._boundBreakpoints where breakpoint.SequencePointIndex == functionContext.<API key> && breakpoint.Enabled select breakpoint).ToList<Breakpoint>(); breakpoints = TriggerBreakpoints(breakpoints); if (breakpoints.Any()) { StopOnSequencePoint(functionContext, breakpoints); } } } } private void UpdateBreakpoints(FunctionContext functionContext) { if (functionContext._breakPoints == null) { // This should be rare - setting a breakpoint inside a script, but debugger hadn't started. SetupBreakpoints(functionContext); } else { // Check pending breakpoints to see if any apply to this script. if (string.IsNullOrEmpty(functionContext._file)) { return; } bool <API key> = false; foreach (var item in _pendingBreakpoints) { if (item.IsScriptBreakpoint && item.Script.Equals(functionContext._file, StringComparison.OrdinalIgnoreCase)) { <API key> = true; break; } } if (<API key>) { <API key>(functionContext); } } } #endregion internal methods #region private members [DebuggerDisplay("{FunctionContext.CurrentPosition}")] private class CallStackInfo { internal InvocationInfo InvocationInfo { get; set; } internal string File { get; set; } internal bool DebuggerStepThrough { get; set; } internal FunctionContext FunctionContext { get; set; } <summary> The frame is hidden due to the <see cref="<API key>"/> attribute. No breakpoints will be set and no stepping in/through. </summary> internal bool IsFrameHidden { get; set; } internal bool <API key> { get; set; } }; private struct CallStackList { internal List<CallStackInfo> _callStackList; internal void Add(CallStackInfo item) { lock (_callStackList) { _callStackList.Add(item); } } internal void RemoveAt(int index) { lock (_callStackList) { _callStackList.RemoveAt(index); } } internal CallStackInfo this[int index] { get { lock (_callStackList) { return ((index > -1) && (index < _callStackList.Count)) ? _callStackList[index] : null; } } } internal CallStackInfo Last() { lock (_callStackList) { return (_callStackList.Count > 0) ? _callStackList[_callStackList.Count - 1] : null; } } internal FunctionContext LastFunctionContext() { var last = Last(); return last != null ? last.FunctionContext : null; } internal bool Any() { lock (_callStackList) { return _callStackList.Count > 0; } } internal int Count { get { lock (_callStackList) { return _callStackList.Count; } } } internal CallStackInfo[] ToArray() { lock (_callStackList) { return _callStackList.ToArray(); } } internal void Clear() { lock (_callStackList) { _callStackList.Clear(); } } } private readonly ExecutionContext _context; private List<LineBreakpoint> _pendingBreakpoints; private readonly Dictionary<string, Tuple<WeakReference, List<LineBreakpoint>>> _boundBreakpoints; private readonly List<CommandBreakpoint> _commandBreakpoints; private readonly Dictionary<string, List<VariableBreakpoint>> <API key>; private readonly Dictionary<int, Breakpoint> _idToBreakpoint; private SteppingMode _steppingMode; private CallStackInfo _overOrOutFrame; private CallStackList _callStack; private static readonly List<Breakpoint> <API key> = new List<Breakpoint>(); private <API key> _commandProcessor = new <API key>(); private InvocationInfo <API key>; private bool _inBreakpoint; private PowerShell _psDebuggerCommand; // Job debugger integration. #if !CORECLR // Workflow Not Supported on OneCore PS private bool <API key>; #endif private bool _nestedDebuggerStop; private bool _writeWFErrorOnce; private Dictionary<Guid, PSJobStartEventArgs> _runningJobs; private ConcurrentStack<Debugger> _activeDebuggers; private ConcurrentStack<<API key>> <API key>; private <API key> <API key>; private <API key> <API key>; private <API key> <API key>; private CallStackInfo _nestedRunningFrame; private object _syncObject; private object <API key>; private int <API key>; private <API key> <API key> = new <API key>(true); // Runspace debugger integration. private Dictionary<Guid, <API key>> _runningRunspaces; private const int _jobCallStackOffset = 2; private const int <API key> = 1; private bool <API key>; private <API key> <API key>; private static readonly string <API key>; #endregion private members #region private methods <summary> Raises the DebuggerStop event </summary> private void OnDebuggerStop(InvocationInfo invocationInfo, List<Breakpoint> breakpoints) { Diagnostics.Assert(breakpoints != null, "The list of breakpoints should not be null"); LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; Diagnostics.Assert(localRunspace != null, "Debugging is only supported on local runspaces"); if (localRunspace.PulsePipeline != null && localRunspace.PulsePipeline == localRunspace.<API key>()) { _context.EngineHostInterface.UI.WriteWarningLine( breakpoints.Count > 0 ? String.Format(CultureInfo.CurrentCulture, DebuggerStrings.<API key>, breakpoints[0]) : new <API key>().Message); return; } <API key> = invocationInfo; _steppingMode = SteppingMode.None; // Optionally wait for a debug stop event subscriber if requested. _inBreakpoint = true; if (!<API key>()) { // No subscriber. Ignore this debug stop event. _inBreakpoint = false; return; } _context.SetVariable(SpecialVariables.<API key>, new PSDebugContext(invocationInfo, breakpoints)); FunctionInfo defaultPromptInfo = null; string <API key> = null; bool hadDefaultPrompt = false; try { Collection<PSObject> items = _context.SessionState.InvokeProvider.Item.Get("function:\\prompt"); if ((items != null) && (items.Count > 0)) { defaultPromptInfo = items[0].BaseObject as FunctionInfo; <API key> = defaultPromptInfo.Definition as string; if (<API key>.Equals(InitialSessionState.<API key>, StringComparison.OrdinalIgnoreCase) || <API key>.Trim().StartsWith(<API key>, StringComparison.OrdinalIgnoreCase)) { hadDefaultPrompt = true; } } } catch (<API key>) { // Ignore, it means they don't have the default prompt } // Update the prompt to the debug prompt if (hadDefaultPrompt) { int index = <API key>.IndexOf("\"", StringComparison.OrdinalIgnoreCase); if (index > -1) { // Fix up prompt. ++index; string debugPrompt = "\"[DBG]: " + <API key>.Substring(index, <API key>.Length - index); defaultPromptInfo.Update( ScriptBlock.Create(debugPrompt), true, ScopedItemOptions.Unspecified); } else { hadDefaultPrompt = false; } } PSLanguageMode? <API key> = null; if (_context.<API key> && (_context.LanguageMode != PSLanguageMode.FullLanguage)) { <API key> = _context.LanguageMode; _context.LanguageMode = PSLanguageMode.FullLanguage; } else if (System.Management.Automation.Security.SystemPolicy.<API key>() == System.Management.Automation.Security.<API key>.Enforce) { // If there is a system lockdown in place, enforce it <API key> = _context.LanguageMode; _context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } <API key> <API key> = _context.CurrentRunspace.<API key>; _context.CurrentRunspace.<API key>( _context.CurrentRunspace.<API key>() != null ? <API key>.<API key> : <API key>.Available, true); Diagnostics.Assert(_context._debuggingMode == 1, "Should only be stopping when debugger is on."); try { <API key>(InternalDebugMode.InScriptStop); if (_callStack.Any()) { // Get-PSCallStack shouldn't report any frames above this frame, so mark it. One alternative // to marking the frame would be to not push new frames while debugging, but that limits our // ability to give a full callstack if there are errors during eval. _callStack.Last().<API key> = true; } // Reset list lines. _commandProcessor.Reset(); // Save a copy of the stop arguments. <API key> copyArgs = new <API key>(invocationInfo, breakpoints); <API key>.Push(copyArgs); // Blocking call to raise debugger stop event. <API key> e = new <API key>(invocationInfo, breakpoints); <API key>(e); ResumeExecution(e.ResumeAction); } finally { <API key>(InternalDebugMode.Enabled); if (_callStack.Any()) { _callStack.Last().<API key> = false; } _context.CurrentRunspace.<API key>(<API key>, true); if (<API key>.HasValue) { _context.LanguageMode = <API key>.Value; } _context.EngineSessionState.RemoveVariable(SpecialVariables.PSDebugContext); if (hadDefaultPrompt) { // Restore the prompt if they had our default defaultPromptInfo.Update( ScriptBlock.Create(<API key>), true, ScopedItemOptions.Unspecified); } <API key> oldArgs; <API key>.TryPop(out oldArgs); _inBreakpoint = false; } } <summary> Resumes execution after a breakpoint/step event has been handled </summary> private void ResumeExecution(<API key> action) { <API key> = <API key>; <API key> = action; switch (action) { case <API key>.StepInto: _steppingMode = SteppingMode.StepIn; _overOrOutFrame = null; break; case <API key>.StepOut: if (_callStack.Count > 1) { // When we pop to the parent frame, we'll clear _overOrOutFrame (so OnSequencePointHit // will stop) and continue with a step. _steppingMode = SteppingMode.StepIn; _overOrOutFrame = _callStack[_callStack.Count - 2]; } else { // Stepping out of the top frame is just like continue (allow hitting // breakpoints in the current frame, but otherwise just go.) goto case <API key>.Continue; } break; case <API key>.StepOver: _steppingMode = SteppingMode.StepIn; _overOrOutFrame = _callStack.Last(); break; case <API key>.Continue: // nothing to do, just continue _steppingMode = SteppingMode.None; _overOrOutFrame = null; break; case <API key>.Stop: _steppingMode = SteppingMode.None; _overOrOutFrame = null; throw new TerminateException(); default: Debug.Assert(false, "Received an unknown action: " + action); break; } } <summary> Blocking call that blocks until a release occurs via <API key>(). </summary> <returns>True if there is a DebuggerStop event subscriber.</returns> private bool <API key>() { if (!<API key>()) { if (<API key>) { // Lazily create the event object. if (<API key> == null) { <API key> = new <API key>(true); } // Set the event handle to non-signaled. if (!<API key>.IsSet) { Diagnostics.Assert(false, "The _preserveDebugStop event handle should always be in the signaled state at this point."); return false; } <API key>.Reset(); // Wait indefinitely for a signal event. <API key>.Wait(); return <API key>(); } return false; } return true; } private enum SteppingMode { StepIn, None } // When a script file changes, we need to rebind all breakpoints in that script. private void <API key>(List<LineBreakpoint> boundBreakpoints) { foreach (var breakpoint in boundBreakpoints) { // Also remove unbound breakpoints from the script to breakpoint map. Tuple<List<LineBreakpoint>, BitArray> lineBreakTuple; if (<API key>.TryGetValue(breakpoint.SequencePoints, out lineBreakTuple)) { lineBreakTuple.Item1.Remove(breakpoint); } breakpoint.SequencePoints = null; breakpoint.SequencePointIndex = -1; breakpoint.BreakpointBitArray = null; _pendingBreakpoints.Add(breakpoint); } boundBreakpoints.Clear(); } private void <API key>(FunctionContext functionContext) { if (!_pendingBreakpoints.Any()) return; var <API key> = new List<LineBreakpoint>(); var currentScriptFile = functionContext._file; // If we're not in a file, we can't have any line breakpoints. if (currentScriptFile == null) return; // Normally we register a script file when the script is run or the module is imported, // but if there weren't any breakpoints when the script was run and the script was dotted, // we will end up here with pending breakpoints, but we won't have cached the list of // breakpoints in the script. RegisterScriptFile(currentScriptFile, functionContext.CurrentPosition.StartScriptPosition.GetFullScript()); Tuple<List<LineBreakpoint>, BitArray> tuple; if (!<API key>.TryGetValue(functionContext._sequencePoints, out tuple)) { Diagnostics.Assert(false, "If the script block is still alive, the entry should not be collected."); } Diagnostics.Assert(tuple.Item1 == functionContext._boundBreakpoints, "What's up?"); foreach (var breakpoint in _pendingBreakpoints) { bool bound = false; if (breakpoint.TrySetBreakpoint(currentScriptFile, functionContext)) { if (_context._debuggingMode == 0) { <API key>(InternalDebugMode.Enabled); } bound = true; tuple.Item1.Add(breakpoint); // We need to keep track of any breakpoints that are bound in each script because they may // need to be rebound if the script changes. var boundBreakpoints = _boundBreakpoints[currentScriptFile].Item2; Diagnostics.Assert(boundBreakpoints.IndexOf(breakpoint) < 0, "Don't add more than once."); boundBreakpoints.Add(breakpoint); } if (!bound) { <API key>.Add(breakpoint); } } _pendingBreakpoints = <API key>; } private void StopOnSequencePoint(FunctionContext functionContext, List<Breakpoint> breakpoints) { if (functionContext._debuggerHidden) { // Never stop in a DebuggerHidden scriptblock. return; } if (functionContext._sequencePoints.Length == 1 && functionContext._scriptBlock != null && object.ReferenceEquals(functionContext._sequencePoints[0], functionContext._scriptBlock.Ast.Extent)) { // If the script is empty or only defines functions, we used the script block extent as a sequence point, but that // was only intended for error reporting, it was not meant to be hit as a breakpoint. return; } var invocationInfo = new InvocationInfo(null, functionContext.CurrentPosition, _context); OnDebuggerStop(invocationInfo, breakpoints); } private enum InternalDebugMode { InPushedStop = -2, InScriptStop = -1, Disabled = 0, Enabled = 1 } <summary> Sets the internal Execution context debug mode given the current DebugMode setting. </summary> <param name="mode">Internal debug mode</param> private void <API key>(InternalDebugMode mode) { lock (_syncObject) { switch (mode) { case InternalDebugMode.InPushedStop: case InternalDebugMode.InScriptStop: case InternalDebugMode.Disabled: _context._debuggingMode = (int)mode; break; case InternalDebugMode.Enabled: _context._debuggingMode = CanEnableDebugger ? (int)InternalDebugMode.Enabled : (int)InternalDebugMode.Disabled; break; } } } private bool CanEnableDebugger { get { // The debugger can be enabled if we are not in DebugMode.None and if we are // not in a local session set only to RemoteScript. return !((DebugMode == DebugModes.RemoteScript) && IsLocalSession) && (DebugMode != DebugModes.None); } } #region Enable debug stepping [Flags] private enum EnableNestedType { None = 0x0, NestedJob = 0x1, NestedRunspace = 0x2 } private void <API key>(EnableNestedType nestedType) { if (DebugMode == DebugModes.None) { throw new <API key>( DebuggerStrings.<API key>, null, Debugger.<API key>, ErrorCategory.InvalidOperation, null); } lock (_syncObject) { if (_context._debuggingMode == 0) { <API key>(InternalDebugMode.Enabled); } Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { // Set active debugger to StepInto mode. activeDebugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript); activeDebugger.SetDebuggerStepMode(true); } else { // Set script debugger to StepInto mode. ResumeExecution(<API key>.StepInto); } } #if !CORECLR // Workflow Not Supported on OneCore PS // Look for any running workflow jobs and set to step mode. if ((nestedType & EnableNestedType.NestedJob) == EnableNestedType.NestedJob) { <API key>(); } #endif // Look for any runspaces with debuggers and set to setp mode. if ((nestedType & EnableNestedType.NestedRunspace) == EnableNestedType.NestedRunspace) { <API key>(true); } } <summary> Restores debugger back to non-step mode. </summary> private void <API key>() { if (!<API key>) { return; } lock (_syncObject) { ResumeExecution(<API key>.Continue); <API key>(); Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { activeDebugger.SetDebuggerStepMode(false); } } <API key>(false); <API key>(false); } private void <API key>() { InternalDebugMode restoreMode = ((DebugMode != DebugModes.None) && (_idToBreakpoint.Count > 0)) ? InternalDebugMode.Enabled : InternalDebugMode.Disabled; <API key>(restoreMode); } #endregion #endregion #region Debugger Overrides <summary> Set ScriptDebugger action. </summary> <param name="resumeAction"><API key></param> public override void SetDebuggerAction(<API key> resumeAction) { throw new <API key>( StringUtil.Format(DebuggerStrings.<API key>)); } <summary> GetDebuggerStopped </summary> <returns><API key></returns> public override <API key> GetDebuggerStopArgs() { <API key> rtnArgs; if (<API key>.TryPeek(out rtnArgs)) { return rtnArgs; } return null; } <summary> ProcessCommand </summary> <param name="command">PowerShell command</param> <param name="output">Output</param> <returns><API key></returns> public override <API key> ProcessCommand(PSCommand command, PSDataCollection<PSObject> output) { if (command == null) { throw new <API key>("command"); } if (output == null) { throw new <API key>("output"); } if (!DebuggerStopped) { throw new <API key>( DebuggerStrings.<API key>, null, Debugger.<API key>, ErrorCategory.InvalidOperation, null); } // // Allow an active pushed debugger to process commands // <API key> results = <API key>(command, output); if (results != null) { return results; } // // Otherwise let root script debugger handle it. // LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace; if (localRunspace == null) { throw new <API key>( DebuggerStrings.<API key>, null, Debugger.<API key>, ErrorCategory.InvalidOperation, null); } try { using (_psDebuggerCommand = PowerShell.Create()) { if (localRunspace.<API key>() != null) { _psDebuggerCommand.SetIsNested(true); } _psDebuggerCommand.Runspace = localRunspace; _psDebuggerCommand.Commands = command; foreach (var cmd in _psDebuggerCommand.Commands.Commands) { cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output); } PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>(); internalOutput.DataAdded += (sender, args) => { foreach (var item in internalOutput.ReadAll()) { if (item == null) { continue; } DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand; if (dbgCmd != null) { bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger); results = new <API key>(dbgCmd.ResumeAction, executedByDebugger); } else { output.Add(item); } } }; // Allow any exceptions to propagate. _psDebuggerCommand.InvokeWithDebugger(null, internalOutput, null, false); } } finally { _psDebuggerCommand = null; } return results ?? new <API key>(null, false); } <summary> StopProcessCommand </summary> public override void StopProcessCommand() { // // If we have a pushed debugger then stop that command. // if (<API key>()) { return; } PowerShell ps = _psDebuggerCommand; if (ps != null) { ps.BeginStop(null, null); } } <summary> Set debug mode </summary> <param name="mode"></param> public override void SetDebugMode(DebugModes mode) { lock (_syncObject) { base.SetDebugMode(mode); if (!CanEnableDebugger) { <API key>(InternalDebugMode.Disabled); } else if ((_idToBreakpoint.Count > 0) && (_context._debuggingMode == 0)) { // Set internal debugger to active. <API key>(InternalDebugMode.Enabled); } } } <summary> Returns current call stack. </summary> <returns>IEnumerable of CallStackFrame objects</returns> public override IEnumerable<CallStackFrame> GetCallStack() { CallStackInfo[] callStack = _callStack.ToArray(); if (callStack.Length > 0) { int startingIndex = callStack.Length - 1; for (int i = startingIndex; i >= 0; i--) { if (callStack[i].<API key>) { startingIndex = i; break; } } for (int i = startingIndex; i >= 0; i--) { var funcContext = callStack[i].FunctionContext; yield return new CallStackFrame(funcContext, callStack[i].InvocationInfo); } } } <summary> SetBreakpoints </summary> <param name="breakpoints"></param> public override void SetBreakpoints(IEnumerable<Breakpoint> breakpoints) { if (breakpoints == null) { throw new <API key>("breakpoints"); } foreach (var breakpoint in breakpoints) { if (_idToBreakpoint.ContainsKey(breakpoint.Id)) { continue; } LineBreakpoint lineBp = breakpoint as LineBreakpoint; if (lineBp != null) { AddLineBreakpoint(lineBp); continue; } CommandBreakpoint cmdBp = breakpoint as CommandBreakpoint; if (cmdBp != null) { <API key>(cmdBp); continue; } VariableBreakpoint variableBp = breakpoint as VariableBreakpoint; if (variableBp != null) { <API key>(variableBp); } } } <summary> True when debugger is active with breakpoints. </summary> public override bool IsActive { get { int debuggerState = _context._debuggingMode; return (debuggerState != 0); } } <summary> Resets the command processor source information so that it is updated with latest information on the next debug stop. </summary> public override void <API key>() { _commandProcessor.Reset(); } <summary> Sets debugger stepping mode. </summary> <param name="enabled">True if stepping is to be enabled</param> public override void SetDebuggerStepMode(bool enabled) { if (enabled) { <API key>(EnableNestedType.NestedJob | EnableNestedType.NestedRunspace); } else { <API key>(); } } <summary> Passes the debugger command to the internal script debugger command processor. This is used internally to handle debugger commands such as list, help, etc. </summary> <param name="command">Command string</param> <param name="output">output</param> <returns>DebuggerCommand containing information on whether and how the command was processed.</returns> internal override DebuggerCommand <API key>(string command, IList<PSObject> output) { if (!DebuggerStopped) { return new DebuggerCommand(command, null, false, false); } // "Exit" command should always result with "Continue" behavior for legacy compatibility. if (command.Equals("exit", StringComparison.OrdinalIgnoreCase)) { return new DebuggerCommand(command, <API key>.Continue, false, true); } return _commandProcessor.ProcessCommand(null, command, <API key>, output); } <summary> Creates a source list based on root script debugger source information if available, with the current source line highlighted. This is used internally for nested runspace debugging where the runspace command is run in context of a parent script. </summary> <param name="lineNum">Current source line</param> <param name="output">Output collection</param> <returns>True if source listed successfully</returns> internal override bool <API key>(int lineNum, IList<PSObject> output) { if (!DebuggerStopped || (<API key> == null)) { return false; } // Create an Invocation object that has full source script from script debugger plus // line information provided from caller. string fullScript = <API key>.GetFullScript(); ScriptPosition startScriptPosition = new ScriptPosition( <API key>.ScriptName, lineNum, <API key>.ScriptPosition.StartScriptPosition.Offset, <API key>.Line, fullScript); ScriptPosition endScriptPosition = new ScriptPosition( <API key>.ScriptName, lineNum, <API key>.ScriptPosition.StartScriptPosition.Offset, <API key>.Line, fullScript); InvocationInfo tempInvocationInfo = InvocationInfo.Create( <API key>.MyCommand, new ScriptExtent( startScriptPosition, endScriptPosition) ); _commandProcessor.ProcessListCommand(tempInvocationInfo, output); return true; } <summary> IsRemote </summary> internal override bool IsRemote { get { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { return (activeDebugger is RemotingJobDebugger); } return false; } } <summary> Array of stack frame objects of active debugger if any, otherwise null. </summary> <returns>CallStackFrame[]</returns> internal override CallStackFrame[] <API key>() { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { return activeDebugger.GetCallStack().ToArray(); } return null; } <summary> Sets how the debugger deals with breakpoint events that are not handled. Ignore - This is the default behavior and ignores any breakpoint event if there is no handler. Releases any preserved event. Wait - This mode preserves a breakpoint event until a handler is subscribed. </summary> internal override <API key> <API key> { get { return (<API key>) ? <API key>.Wait : <API key>.Ignore; } set { switch (value) { case <API key>.Wait: <API key> = true; break; case <API key>.Ignore: <API key> = false; <API key>(); break; } } } #region Job Debugging <summary> Sets up debugger to debug provided job or its child jobs. </summary> <param name="job"> Job object that is either a debuggable job or a container of debuggable child jobs. </param> internal override void DebugJob(Job job) { if (job == null) { throw new <API key>("job"); } lock (_syncObject) { if (_context._debuggingMode < 0) { throw new RuntimeException(DebuggerStrings.<API key>); } } // If a debuggable job was passed in then add it to the // job running list. bool jobsAdded = TryAddDebugJob(job); if (!jobsAdded) { // Otherwise treat as parent Job and iterate over child jobs. foreach (Job childJob in job.ChildJobs) { if (TryAddDebugJob(childJob) && !jobsAdded) { jobsAdded = true; } } } if (!jobsAdded) { throw new <API key>(DebuggerStrings.<API key>); } } private bool TryAddDebugJob(Job job) { IJobDebugger debuggableJob = job as IJobDebugger; if ((debuggableJob != null) && (debuggableJob.Debugger != null) && ((job.JobStateInfo.State == JobState.Running) || (job.JobStateInfo.State == JobState.AtBreakpoint))) { // Check to see if job is already stopped in debugger. bool <API key> = debuggableJob.Debugger.InBreakpoint; // Add to running job list with debugger set to step into. SetDebugJobAsync(debuggableJob, false); AddToJobRunningList( new PSJobStartEventArgs(job, debuggableJob.Debugger, false), <API key>.StepInto); // Raise debug stop event if job is already in stopped state. if (<API key>) { RemotingJobDebugger remoteJobDebugger = debuggableJob.Debugger as RemotingJobDebugger; if (remoteJobDebugger != null) { remoteJobDebugger.<API key>(); } else { Diagnostics.Assert(false, "Should never get debugger stopped job that is not of RemotingJobDebugger type."); } } return true; } return false; } <summary> Removes job from debugger job list and pops its debugger from the active debugger stack. </summary> <param name="job">Job</param> internal override void StopDebugJob(Job job) { // Parameter validation. if (job == null) { throw new <API key>("job"); } <API key>(InternalDebugMode.Disabled); <API key>(job); SetDebugJobAsync(job as IJobDebugger, true); foreach (var cJob in job.ChildJobs) { <API key>(cJob); SetDebugJobAsync(cJob as IJobDebugger, true); } <API key>(); } <summary> Helper method to set a IJobDebugger job CanDebug property. </summary> <param name="debuggableJob">IJobDebugger</param> <param name="isAsync">Boolean</param> internal static void SetDebugJobAsync(IJobDebugger debuggableJob, bool isAsync) { if (debuggableJob != null) { debuggableJob.IsAsync = isAsync; } } #endregion #region Runspace Debugging <summary> Sets up debugger to debug provided Runspace in a nested debug session. </summary> <param name="runspace">Runspace to debug</param> internal override void DebugRunspace(Runspace runspace) { if (runspace == null) { throw new <API key>("runspace"); } if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) { throw new <API key>( string.Format(CultureInfo.InvariantCulture, DebuggerStrings.<API key>, runspace.RunspaceStateInfo.State) ); } lock (_syncObject) { if (_context._debuggingMode < 0) { throw new <API key>(DebuggerStrings.<API key>); } } if (runspace.Debugger == null) { throw new <API key>( string.Format(CultureInfo.InvariantCulture, DebuggerStrings.<API key>, runspace.Name)); } if (runspace.Debugger.DebugMode == DebugModes.None) { throw new <API key>(DebuggerStrings.<API key>); } <API key>(new <API key>(runspace)); if (!runspace.Debugger.InBreakpoint) { <API key>(EnableNestedType.NestedRunspace); } } <summary> Removes the provided Runspace from the nested "active" debugger state. </summary> <param name="runspace">Runspace</param> internal override void StopDebugRunspace(Runspace runspace) { if (runspace == null) { throw new <API key>("runspace"); } <API key>(InternalDebugMode.Disabled); <API key>(runspace); <API key>(); } #endregion #endregion #region Job debugger integration #if !CORECLR // Workflow Not Supported on OneCore PS private void <API key>() { Diagnostics.Assert(_context.Events != null, "Event manager cannot be null."); _context.Events.SubscribeEvent( source: null, eventName: null, sourceIdentifier: PSEngineEvent.<API key>, data: null, handlerDelegate: HandleJobStartEvent, supportEvent: true, forwardEvent: false); <API key> = true; } private void <API key>() { PSEventManager eventManager = _context.Events; Diagnostics.Assert(eventManager != null, "Event manager cannot be null."); foreach (var subscriber in eventManager.GetEventSubscribers(PSEngineEvent.<API key>)) { eventManager.UnsubscribeEvent(subscriber); } <API key> = false; } private void HandleJobStartEvent(object sender, PSEventArgs args) { Diagnostics.Assert(args.SourceArgs.Length == 1, "WF Job Started engine event SourceArgs should have a single element."); PSJobStartEventArgs jobStartedArgs = args.SourceArgs[0] as PSJobStartEventArgs; Diagnostics.Assert(jobStartedArgs != null, "WF Job Started engine event args cannot be null."); Diagnostics.Assert(jobStartedArgs.Job != null, "WF Job to start cannot be null."); Diagnostics.Assert(jobStartedArgs.Debugger != null, "WF Job Started Debugger object cannot be null."); if (!(jobStartedArgs.Debugger.GetType().FullName.Equals("Microsoft.PowerShell.Workflow.PSWorkflowDebugger", StringComparison.OrdinalIgnoreCase))) { // Check to ensure only PS workflow debuggers can be passed in. throw new <API key>(); } // At this point the script debugger stack frame must be the Workflow execution function which is DebuggerHidden. // The internal debugger resume action is set to StepOut, *if* the user selected StepIn, so as to skip this frame // since debugging the workflow execution function is turned off. We look at the previous resume action to see // what the user intended. If it is StepIn then we start the workflow job debugger in step mode. Diagnostics.Assert(_callStack.LastFunctionContext()._debuggerHidden, "Current stack frame must be WF function DebuggerHidden"); <API key> startAction = (<API key> == <API key>.StepInto) ? <API key>.StepInto : <API key>.Continue; AddToJobRunningList(jobStartedArgs, startAction); } #endif private void AddToJobRunningList(PSJobStartEventArgs jobArgs, <API key> startAction) { bool newJob = false; lock (_syncObject) { jobArgs.Job.StateChanged += <API key>; if (jobArgs.Job.IsPersistentState(jobArgs.Job.JobStateInfo.State)) { jobArgs.Job.StateChanged -= <API key>; return; } if (!_runningJobs.ContainsKey(jobArgs.Job.InstanceId)) { // For now ignore WF jobs started asynchronously from script. if (jobArgs.IsAsync) { return; } // Turn on output processing monitoring on workflow job so that // the debug stop events can coordinate with end of output processing. jobArgs.Job.<API key> += <API key>; jobArgs.Job.<API key> = true; _runningJobs.Add(jobArgs.Job.InstanceId, jobArgs); jobArgs.Debugger.DebuggerStop += <API key>; jobArgs.Debugger.BreakpointUpdated += <API key>; newJob = true; } } if (newJob) { jobArgs.Debugger.SetParent( this, _idToBreakpoint.Values.ToArray<Breakpoint>(), startAction, _context.EngineHostInterface.ExternalHost, _context.SessionState.Path.CurrentLocation, <API key>()); } else { // If job already in collection then make sure start action is set. // Note that this covers the case where Debug-Job was performed on // an async job, which then becomes sync, the user continues execution // and then wants to break (step mode) into the debugger *again*. jobArgs.Debugger.SetDebuggerStepMode(true); } } private void <API key>(bool enableStepping) { PSJobStartEventArgs[] runningJobs; lock (_syncObject) { runningJobs = _runningJobs.Values.ToArray(); } foreach (var item in runningJobs) { try { item.Debugger.SetDebuggerStepMode(enableStepping); } catch (<API key>) { } } } private void <API key>(bool enableStepping) { <API key>[] runspaceList; lock (_syncObject) { runspaceList = _runningRunspaces.Values.ToArray(); } foreach (var item in runspaceList) { try { Debugger nestedDebugger = item.NestedDebugger; if (nestedDebugger != null) { nestedDebugger.SetDebuggerStepMode(enableStepping); } } catch (<API key>) { } } } private Dictionary<string, DebugSource> <API key>() { Dictionary<string, DebugSource> fnToSource = new Dictionary<string, DebugSource>(); // Get workflow function source information for workflow debugger. Collection<PSObject> items = _context.SessionState.InvokeProvider.Item.Get("function:\\*"); foreach (var item in items) { var funcItem = item.BaseObject as WorkflowInfo; if ((funcItem != null) && (!string.IsNullOrEmpty(funcItem.Name))) { if ((funcItem.Module != null) && (funcItem.Module.Path != null)) { string scriptFile = funcItem.Module.Path; string scriptSource = GetFunctionSource(scriptFile); if (scriptSource != null) { fnToSource.Add( funcItem.Name, new DebugSource( scriptSource, scriptFile, funcItem.XamlDefinition)); } } } } return fnToSource; } private string GetFunctionSource( string scriptFile) { if (System.IO.File.Exists(scriptFile)) { try { return System.IO.File.ReadAllText(scriptFile); } catch (ArgumentException) { } catch (System.IO.IOException) { } catch (Un<API key>) { } catch (<API key>) { } catch (System.Security.SecurityException) { } } return null; } private void <API key>(Job job) { job.StateChanged -= <API key>; job.<API key> -= <API key>; PSJobStartEventArgs jobArgs = null; lock (_syncObject) { if (_runningJobs.TryGetValue(job.InstanceId, out jobArgs)) { jobArgs.Debugger.DebuggerStop -= <API key>; jobArgs.Debugger.BreakpointUpdated -= <API key>; _runningJobs.Remove(job.InstanceId); } } if (jobArgs != null) { // Pop from active debugger stack. lock (<API key>) { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { if (activeDebugger.Equals(jobArgs.Debugger)) { PopActiveDebugger(); } } } } } private void ClearRunningJobList() { #if !CORECLR // Workflow Not Supported on OneCore PS <API key>(); #endif PSJobStartEventArgs[] runningJobs = null; lock (_syncObject) { if (_runningJobs.Count > 0) { runningJobs = new PSJobStartEventArgs[_runningJobs.Values.Count]; _runningJobs.Values.CopyTo(runningJobs, 0); } } if (runningJobs != null) { foreach (var item in runningJobs) { <API key>(item.Job); } } } private bool PushActiveDebugger(Debugger debugger, int callstackOffset) { // Don't push active debugger if script debugger disabled debugging. if (_context._debuggingMode == -1) { return false; } // Disable script debugging while another debugger is running. // -1 - Indicates script debugging is disabled from script debugger. // -2 - Indicates script debugging is disabled from pushed active debugger. <API key>(InternalDebugMode.InPushedStop); // Save running calling frame. _nestedRunningFrame = _callStack[_callStack.Count - callstackOffset]; _commandProcessor.Reset(); // Make active debugger. _activeDebuggers.Push(debugger); return true; } private Debugger PopActiveDebugger() { Debugger poppedDebugger = null; if (_activeDebuggers.TryPop(out poppedDebugger)) { int runningJobCount; lock (_syncObject) { runningJobCount = _runningJobs.Count; } if (runningJobCount == 0) { // If we are back to the root debugger and are in step mode, ensure // that the root debugger is in step mode to continue stepping. switch (<API key>) { case <API key>.StepInto: case <API key>.StepOver: case <API key>.StepOut: // Set script debugger to step mode after the WF running // script completes. _steppingMode = SteppingMode.StepIn; _overOrOutFrame = _nestedRunningFrame; _nestedRunningFrame = null; break; case <API key>.Stop: _nestedDebuggerStop = true; break; default: ResumeExecution(<API key>.Continue); break; } // Allow script debugger to continue in debugging mode. <API key> = 0; <API key>(InternalDebugMode.Enabled); <API key> = <API key>; <API key> = <API key>.Continue; } } return poppedDebugger; } private void <API key>(object sender, <API key> args) { // If we are debugging nested runspaces then ignore job debugger stops if (_runningRunspaces.Count > 0) { return; } // Forward active debugger event. if (args != null) { // Save copy of arguments. <API key> copyArgs = new <API key>( args.InvocationInfo, new Collection<Breakpoint>(args.Breakpoints), args.ResumeAction); <API key>.Push(copyArgs); CallStackInfo savedCallStackItem = null; try { // Wait for up to 5 seconds for output processing to complete. <API key>.Wait(5000); // Fix up call stack representing this WF call. savedCallStackItem = FixUpCallStack(); // Blocking call that raises stop event. <API key>(args); <API key> = args.ResumeAction; } finally { RestoreCallStack(savedCallStackItem); <API key>.TryPop(out copyArgs); } } } private CallStackInfo FixUpCallStack() { // Remove the top level call stack item, which is // the PS script that starts the workflow. The workflow // debugger will add its call stack in its GetCallStack() // override. int count = _callStack.Count; CallStackInfo item = null; if (count > 1) { item = _callStack.Last(); _callStack.RemoveAt(count - 1); } return item; } private void RestoreCallStack(CallStackInfo item) { if (item != null) { _callStack.Add(item); } } private void <API key>(object sender, <API key> args) { if (!IsJobDebuggingMode()) { #if !CORECLR // Workflow Not Supported on OneCore PS // Remove workflow job callback. <API key>(); // Write warning to user. <API key>(); #endif // Ignore job debugger stop. args.ResumeAction = <API key>.Continue; return; } Debugger senderDebugger = sender as Debugger; lock (<API key>) { Debugger activeDebugger = null; if (_activeDebuggers.TryPeek(out activeDebugger)) { if (activeDebugger.Equals(senderDebugger)) { <API key>(sender, args); return; } if (<API key>(activeDebugger)) { // Replace current job active debugger by first popping. PopActiveDebugger(); } } if (PushActiveDebugger(senderDebugger, _jobCallStackOffset)) { // Forward the debug stop event. <API key>(sender, args); } } } private bool IsJobDebuggingMode() { return ((((DebugMode & DebugModes.LocalScript) == DebugModes.LocalScript) && IsLocalSession) || (((DebugMode & DebugModes.RemoteScript) == DebugModes.RemoteScript) && !IsLocalSession)); } private void <API key>(object sender, <API key> e) { switch (e.UpdateType) { case <API key>.Set: AddNewBreakpoint(e.Breakpoint); break; case <API key>.Removed: RemoveBreakpoint(e.Breakpoint); break; case <API key>.Enabled: EnableBreakpoint(e.Breakpoint); break; case <API key>.Disabled: DisableBreakpoint(e.Breakpoint); break; } } private bool <API key>(Debugger debugger) { lock (_syncObject) { foreach (var item in _runningJobs.Values) { if (item.Debugger.Equals(debugger)) { return true; } } } return false; } private void <API key>(object sender, JobStateEventArgs args) { Job job = sender as Job; if (job.IsPersistentState(args.JobStateInfo.State)) { <API key>(job); } } private void <API key>(object sender, <API key> e) { lock (_syncObject) { if (e.ProcessingOutput) { if (++<API key> == 1) { <API key>.Reset(); } } else if (<API key> > 0) { if (--<API key> == 0) { <API key>.Set(); } } } } private <API key> <API key>(PSCommand command, PSDataCollection<PSObject> output) { // Check for debugger "detach" command which is only applicable to nested debugging. bool detachCommand = ((command.Commands.Count > 0) && ((command.Commands[0].CommandText.Equals("Detach", StringComparison.OrdinalIgnoreCase)) || (command.Commands[0].CommandText.Equals("d", StringComparison.OrdinalIgnoreCase)))); Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { if (detachCommand) { // Exit command means to cancel the nested debugger session. This needs to be done by the // owner of the session so we raise an event and release the debugger stop. <API key> = <API key>.Ignore; <API key>(); return new <API key>(<API key>.Continue, true); } else if ((command.Commands.Count > 0) && (command.Commands[0].CommandText.IndexOf(".EnterNestedPrompt()", StringComparison.OrdinalIgnoreCase) > 0)) { // Prevent a host EnterNestedPrompt() call from occuring in an active debugger. // Host nested prompt makes no sense in this case and can cause hangs depending on host implementation. throw new <API key>(); } // Get current debugger stop breakpoint info. <API key> stopArgs; if (<API key>.TryPeek(out stopArgs)) { string commandText = command.Commands[0].CommandText; // Check to see if this is a resume command that we handle here. DebuggerCommand dbgCommand = _commandProcessor.ProcessBasicCommand(commandText); if (dbgCommand != null && dbgCommand.ResumeAction != null) { <API key> = dbgCommand.ResumeAction.Value; return new <API key>(dbgCommand.ResumeAction, true); } // If active debugger is Workflow debugger then process command here (for "list" and "help"). if (activeDebugger.GetType().FullName.Equals("Microsoft.PowerShell.Workflow.PSWorkflowDebugger", StringComparison.OrdinalIgnoreCase)) { DebuggerCommand results = _commandProcessor.ProcessCommand(null, commandText, stopArgs.InvocationInfo, output); if ((results != null) && results.ExecutedByDebugger) { return new <API key>(results.ResumeAction, true); } } } return activeDebugger.ProcessCommand(command, output); } if (detachCommand) { // Detach command only applies to nested debugging. So if there isn't any active debugger then emit error. throw new <API key>(DebuggerStrings.<API key>); } return null; } private bool <API key>() { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { activeDebugger.StopProcessCommand(); return true; } return false; } private void <API key>() { if (!_writeWFErrorOnce) { var host = _context.EngineHostInterface.ExternalHost; if (host != null && host.UI != null) { host.UI.WriteErrorLine(DebuggerStrings.<API key>); } _writeWFErrorOnce = true; } } #if !CORECLR // Workflow Not Supported on OneCore PS private void <API key>() { // Make sure workflow job start callback is set to pick // up any newly starting jobs. if (!<API key>) { lock (_syncObject) { if (!<API key>) { <API key>(); } } } // Get list of workflow jobs Collection<Job> jobs; using (PowerShell ps = PowerShell.Create()) { ps.Commands.Clear(); ps.AddScript(@"Get-Job | ? {$_.PSJobTypeName -eq 'PSWorkflowJob'}"); jobs = ps.Invoke<Job>(); } // Add debuggable workflow jobs to running Job list // and set debugger to step mode. foreach (var parentJob in jobs) { if (parentJob != null) { foreach (var childJob in parentJob.ChildJobs) { IJobDebugger debuggableJob = childJob as IJobDebugger; if (debuggableJob != null) { AddToJobRunningList( new PSJobStartEventArgs( childJob, debuggableJob.Debugger, debuggableJob.IsAsync), <API key>.StepInto); } } } } // Ensure existing running jobs in list are also set to step mode. <API key>(true); } #endif #endregion #region Runspace debugger integration internal override void <API key>(<API key> runspaceInfo) { if (runspaceInfo == null || runspaceInfo.Runspace == null) { return; } if ((runspaceInfo.Runspace.Debugger != null) && runspaceInfo.Runspace.Debugger.Equals(this)) { Debug.Assert(false, "Nested debugger cannot be the root debugger."); return; } <API key> startAction = (<API key> == <API key>.StepInto) ? <API key>.StepInto : <API key>.Continue; <API key>(runspaceInfo.Copy()); } internal override void <API key>(<API key> runspaceInfo) { if (runspaceInfo == null || runspaceInfo.Runspace == null) { return; } <API key>(runspaceInfo.Runspace); } <summary> If a debug stop event is currently pending then this method will release the event to continue processing. </summary> internal override void <API key>() { if (<API key>) { <API key>.Set(); } } private void <API key>(<API key> args) { Runspace runspace = args.Runspace; runspace.StateChanged += <API key>; RunspaceState rsState = runspace.RunspaceStateInfo.State; if (rsState == RunspaceState.Broken || rsState == RunspaceState.Closed || rsState == RunspaceState.Disconnected) { runspace.StateChanged -= <API key>; return; } lock (_syncObject) { if (!_runningRunspaces.ContainsKey(runspace.InstanceId)) { _runningRunspaces.Add(runspace.InstanceId, args); } } // It is possible for the debugger to be non-null at this point if a runspace // is being reused. <API key>(runspace); } private void <API key>(Runspace runspace) { runspace.StateChanged -= <API key>; // Remove from running list. <API key> runspaceInfo = null; lock (_syncObject) { if (_runningRunspaces.TryGetValue(runspace.InstanceId, out runspaceInfo)) { _runningRunspaces.Remove(runspace.InstanceId); } } // Clean up nested debugger. <API key> nestedDebugger = (runspaceInfo != null) ? runspaceInfo.NestedDebugger : null; if (nestedDebugger != null) { nestedDebugger.DebuggerStop -= <API key>; nestedDebugger.BreakpointUpdated -= <API key>; nestedDebugger.Dispose(); // If current active debugger, then pop. lock (<API key>) { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { if (activeDebugger.Equals(nestedDebugger)) { PopActiveDebugger(); } } } } } private void <API key>() { <API key>[] runningRunspaces = null; lock (_syncObject) { if (_runningRunspaces.Count > 0) { runningRunspaces = new <API key>[_runningRunspaces.Count]; _runningRunspaces.Values.CopyTo(runningRunspaces, 0); } } if (runningRunspaces != null) { foreach (var item in runningRunspaces) { <API key>(item.Runspace); } } } private void <API key>(object sender, <API key> e) { Runspace runspace = sender as Runspace; bool remove = false; switch (e.RunspaceStateInfo.State) { // Detect transition to Opened state. case RunspaceState.Opened: remove = !<API key>(runspace); break; // Detect any transition to a finished runspace. case RunspaceState.Broken: case RunspaceState.Closed: case RunspaceState.Disconnected: remove = true; break; } if (remove) { <API key>(runspace); } } private void <API key>(object sender, <API key> args) { if (sender == null || args == null) { return; } Debugger senderDebugger = sender as Debugger; lock (<API key>) { Debugger activeDebugger; if (_activeDebuggers.TryPeek(out activeDebugger)) { // Replace current runspace debugger by first popping the old debugger. if (IsRunningRSDebugger(activeDebugger)) { PopActiveDebugger(); } } // Get nested debugger runspace info. <API key> nestedDebugger = senderDebugger as <API key>; if (nestedDebugger == null) { return; } <API key> runspaceType = nestedDebugger.RunspaceType; // If this is a workflow debugger then ensure that there is a current active // debugger that is the associated job debugger for this inline script WF runspace. if (runspaceType == <API key>.<API key>) { bool <API key> = true; if (_activeDebuggers.TryPeek(out activeDebugger)) { <API key> = (activeDebugger.InstanceId != nestedDebugger.ParentDebuggerId); if (<API key>) { // Pop incorrect active debugger. PopActiveDebugger(); } } if (<API key>) { PSJobStartEventArgs wfJobArgs = null; lock (_syncObject) { _runningJobs.TryGetValue(nestedDebugger.ParentDebuggerId, out wfJobArgs); } if (wfJobArgs == null) { Diagnostics.Assert(false, "We should never get a WF job InlineScript debugger without an associated WF parent job."); return; } PushActiveDebugger(wfJobArgs.Debugger, _jobCallStackOffset); } } // Fix up invocation info script extents for embedded nested debuggers where the script source is // from the parent. args.InvocationInfo = nestedDebugger.FixupInvocationInfo(args.InvocationInfo); // Finally push the runspace debugger. if (PushActiveDebugger(senderDebugger, <API key>)) { // Forward the debug stop event. // This method will always pop the debugger after debugger stop completes. <API key>(sender, args); } } } private void <API key>(object sender, <API key> args) { // Save copy of arguments. <API key> copyArgs = new <API key>( args.InvocationInfo, new Collection<Breakpoint>(args.Breakpoints), args.ResumeAction); <API key>.Push(copyArgs); // Forward active debugger event. try { // Blocking call that raises the stop event. <API key>(args); <API key> = args.ResumeAction; } catch (Exception ex) { // Catch all external user generated exceptions thrown on event thread. <API key>.<API key>(ex); } finally { <API key>.TryPop(out copyArgs); PopActiveDebugger(); } } private bool IsRunningRSDebugger(Debugger debugger) { lock (_syncObject) { foreach (var item in _runningRunspaces.Values) { if (item.Runspace.Debugger.Equals(debugger)) { return true; } } } return false; } private bool <API key>(Runspace runspace) { <API key> runspaceInfo = null; lock (_syncObject) { _runningRunspaces.TryGetValue(runspace.InstanceId, out runspaceInfo); } // Create nested debugger wrapper if it is not already created and if // the runspace debugger is available. if ((runspace.Debugger != null) && (runspaceInfo != null) && (runspaceInfo.NestedDebugger == null)) { try { <API key> nestedDebugger = runspaceInfo.CreateDebugger(this); runspaceInfo.NestedDebugger = nestedDebugger; nestedDebugger.DebuggerStop += <API key>; nestedDebugger.BreakpointUpdated += <API key>; if (((<API key> == <API key>.StepInto) || (<API key> == <API key>.StepInto)) && !nestedDebugger.IsActive) { nestedDebugger.SetDebuggerStepMode(true); } // If the nested debugger has a pending (saved) debug stop then // release it here now that we have the debug stop handler added. // Note that the DebuggerStop event is raised on the original execution // thread in the debugger (not this thread). nestedDebugger.<API key>(); return true; } catch (<API key>) { } } return false; } #endregion #region IDisposable <summary> Dispose </summary> public void Dispose() { #if !CORECLR // Workflow Not Supported on OneCore PS <API key>(); #endif // Ensure all job event handlers are removed. PSJobStartEventArgs[] runningJobs; lock (_syncObject) { runningJobs = _runningJobs.Values.ToArray(); } foreach (var item in runningJobs) { Job job = item.Job; if (job != null) { job.StateChanged -= <API key>; job.<API key> -= <API key>; } } <API key>.Dispose(); <API key> = null; if (<API key> != null) { <API key>.Dispose(); <API key> = null; } } #endregion #region Tracing internal void EnableTracing(int traceLevel, bool? step) { // Enable might actually be disabling depending on the arguments. if (traceLevel < 1 && (step == null || !(bool)step)) { DisableTracing(); return; } <API key> = _context.IgnoreScriptDebug; _context.IgnoreScriptDebug = false; _context.PSDebugTraceLevel = traceLevel; if (step != null) { _context.PSDebugTraceStep = (bool)step; } <API key>(InternalDebugMode.Enabled); } internal void DisableTracing() { _context.IgnoreScriptDebug = <API key>; _context.PSDebugTraceLevel = 0; _context.PSDebugTraceStep = false; if (!_idToBreakpoint.Any()) { // Only disable debug mode if there are no breakpoints. <API key>(InternalDebugMode.Disabled); } } private bool <API key> = false; internal void Trace(string messageId, string resourceString, params object[] args) { ActionPreference pref = ActionPreference.Continue; string message; if (null == args || 0 == args.Length) { // Don't format in case the string contains literal curly braces message = resourceString; } else { message = StringUtil.Format(resourceString, args); } if (String.IsNullOrEmpty(message)) { message = "Could not load text for msh script tracing message id '" + messageId + "'"; Diagnostics.Assert(false, message); } ((<API key>)_context.EngineHostInterface.UI).WriteDebugLine(message, ref pref); } internal void TraceLine(IScriptExtent extent) { string msg = PositionUtilities.BriefMessage(extent.StartScriptPosition); <API key> ui = (<API key>)_context.EngineHostInterface.UI; ActionPreference pref = _context.PSDebugTraceStep ? ActionPreference.Inquire : ActionPreference.Continue; ui.WriteDebugLine(msg, ref pref); if (pref == ActionPreference.Continue) _context.PSDebugTraceStep = false; } internal void <API key>(FunctionContext functionContext) { var methodName = functionContext._functionName; if (String.IsNullOrEmpty(functionContext._file)) { Trace("<API key>", ParserStrings.<API key>, methodName); } else { Trace("<API key>", ParserStrings.<API key>, methodName, functionContext._file); } } internal void TraceVariableSet(string varName, object value) { // Don't trace into debugger hidden or debugger step through unless the trace level > 2. if (_callStack.Any() && _context.PSDebugTraceLevel <= 2) { // Skip trace messages in hidden/step through frames. var frame = _callStack.Last(); if (frame.IsFrameHidden || frame.DebuggerStepThrough) { return; } } // If the value is an IEnumerator, we don't attempt to get its string format via 'ToStringParser' method, // because 'ToStringParser' would iterate through the enumerator to get the individual elements, which will // make irreversible changes to the enumerator. bool <API key> = PSObject.Base(value) is IEnumerator; string valAsString = <API key> ? typeof(IEnumerator).Name : PSObject.ToStringParser(_context, value); int msgLength = 60 - varName.Length; if (valAsString.Length > msgLength) { valAsString = valAsString.Substring(0, msgLength) + "..."; } Trace("<API key>", ParserStrings.<API key>, varName, valAsString); } #endregion Tracing } #endregion #region <API key> <summary> Base class for nested runspace debugger wrapper. </summary> internal abstract class <API key> : Debugger, IDisposable { #region Members protected Runspace _runspace; protected Debugger _wrappedDebugger; #endregion #region Properties <summary> Type of runspace being monitored for debugging. </summary> public <API key> RunspaceType { get; private set; } <summary> Unique parent debugger identifier for monitored runspace. </summary> public Guid ParentDebuggerId { get; private set; } #endregion #region Constructors <summary> Creates an instance of <API key>. </summary> <param name="runspace">Runspace</param> <param name="runspaceType">Runspace type</param> <param name="parentDebuggerId">Debugger Id of parent</param> public <API key>( Runspace runspace, <API key> runspaceType, Guid parentDebuggerId) { if (runspace == null || runspace.Debugger == null) { throw new <API key>("runspace"); } _runspace = runspace; _wrappedDebugger = runspace.Debugger; base.SetDebugMode(_wrappedDebugger.DebugMode); RunspaceType = runspaceType; ParentDebuggerId = parentDebuggerId; // Handlers for wrapped debugger events. _wrappedDebugger.BreakpointUpdated += <API key>; _wrappedDebugger.DebuggerStop += HandleDebuggerStop; } #endregion #region Overrides <summary> Process debugger or PowerShell command/script. </summary> <param name="command">PowerShell command</param> <param name="output">Output collection</param> <returns><API key></returns> public override <API key> ProcessCommand(PSCommand command, PSDataCollection<PSObject> output) { // Preprocess debugger commands. String cmd = command.Commands[0].CommandText.Trim(); if (cmd.Equals("prompt", StringComparison.OrdinalIgnoreCase)) { return HandlePromptCommand(output); } if (cmd.Equals("k", StringComparison.OrdinalIgnoreCase) || cmd.StartsWith("Get-PSCallStack", StringComparison.OrdinalIgnoreCase)) { return HandleCallStack(output); } if (cmd.Equals("l", StringComparison.OrdinalIgnoreCase) || cmd.Equals("list", StringComparison.OrdinalIgnoreCase)) { if (HandleListCommand(output)) { return new <API key>(null, true); } } return _wrappedDebugger.ProcessCommand(command, output); } <summary> SetDebuggerAction </summary> <param name="resumeAction">Debugger resume action</param> public override void SetDebuggerAction(<API key> resumeAction) { _wrappedDebugger.SetDebuggerAction(resumeAction); } <summary> Stops running command. </summary> public override void StopProcessCommand() { _wrappedDebugger.StopProcessCommand(); } <summary> Returns current debugger stop event arguments if debugger is in debug stop state. Otherwise returns null. </summary> <returns><API key></returns> public override <API key> GetDebuggerStopArgs() { return _wrappedDebugger.GetDebuggerStopArgs(); } <summary> Sets the debugger mode. </summary> <param name="mode">Debug mode</param> public override void SetDebugMode(DebugModes mode) { _wrappedDebugger.SetDebugMode(mode); } <summary> Sets debugger stepping mode. </summary> <param name="enabled">True if stepping is to be enabled</param> public override void SetDebuggerStepMode(bool enabled) { _wrappedDebugger.SetDebuggerStepMode(enabled); } <summary> Returns true if debugger is active. </summary> public override bool IsActive { get { return _wrappedDebugger.IsActive; } } #endregion #region IDisposable <summary> Dispose </summary> public virtual void Dispose() { if (_wrappedDebugger != null) { _wrappedDebugger.BreakpointUpdated -= <API key>; _wrappedDebugger.DebuggerStop -= HandleDebuggerStop; } _wrappedDebugger = null; _runspace = null; // Call GC.SuppressFinalize since this is an unsealed type, in case derived types // have finalizers. GC.SuppressFinalize(this); } #endregion #region Protected Methods protected virtual void HandleDebuggerStop(object sender, <API key> e) { this.<API key>(e); } protected virtual void <API key>(object sender, <API key> e) { this.<API key>(e); } protected virtual <API key> HandlePromptCommand(PSDataCollection<PSObject> output) { // Nested debugged runspace prompt should look like: // [ComputerName]: [DBG]: [Process:<id>]: [RunspaceName]: PS C:\> string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null; string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPart = StringUtil.Format(processPartPattern, @"""", DebuggerStrings.<API key>, @"$($PID)", @""""); string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; string promptScript = "'[DBG]: '" + " + " + processPart + " + " + "' [" + CodeGeneration.<API key>(_runspace.Name) + "]: '" + " + " + locationPart; // Get the command prompt from the wrapped debugger. PSCommand promptCommand = new PSCommand(); promptCommand.AddScript(promptScript); PSDataCollection<PSObject> promptOutput = new PSDataCollection<PSObject>(); _wrappedDebugger.ProcessCommand(promptCommand, promptOutput); string promptString = (promptOutput.Count == 1) ? promptOutput[0].BaseObject as string : string.Empty; var nestedPromptString = new System.Text.StringBuilder(); // For remote runspaces display computer name in prompt. if (!string.IsNullOrEmpty(computerName)) { nestedPromptString.Append("[" + computerName + "]:"); } nestedPromptString.Append(promptString); // Fix up for non-remote runspaces since the runspace is not in a nested prompt // but the root runspace is. if (string.IsNullOrEmpty(computerName)) { nestedPromptString.Insert(nestedPromptString.Length - 1, ">"); } output.Add(nestedPromptString.ToString()); return new <API key>(null, true); } protected virtual <API key> HandleCallStack(PSDataCollection<PSObject> output) { throw new <API key>(); } protected virtual bool HandleListCommand(PSDataCollection<PSObject> output) { return false; } #endregion #region Internal Methods <summary> Attempts to fix up the debugger stop invocation information so that the correct stack and source can be displayed in the debugger, for cases where the debugged runspace is called inside a parent sccript, such as with Workflow InlineScripts and script Invoke-Command cases. </summary> <param name="<API key>"></param> <returns>InvocationInfo</returns> internal virtual InvocationInfo FixupInvocationInfo(InvocationInfo <API key>) { // Default is no fix up. return <API key>; } internal bool IsSameDebugger(Debugger testDebugger) { return _wrappedDebugger.Equals(testDebugger); } <summary> Checks to see if the runspace debugger is in a preserved debug stop state, and if so then allows the debugger stop event to continue processing and raise the event. </summary> internal void <API key>() { RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger; if (remoteDebugger != null) { // Have remote debugger raise existing debugger stop event. remoteDebugger.<API key>(); } else if (this._wrappedDebugger.<API key>) { // Release local debugger preserved debugger stop event. this._wrappedDebugger.<API key>(); } else { // If this is a remote server debugger then we want to convert the pending remote // debugger stop to a local debugger stop event for this Debug-Runspace to handle. <API key> <API key> = this._wrappedDebugger as <API key>; if (<API key> != null) { <API key>.<API key>(); } } } #endregion } <summary> Wrapper class for runspace debugger where it is running in no known embedding scenario and is assumed to be running independently of any other running script. </summary> internal sealed class <API key> : <API key> { #region Constructor <summary> Constructor </summary> <param name="runspace">Runspace</param> public <API key>( Runspace runspace) : base(runspace, <API key>.Standalone, Guid.Empty) { } #endregion #region Overrides protected override <API key> HandleCallStack(PSDataCollection<PSObject> output) { // Get call stack from wrapped debugger PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-PSCallStack"); PSDataCollection<PSObject> callStackOutput = new PSDataCollection<PSObject>(); _wrappedDebugger.ProcessCommand(cmd, callStackOutput); // Display call stack info as formatted. using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("Out-String").AddParameter("Stream", true); ps.Invoke(callStackOutput, output); } return new <API key>(null, true); } protected override void HandleDebuggerStop(object sender, <API key> e) { PowerShell runningCmd = null; try { runningCmd = <API key>(); this.<API key>(e); } finally { RestoreRemoteOutput(runningCmd); } } #endregion #region Private Methods private PowerShell <API key>() { // We only do this for remote runspaces. RemoteRunspace remoteRunspace = _runspace as RemoteRunspace; if (remoteRunspace == null) { return null; } PowerShell runningCmd = remoteRunspace.<API key>(); if (runningCmd != null) { runningCmd.<API key>(); runningCmd.SuspendIncomingData(); return runningCmd; } return null; } private void RestoreRemoteOutput(PowerShell runningCmd) { if (runningCmd != null) { runningCmd.ResumeIncomingData(); } } #endregion } <summary> Wrapper class for runspace debugger where the runspace is being used in an embedded scenario such as Workflow InlineScript or Invoke-Command command inside script. </summary> internal sealed class <API key> : <API key> { #region Members private PowerShell _command; private Debugger _rootDebugger; private ScriptBlockAst <API key>; private <API key> _sendDebuggerArgs; #endregion #region Constructors <summary> Constructor for runspaces executing from script. </summary> <param name="runspace">Runspace to debug</param> <param name="command">PowerShell command</param> <param name="rootDebugger">Root debugger</param> <param name="runspaceType">Runspace to monitor type</param> <param name="parentDebuggerId">Parent debugger Id</param> public <API key>( Runspace runspace, PowerShell command, Debugger rootDebugger, <API key> runspaceType, Guid parentDebuggerId) : base(runspace, runspaceType, parentDebuggerId) { if (rootDebugger == null) { throw new <API key>("rootDebugger"); } _command = command; _rootDebugger = rootDebugger; } #endregion #region Overrides protected override void HandleDebuggerStop(object sender, <API key> e) { _sendDebuggerArgs = new <API key>( e.InvocationInfo, new Collection<Breakpoint>(e.Breakpoints), e.ResumeAction); Object remoteRunningCmd = null; try { // For remote debugging drain/block output channel. remoteRunningCmd = <API key>(); this.<API key>(_sendDebuggerArgs); } finally { RestoreRemoteOutput(remoteRunningCmd); // Return user determined resume action. e.ResumeAction = _sendDebuggerArgs.ResumeAction; } } protected override <API key> HandleCallStack(PSDataCollection<PSObject> output) { // First get call stack from wrapped debugger PSCommand cmd = new PSCommand(); cmd.AddCommand("Get-PSCallStack"); PSDataCollection<PSObject> callStackOutput = new PSDataCollection<PSObject>(); _wrappedDebugger.ProcessCommand(cmd, callStackOutput); // Next get call stack from parent debugger. PSDataCollection<CallStackFrame> callStack = _rootDebugger.GetCallStack().ToArray(); // Combine call stack info. foreach (var item in callStack) { callStackOutput.Add(new PSObject(item)); } // Display call stack info as formatted. using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("Out-String").AddParameter("Stream", true); ps.Invoke(callStackOutput, output); } return new <API key>(null, true); } protected override bool HandleListCommand(PSDataCollection<PSObject> output) { if ((_sendDebuggerArgs != null) && (_sendDebuggerArgs.InvocationInfo != null)) { return _rootDebugger.<API key>(_sendDebuggerArgs.InvocationInfo.ScriptLineNumber, output); } return false; } <summary> Attempts to fix up the debugger stop invocation information so that the correct stack and source can be displayed in the debugger, for cases where the debugged runspace is called inside a parent sccript, such as with Workflow InlineScripts and script Invoke-Command cases. </summary> <param name="<API key>">Invocation information from debugger stop</param> <returns>InvocationInfo</returns> internal override InvocationInfo FixupInvocationInfo(InvocationInfo <API key>) { if (<API key> == null) { return null; } // Check to see if this nested debug stop is called from within // a known parent source. int dbStopLineNumber = <API key>.ScriptLineNumber; CallStackFrame topItem = null; var parentActiveStack = _rootDebugger.<API key>(); if ((parentActiveStack != null) && (parentActiveStack.Length > 0)) { topItem = parentActiveStack[0]; } else { var parentStack = _rootDebugger.GetCallStack().ToArray(); if ((parentStack != null) && (parentStack.Length > 0)) { topItem = parentStack[0]; dbStopLineNumber } } InvocationInfo debugInvocationInfo = <API key>( topItem, dbStopLineNumber, <API key>.ScriptPosition.StartColumnNumber, <API key>.ScriptPosition.EndColumnNumber); return debugInvocationInfo ?? <API key>; } #endregion #region IDisposable <summary> Dispose </summary> public override void Dispose() { base.Dispose(); _rootDebugger = null; <API key> = null; _command = null; _sendDebuggerArgs = null; } #endregion #region Private Methods private InvocationInfo <API key>( CallStackFrame parentStackFrame, int debugLineNumber, int debugStartColNumber, int debugEndColNumber) { if (parentStackFrame == null) { return null; } // Attempt to find parent script file create script block with Ast to // find correct line and offset adjustments. if ((<API key> == null) && !string.IsNullOrEmpty(parentStackFrame.ScriptName) && System.IO.File.Exists(parentStackFrame.ScriptName)) { ParseError[] errors; Token[] tokens; <API key> = Parser.ParseInput( System.IO.File.ReadAllText(parentStackFrame.ScriptName), out tokens, out errors); } if (<API key> != null) { int callingLineNumber = parentStackFrame.ScriptLineNumber; StatementAst debugStatement = null; StatementAst callingStatement = <API key>.Find( ast => { return ((ast is StatementAst) && (ast.Extent.StartLineNumber == callingLineNumber)); } , true) as StatementAst; if (callingStatement != null) { // Find first statement in calling statement. StatementAst firstStatement = callingStatement.Find(ast => { return ((ast is StatementAst) && ast.Extent.StartLineNumber > callingLineNumber); }, true) as StatementAst; if (firstStatement != null) { int adjustedLineNumber = firstStatement.Extent.StartLineNumber + debugLineNumber - 1; debugStatement = callingStatement.Find(ast => { return ((ast is StatementAst) && ast.Extent.StartLineNumber == adjustedLineNumber); }, true) as StatementAst; } } if (debugStatement != null) { int endColNum = debugStartColNumber + (debugEndColNumber - debugStartColNumber) - 2; string statementExtentText = <API key>(debugStatement.Extent.StartColumnNumber - 1, debugStatement.Extent.Text); ScriptPosition scriptStartPosition = new ScriptPosition( parentStackFrame.ScriptName, debugStatement.Extent.StartLineNumber, debugStartColNumber, statementExtentText); ScriptPosition scriptEndPosition = new ScriptPosition( parentStackFrame.ScriptName, debugStatement.Extent.EndLineNumber, endColNum, statementExtentText); return InvocationInfo.Create( parentStackFrame.InvocationInfo.MyCommand, new ScriptExtent( scriptStartPosition, scriptEndPosition) ); } } return null; } private string <API key>(int startColNum, string stateExtentText) { Text.StringBuilder sb = new Text.StringBuilder(); sb.Append(' ', startColNum); sb.Append(stateExtentText); return sb.ToString(); } private Object <API key>() { // We only do this for remote runspaces. if (!(_runspace is RemoteRunspace)) { return null; } try { if (_command != null) { _command.<API key>(); _command.SuspendIncomingData(); return _command; } Pipeline runningCmd = _runspace.<API key>(); if (runningCmd != null) { runningCmd.DrainIncomingData(); runningCmd.SuspendIncomingData(); return runningCmd; } } catch (<API key>) { } return null; } private void RestoreRemoteOutput(Object runningCmd) { if (runningCmd == null) { return; } PowerShell command = runningCmd as PowerShell; if (command != null) { command.ResumeIncomingData(); } else { Pipeline pipelineCommand = runningCmd as Pipeline; if (pipelineCommand != null) { pipelineCommand.ResumeIncomingData(); } } } #endregion } #endregion #region <API key> <summary> Command results returned from Debugger.ProcessCommand. </summary> public sealed class <API key> { #region Properties <summary> Resume action </summary> public <API key>? ResumeAction { get; private set; } <summary> True if debugger evaluated command. Otherwise evaluation was performed by PowerShell. </summary> public bool EvaluatedByDebugger { get; private set; } #endregion #region Constructors private <API key>() { } <summary> Constructor </summary> <param name="resumeAction">Resume action</param> <param name="evaluatedByDebugger">True if evaluated by debugger</param> public <API key>( <API key>? resumeAction, bool evaluatedByDebugger) { ResumeAction = resumeAction; EvaluatedByDebugger = evaluatedByDebugger; } #endregion } #endregion #region <API key> <summary> This class is used to pre-process the command read by the host when it is in debug mode; its main intention is to implement the debugger commands ("s", "c", "o", etc) </summary> internal class <API key> { // debugger commands private const string ContinueCommand = "continue"; private const string ContinueShortcut = "c"; private const string <API key> = "k"; private const string HelpCommand = "h"; private const string HelpShortcut = "?"; private const string ListCommand = "list"; private const string ListShortcut = "l"; private const string StepCommand = "stepInto"; private const string StepShortcut = "s"; private const string StepOutCommand = "stepOut"; private const string StepOutShortcut = "o"; private const string StepOverCommand = "stepOver"; private const string StepOverShortcut = "v"; private const string StopCommand = "quit"; private const string StopShortcut = "q"; private const string DetachCommand = "detach"; private const string DetachShortcut = "d"; // default line count for the list command private const int <API key> = 16; // table of debugger commands private Dictionary<string, DebuggerCommand> _commandTable; // the Help command private DebuggerCommand _helpCommand; // the List command private DebuggerCommand _listCommand; // last command processed private DebuggerCommand _lastCommand; // the source script split into lines private string[] _lines; // last line displayed by the list command private int _lastLineDisplayed; private const string Crlf = "\x000D\x000A"; <summary> Creates the table of debugger commands </summary> public <API key>() { _commandTable = new Dictionary<string, DebuggerCommand>(StringComparer.OrdinalIgnoreCase); _commandTable[StepCommand] = _commandTable[StepShortcut] = new DebuggerCommand(StepCommand, <API key>.StepInto, true, false); _commandTable[StepOutCommand] = _commandTable[StepOutShortcut] = new DebuggerCommand(StepOutCommand, <API key>.StepOut, false, false); _commandTable[StepOverCommand] = _commandTable[StepOverShortcut] = new DebuggerCommand(StepOverCommand, <API key>.StepOver, true, false); _commandTable[ContinueCommand] = _commandTable[ContinueShortcut] = new DebuggerCommand(ContinueCommand, <API key>.Continue, false, false); _commandTable[StopCommand] = _commandTable[StopShortcut] = new DebuggerCommand(StopCommand, <API key>.Stop, false, false); _commandTable[<API key>] = new DebuggerCommand("get-pscallstack", null, false, false); _commandTable[HelpCommand] = _commandTable[HelpShortcut] = _helpCommand = new DebuggerCommand(HelpCommand, null, false, true); _commandTable[ListCommand] = _commandTable[ListShortcut] = _listCommand = new DebuggerCommand(ListCommand, null, true, true); _commandTable[string.Empty] = new DebuggerCommand(string.Empty, null, false, true); } <summary> Resets any state in the command processor </summary> public void Reset() { _lines = null; } <summary> Process the command read by the host and returns the <API key> or the command that the host should execute (see comments in the DebuggerCommand class above). </summary> public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInfo invocationInfo) { return _lastCommand = DoProcessCommand(host, command, invocationInfo, null); } <summary> ProcessCommand </summary> <param name="host"></param> <param name="command"></param> <param name="invocationInfo"></param> <param name="output"></param> <returns></returns> public DebuggerCommand ProcessCommand(PSHost host, string command, InvocationInfo invocationInfo, IList<PSObject> output) { DebuggerCommand dbgCommand = DoProcessCommand(host, command, invocationInfo, output); if (dbgCommand.ExecutedByDebugger || (dbgCommand.ResumeAction != null)) { _lastCommand = dbgCommand; } return dbgCommand; } <summary> Process list command with provided line number. </summary> <param name="invocationInfo">Current InvocationInfo</param> <param name="output">Output</param> public void ProcessListCommand(InvocationInfo invocationInfo, IList<PSObject> output) { DoProcessCommand(null, "list", invocationInfo, output); } <summary> Looks up string command and if it is a debugger command returns the corresponding DebuggerCommand object. </summary> <param name="command">String command</param> <returns>DebuggerCommand or null.</returns> public DebuggerCommand ProcessBasicCommand(string command) { if (command.Length == 0 && _lastCommand != null && _lastCommand.RepeatOnEnter) { return _lastCommand; } DebuggerCommand debuggerCommand; if (_commandTable.TryGetValue(command, out debuggerCommand)) { if (debuggerCommand.ExecutedByDebugger || (debuggerCommand.ResumeAction != null)) { _lastCommand = debuggerCommand; } return debuggerCommand; } return null; } <summary> Helper for ProcessCommand </summary> private DebuggerCommand DoProcessCommand(PSHost host, string command, InvocationInfo invocationInfo, IList<PSObject> output) { // check for <enter> if (command.Length == 0 && _lastCommand != null && _lastCommand.RepeatOnEnter) { if (_lastCommand == _listCommand) { if (_lines != null && _lastLineDisplayed < _lines.Length) { DisplayScript(host, output, invocationInfo, _lastLineDisplayed + 1, <API key>); } return _listCommand; } command = _lastCommand.Command; } // Check for the list command using a regular expression Regex listCommandRegex = new Regex(@"^l(ist)?(\s+(?<start>\S+))?(\s+(?<count>\S+))?$", RegexOptions.IgnoreCase); Match match = listCommandRegex.Match(command); if (match.Success) { DisplayScript(host, output, invocationInfo, match); return _listCommand; } // Check for the rest of the debugger commands DebuggerCommand debuggerCommand = null; if (_commandTable.TryGetValue(command, out debuggerCommand)) { // Check for the help command if (debuggerCommand == _helpCommand) { DisplayHelp(host, output); } return debuggerCommand; } // Else return the same command return new DebuggerCommand(command, null, false, false); } <summary> Displays the help text for the debugger commands </summary> private void DisplayHelp(PSHost host, IList<PSObject> output) { WriteLine("", host, output); WriteLine(StringUtil.Format(DebuggerStrings.StepHelp, StepShortcut, StepCommand), host, output); WriteLine(StringUtil.Format(DebuggerStrings.StepOverHelp, StepOverShortcut, StepOverCommand), host, output); WriteLine(StringUtil.Format(DebuggerStrings.StepOutHelp, StepOutShortcut, StepOutCommand), host, output); WriteLine("", host, output); WriteLine(StringUtil.Format(DebuggerStrings.ContinueHelp, ContinueShortcut, ContinueCommand), host, output); WriteLine(StringUtil.Format(DebuggerStrings.StopHelp, StopShortcut, StopCommand), host, output); WriteLine(StringUtil.Format(DebuggerStrings.DetachHelp, DetachShortcut, DetachCommand), host, output); WriteLine("", host, output); WriteLine(StringUtil.Format(DebuggerStrings.GetStackTraceHelp, <API key>), host, output); WriteLine("", host, output); WriteLine(StringUtil.Format(DebuggerStrings.ListHelp, ListShortcut, ListCommand), host, output); WriteLine(StringUtil.Format(DebuggerStrings.AdditionalListHelp1), host, output); WriteLine(StringUtil.Format(DebuggerStrings.AdditionalListHelp2), host, output); WriteLine(StringUtil.Format(DebuggerStrings.AdditionalListHelp3), host, output); WriteLine("", host, output); WriteLine(StringUtil.Format(DebuggerStrings.EnterHelp, StepCommand, StepOverCommand, ListCommand), host, output); WriteLine("", host, output); WriteLine(StringUtil.Format(DebuggerStrings.HelpCommandHelp, HelpShortcut, HelpCommand), host, output); WriteLine("\n", host, output); WriteLine(StringUtil.Format(DebuggerStrings.PromptHelp), host, output); WriteLine("", host, output); } <summary> Executes the list command </summary> private void DisplayScript(PSHost host, IList<PSObject> output, InvocationInfo invocationInfo, Match match) { if (invocationInfo == null) { return; } // Get the source code for the script if (_lines == null) { string scriptText = invocationInfo.GetFullScript(); if (string.IsNullOrEmpty(scriptText)) { WriteErrorLine(StringUtil.Format(DebuggerStrings.NoSourceCode), host, output); return; } _lines = scriptText.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); } // Get the starting line int start = Math.Max(invocationInfo.ScriptLineNumber - 5, 1); if (match.Groups["start"].Value.Length > 0) { try { start = int.Parse(match.Groups["start"].Value, CultureInfo.CurrentCulture.NumberFormat); } catch { WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, _lines.Length), host, output); return; } if (start <= 0 || start > _lines.Length) { WriteErrorLine(StringUtil.Format(DebuggerStrings.BadStartFormat, _lines.Length), host, output); return; } } // Get the line count int count = <API key>; if (match.Groups["count"].Value.Length > 0) { try { count = int.Parse(match.Groups["count"].Value, CultureInfo.CurrentCulture.NumberFormat); } catch { WriteErrorLine(StringUtil.Format(DebuggerStrings.BadCountFormat, _lines.Length), host, output); return; } // Limit requested line count to maximum number of existing lines count = (count > _lines.Length) ? _lines.Length : count; if (count <= 0) { WriteErrorLine(DebuggerStrings.BadCountFormat, host, output); return; } } // Execute the command DisplayScript(host, output, invocationInfo, start, count); } <summary> Executes the list command </summary> private void DisplayScript(PSHost host, IList<PSObject> output, InvocationInfo invocationInfo, int start, int count) { WriteCR(host, output); for (int lineNumber = start; lineNumber <= _lines.Length && lineNumber < start + count; lineNumber++) { WriteLine( lineNumber == invocationInfo.ScriptLineNumber ? string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, _lines[lineNumber - 1]) : string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, _lines[lineNumber - 1]), host, output); _lastLineDisplayed = lineNumber; } WriteCR(host, output); } private void WriteLine(string line, PSHost host, IList<PSObject> output) { if (host != null) { host.UI.WriteLine(line); } if (output != null) { output.Add(new PSObject(line)); } } private void WriteCR(PSHost host, IList<PSObject> output) { if (host != null) { host.UI.WriteLine(); } if (output != null) { output.Add(new PSObject(Crlf)); } } private void WriteErrorLine(string error, PSHost host, IList<PSObject> output) { if (host != null) { host.UI.WriteErrorLine(error); } if (output != null) { output.Add( new PSObject( new ErrorRecord( new RuntimeException(error), "DebuggerError", ErrorCategory.InvalidOperation, null))); } } } <summary> Class used to hold the output of the <API key> </summary> internal class DebuggerCommand { public DebuggerCommand(string command, <API key>? action, bool repeatOnEnter, bool executedByDebugger) { ResumeAction = action; Command = command; RepeatOnEnter = repeatOnEnter; ExecutedByDebugger = executedByDebugger; } <summary> If ResumeAction is not null it indicates that the host must exit the debugger and resume execution of the suspended pipeline; the debugger will use the value of this property to decide how to resume the pipeline (i.e. step into, step-over, continue, etc) </summary> public <API key>? ResumeAction { get; } <summary> When ResumeAction is null, this property indicates the command that the host should pass to the PowerShell engine </summary> public string Command { get; } <summary> If true, the host should repeat this command if the next command in an empty line (enter) </summary> public bool RepeatOnEnter { get; } <summary> If true, the command was executed by the debugger and the host should ignore the command </summary> public bool ExecutedByDebugger { get; } } #endregion #region PSDebugContext class <summary> This class exposes the information about the debugger that is available via $PSDebugContext </summary> public class PSDebugContext { <summary> Constructor. </summary> <param name="invocationInfo">InvocationInfo</param> <param name="breakpoints">Breakpoints</param> public PSDebugContext(InvocationInfo invocationInfo, List<Breakpoint> breakpoints) { if (breakpoints == null) { throw new <API key>("breakpoints"); } this.InvocationInfo = invocationInfo; this.Breakpoints = breakpoints.ToArray(); } <summary> InvocationInfo of the command currently being executed </summary> public InvocationInfo InvocationInfo { get; private set; } <summary> If not empty, indicates that the execution was suspended because one or more breakpoints were hit. Otherwise, the execution was suspended as part of a step operation. </summary> public Breakpoint[] Breakpoints { get; private set; } } #endregion #region CallStackFrame class <summary> A call stack item returned by the Get-PSCallStack cmdlet. </summary> public sealed class CallStackFrame { <summary> Constructor </summary> <param name="invocationInfo">Invocation Info</param> public CallStackFrame(InvocationInfo invocationInfo) : this(null, invocationInfo) { } <summary> Constructor </summary> <param name="functionContext">Function context</param> <param name="invocationInfo">Invocation Info</param> internal CallStackFrame(FunctionContext functionContext, InvocationInfo invocationInfo) { if (invocationInfo == null) { throw new <API key>("invocationInfo"); } if (functionContext != null) { this.InvocationInfo = invocationInfo; FunctionContext = functionContext; this.Position = functionContext.CurrentPosition; } else { // WF functions do not have functionContext. Use InvocationInfo. this.InvocationInfo = invocationInfo; this.Position = invocationInfo.ScriptPosition; FunctionContext = new FunctionContext(); FunctionContext._functionName = invocationInfo.ScriptName; } } <summary> File name of the current location, or null if the frame is not associated to a script </summary> public string ScriptName { get { return Position.File; } } <summary> Line number of the current location, or 0 if the frame is not associated to a script </summary> public int ScriptLineNumber { get { return Position.StartLineNumber; } } <summary> The InvocationInfo of the command </summary> public InvocationInfo InvocationInfo { get; private set; } <summary> The position information for the current position in the frame. Null if the frame is not associated with a script. </summary> public IScriptExtent Position { get; private set; } <summary> The name of the function associated with this frame. </summary> public string FunctionName { get { return FunctionContext._functionName; } } internal FunctionContext FunctionContext { get; } <summary> Returns a formatted string containing the ScriptName and ScriptLineNumber </summary> public string GetScriptLocation() { if (string.IsNullOrEmpty(this.ScriptName)) { return DebuggerStrings.NoFile; } return StringUtil.Format(DebuggerStrings.LocationFormat, Path.GetFileName(this.ScriptName), this.ScriptLineNumber); } <summary> Return a dictionary with the names and values of variables that are "local" to the frame. </summary> <returns></returns> public Dictionary<string, PSVariable> GetFrameVariables() { var result = new Dictionary<string, PSVariable>(StringComparer.OrdinalIgnoreCase); if (FunctionContext._executionContext == null) { return result; } var scope = FunctionContext._executionContext.EngineSessionState.CurrentScope; while (scope != null) { if (scope.LocalsTuple == FunctionContext._localsTuple) { // We can ignore any dotted scopes. break; } if (scope.DottedScopes != null && scope.DottedScopes.Where(s => s == FunctionContext._localsTuple).Any()) { var dottedScopes = scope.DottedScopes.ToArray(); int i; // Skip dotted scopes above the current scope for (i = 0; i < dottedScopes.Length; ++i) { if (dottedScopes[i] == FunctionContext._localsTuple) break; } for (; i < dottedScopes.Length; ++i) { dottedScopes[i].GetVariableTable(result, true); } break; } scope = scope.Parent; } FunctionContext._localsTuple.GetVariableTable(result, true); return result; } <summary> ToString override. </summary> public override string ToString() { return StringUtil.Format(DebuggerStrings.StackTraceFormat, FunctionName, ScriptName ?? DebuggerStrings.NoFile, ScriptLineNumber); } } #endregion } namespace System.Management.Automation.Internal { #region DebuggerUtils <summary> Debugger Utilities class </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:<API key>", Justification = "Needed Internal use only")] public static class DebuggerUtils { <summary> <API key> function. </summary> public const string SetVariableFunction = @"function <API key> { [CmdletBinding()] param( [Parameter(Position=0)] [HashTable] $Variables ) foreach($key in $Variables.Keys) { microsoft.powershell.utility\set-variable -Name $key -Value $Variables[$key] -Scope global } Set-StrictMode -Off }"; <summary> <API key> function. </summary> public const string <API key> = @"function <API key> { [CmdletBinding()] param( [Parameter(Position=0)] [string[]] $Name ) foreach ($item in $Name) { microsoft.powershell.utility\remove-variable -name $item -scope global } Set-StrictMode -Off }"; <summary> Get-PSCallStack override function. </summary> public const string <API key> = @"function Get-PSCallStack { [CmdletBinding()] param() if ($PSWorkflowDebugger -ne $null) { foreach ($frame in $PSWorkflowDebugger.GetCallStack()) { Write-Output $frame } } Set-StrictMode -Off }"; internal const string <API key> = "__Set-PSDebugMode"; internal const string <API key> = "<API key>"; internal const string <API key> = "<API key>"; internal const string SetDebuggerStepMode = "<API key>"; internal const string <API key> = "<API key>"; private static SortedSet<string> <API key> = new SortedSet<string>(StringComparer.OrdinalIgnoreCase) { "prompt", "<API key>", "<API key>", "Set-PSDebugMode", "TabExpansion2" }; <summary> Helper method to determine if command should be added to debugger history. </summary> <param name="command">Command string</param> <returns>True if command can be added to history</returns> public static bool <API key>(string command) { if (command == null) { throw new <API key>("command"); } lock (<API key>) { return !(<API key>.Contains(command, StringComparer.OrdinalIgnoreCase)); } } <summary> Helper method to return an enumeration of workflow debugger functions. </summary> <returns></returns> public static IEnumerable<string> <API key>() { return new Collection<string>() { SetVariableFunction, <API key>, <API key> }; } <summary> Start monitoring a runspace on the target debugger. </summary> <param name="debugger">Target debugger</param> <param name="runspaceInfo"><API key></param> public static void <API key>(Debugger debugger, <API key> runspaceInfo) { if (debugger == null) { throw new <API key>("debugger"); } if (runspaceInfo == null) { throw new <API key>("runspaceInfo"); } debugger.<API key>(runspaceInfo); } <summary> End monitoring a runspace on the target degbugger. </summary> <param name="debugger">Target debugger</param> <param name="runspaceInfo"><API key></param> public static void <API key>(Debugger debugger, <API key> runspaceInfo) { if (debugger == null) { throw new <API key>("debugger"); } if (runspaceInfo == null) { throw new <API key>("runspaceInfo"); } debugger.<API key>(runspaceInfo); } } #region <API key> <summary> <API key> </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:<API key>", Justification = "Needed Internal use only")] public enum <API key> { <summary> Standalone runspace. </summary> Standalone = 0, <summary> Runspace from remote Invoke-Command script. </summary> InvokeCommand, <summary> Runspace from Workflow activity inline script. </summary> <API key> } <summary> Runspace information for monitoring runspaces for debugging. </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:<API key>", Justification = "Needed Internal use only")] public abstract class <API key> { #region Properties <summary> Created Runspace </summary> public Runspace Runspace { get; private set; } <summary> Type of runspace for monitoring. </summary> public <API key> RunspaceType { get; private set; } <summary> Nested debugger wrapper for runspace debugger. </summary> internal <API key> NestedDebugger { get; set; } #endregion #region Constructors private <API key>() { } <summary> Constructor </summary> <param name="runspace">Runspace</param> <param name="runspaceType">Runspace type</param> protected <API key>( Runspace runspace, <API key> runspaceType) { if (runspace == null) { throw new <API key>("runspace"); } Runspace = runspace; RunspaceType = runspaceType; } #endregion #region Methods <summary> Returns a copy of this object. </summary> <returns></returns> internal abstract <API key> Copy(); <summary> Creates an instance of a <API key>. </summary> <param name="rootDebugger">Root debugger or null.</param> <returns><API key></returns> internal abstract <API key> CreateDebugger(Debugger rootDebugger); #endregion } <summary> Standalone runspace information for monitoring runspaces for debugging. </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:<API key>", Justification = "Needed Internal use only")] public sealed class <API key> : <API key> { #region Constructor <summary> Creates instance of <API key> </summary> <param name="runspace">Runspace to monitor</param> public <API key>( Runspace runspace) : base(runspace, <API key>.Standalone) { } #endregion #region Overrides <summary> Returns a copy of this object. </summary> <returns></returns> internal override <API key> Copy() { return new <API key>(Runspace); } <summary> Creates an instance of a <API key>. </summary> <param name="rootDebugger">Root debugger or null</param> <returns><API key> wrapper</returns> internal override <API key> CreateDebugger(Debugger rootDebugger) { return new <API key>(Runspace); } #endregion } <summary> Embedded runspaces running in context of a parent script, used for monitoring runspace debugging. </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:<API key>", Justification = "Needed Internal use only")] public sealed class <API key> : <API key> { #region Properties <summary> PowerShell command to run. Can be null. </summary> public PowerShell Command { get; private set; } <summary> Unique parent debugger identifier </summary> public Guid ParentDebuggerId { get; private set; } #endregion #region Constructor <summary> Creates instance of <API key> </summary> <param name="runspace">Runspace to monitor</param> <param name="runspaceType">Type of runspace</param> <param name="command">Running command</param> <param name="parentDebuggerId">Unique parent debugger id or null</param> public <API key>( Runspace runspace, <API key> runspaceType, PowerShell command, Guid parentDebuggerId) : base(runspace, runspaceType) { Command = command; ParentDebuggerId = parentDebuggerId; } #endregion #region Overrides <summary> Returns a copy of this object. </summary> <returns></returns> internal override <API key> Copy() { return new <API key>( Runspace, RunspaceType, Command, ParentDebuggerId); } <summary> Creates an instance of a <API key>. </summary> <param name="rootDebugger">Root debugger or null</param> <returns><API key> wrapper</returns> internal override <API key> CreateDebugger(Debugger rootDebugger) { return new <API key>( Runspace, Command, rootDebugger, RunspaceType, ParentDebuggerId); } #endregion } #endregion #endregion }
// NDKCallbackNode.cpp // <API key> #include "NDKCallbackNode.h" NDKCallbackNode::NDKCallbackNode(const char *groupName, const char *name, SEL_CallFuncND sel, CCNode *target) { this->groupName = groupName; this->name = name; this->sel = sel; this->target = target; } string NDKCallbackNode::getName() { return this->name; } string NDKCallbackNode::getGroup() { return this->groupName; } SEL_CallFuncND NDKCallbackNode::getSelector() { return this->sel; } CCNode* NDKCallbackNode::getTarget() { return this->target; }
+++ title = "`<API key>(expr)`" description = "Evaluate from within a coroutine an expression which results in an understood type, emitting the `T` if successful, immediately returning `<API key>(X)` from the calling function if unsuccessful." +++ Evaluate within a coroutine an expression which results in a type matching the following customisation points, emitting the `T` if successful, immediately returning {{% api "<API key>(X)" %}} from the calling function if unsuccessful: - `<API key>::`{{% api "<API key>(X)" %}} - `<API key>::`{{% api "<API key>(X)" %}} - `<API key>::`{{% api "<API key>(X)" %}} Default overloads for these customisation points are provided. See [the recipe for supporting foreign input to `BOOST_OUTCOME_TRY`]({{% relref "/recipes/foreign-try" %}}). Hints are given to the compiler that the expression will be successful. If you expect failure, you should use {{% api "<API key>(expr)" %}} instead. An internal temporary to hold the value of the expression is created, which generally invokes a copy/move. [If you wish to never copy/move, you can tell this macro to create the internal temporary as a reference instead.]({{% relref "/tutorial/essential/result/try_ref" %}}) *Availability*: GCC and clang only. Use `#ifdef <API key>` to determine if available. *Overridable*: Not overridable. *Definition*: See {{% api "<API key>(expr)" %}} for most of the mechanics. This macro makes use of a proprietary extension in GCC and clang to emit the `T` from a successful expression. You can thus use `<API key>(expr)` directly in expressions e.g. `auto x = y + <API key>(foo(z));`. Be aware there are compiler quirks in preserving the rvalue/lvalue/etc-ness of emitted `T`'s, specifically copy or move constructors may be called unexpectedly and/or copy elision not work as expected. If these prove to be problematic, use {{% api "<API key>(var, expr)" %}} instead. *Header*: `<boost/outcome/try.hpp>`
name 'git' maintainer 'Chef Software, Inc.' maintainer_email 'cookbooks@chef.io' license 'Apache 2.0' description 'Installs git and/or sets up a Git server daemon' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '4.1.0' recipe 'git', 'Installs git' recipe 'git::server', 'Sets up a runit_service for git daemon' recipe 'git::source', 'Installs git from source' supports 'amazon' supports 'arch' supports 'centos' supports 'debian' supports 'fedora' supports 'freebsd' supports 'mac_os_x', '>= 10.6.0' supports 'omnios' supports 'oracle' supports 'redhat' supports 'smartos' supports 'scientific' supports 'ubuntu' supports 'windows' depends 'build-essential' depends 'dmg' depends 'runit', '>= 1.0' depends 'windows' depends 'yum', '~> 3.0' depends 'yum-epel' attribute 'git/server/base_path', :display_name => 'Git Daemon Base Path', :description => 'A directory containing git repositories to be ' \ 'exposed by the git-daemon', :default => '/srv/git', :recipes => ['git::server'] attribute 'git/server/export_all', :display_name => 'Git Daemon Export All', :description => 'Adds the --export-all option to the git-daemon ' \ 'parameters, making all repositories publicly readable even if ' \ 'they lack the \'<API key>\' file', :choice => %w{ true false }, :default => 'true', :recipes => ['git::server']
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using UnityEngine; namespace InControl { public class PlayerOneAxisAction : OneAxisInputControl { PlayerAction negativeAction; PlayerAction positiveAction; internal PlayerOneAxisAction( PlayerAction negativeAction, PlayerAction positiveAction ) { this.negativeAction = negativeAction; this.positiveAction = positiveAction; Raw = true; } internal void Update( ulong updateTick, float deltaTime ) { var value = Utility.ValueFromSides( negativeAction, positiveAction ); CommitWithValue( value, updateTick, deltaTime ); } } }
package com.zhan_dui.modal; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; @Table(name = "Categories") public class Category extends Model implements Parcelable { @Column(name="cid") public int cid; @Column(name="name") public String Name; @Column(name="count") public int Count; public Category(){} public Category(int cid,String name,int count){ this.cid = cid; this.Name = name; this.Count = count; } public static Category build(JSONObject object){ try { return new Category(object.getInt("id"),object.getString("name"),object.getInt("count")); } catch (JSONException e) { return null; } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(cid); parcel.writeString(Name); parcel.writeInt(Count); } public Category(Parcel in){ cid = in.readInt(); Name = in.readString(); Count = in.readInt(); } public static final Creator<Category> CREATOR = new Creator<Category>() { @Override public Category createFromParcel(Parcel parcel) { return new Category(parcel); } @Override public Category[] newArray(int size) { return new Category[size]; } }; }
using System; using System.Collections.Generic; using System.IO; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Persistence.Querying; namespace Umbraco.Cms.Core.Services { <summary> Defines the Media Service, which is an easy access to operations involving <see cref="IMedia"/> </summary> public interface IMediaService : IContentServiceBase<IMedia> { int CountNotTrashed(string contentTypeAlias = null); int Count(string mediaTypeAlias = null); int CountChildren(int parentId, string mediaTypeAlias = null); int CountDescendants(int parentId, string mediaTypeAlias = null); IEnumerable<IMedia> GetByIds(IEnumerable<int> ids); IEnumerable<IMedia> GetByIds(IEnumerable<Guid> ids); <summary> Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> that this Media should based on. </summary> <remarks> Note that using this method will simply return a new IMedia without any identity as it has not yet been persisted. It is intended as a shortcut to creating new media objects that does not invoke a save operation against the database. </remarks> <param name="name">Name of the Media object</param> <param name="parentId">Id of Parent for the new Media item</param> <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> <param name="userId">Optional id of the user creating the media item</param> <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, Guid parentId, string mediaTypeAlias, int userId = Constants.Security.SuperUserId); <summary> Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> that this Media should based on. </summary> <remarks> Note that using this method will simply return a new IMedia without any identity as it has not yet been persisted. It is intended as a shortcut to creating new media objects that does not invoke a save operation against the database. </remarks> <param name="name">Name of the Media object</param> <param name="parentId">Id of Parent for the new Media item</param> <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> <param name="userId">Optional id of the user creating the media item</param> <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = Constants.Security.SuperUserId); <summary> Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> that this Media should based on. </summary> <remarks> Note that using this method will simply return a new IMedia without any identity as it has not yet been persisted. It is intended as a shortcut to creating new media objects that does not invoke a save operation against the database. </remarks> <param name="name">Name of the Media object</param> <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> <param name="userId">Optional id of the user creating the media item</param> <returns><see cref="IMedia"/></returns> IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = Constants.Security.SuperUserId); <summary> Gets an <see cref="IMedia"/> object by Id </summary> <param name="id">Id of the Content to retrieve</param> <returns><see cref="IMedia"/></returns> IMedia GetById(int id); <summary> Gets a collection of <see cref="IMedia"/> objects by Parent Id </summary> <param name="id">Id of the Parent to retrieve Children from</param> <param name="pageIndex">Page number</param> <param name="pageSize">Page size</param> <param name="totalRecords">Total records query would return without paging</param> <param name="orderBy">Field to order by</param> <param name="orderDirection">Direction to order by</param> <param name="orderBySystemField">Flag to indicate when ordering by system field</param> <param name="filter"></param> <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords, IQuery<IMedia> filter = null, Ordering ordering = null); <summary> Gets a collection of <see cref="IMedia"/> objects by Parent Id </summary> <param name="id">Id of the Parent to retrieve Descendants from</param> <param name="pageIndex">Page number</param> <param name="pageSize">Page size</param> <param name="totalRecords">Total records query would return without paging</param> <param name="ordering"></param> <param name="filter"></param> <returns>An Enumerable list of <see cref="IContent"/> objects</returns> IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords, IQuery<IMedia> filter = null, Ordering ordering = null); <summary> Gets paged documents of a content </summary> <param name="contentTypeId">The page number.</param> <param name="pageIndex">The page number.</param> <param name="pageSize">The page size.</param> <param name="totalRecords">Total number of documents.</param> <param name="filter">Search text filter.</param> <param name="ordering">Ordering infos.</param> IEnumerable<IMedia> GetPagedOfType(int contentTypeId, long pageIndex, int pageSize, out long totalRecords, IQuery<IMedia> filter = null, Ordering ordering = null); <summary> Gets paged documents for specified content types </summary> <param name="contentTypeIds">The page number.</param> <param name="pageIndex">The page number.</param> <param name="pageSize">The page size.</param> <param name="totalRecords">Total number of documents.</param> <param name="filter">Search text filter.</param> <param name="ordering">Ordering infos.</param> IEnumerable<IMedia> GetPagedOfTypes(int[] contentTypeIds, long pageIndex, int pageSize, out long totalRecords, IQuery<IMedia> filter = null, Ordering ordering = null); <summary> Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root </summary> <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetRootMedia(); <summary> Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin </summary> <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> <API key>(long pageIndex, int pageSize, out long totalRecords, IQuery<IMedia> filter = null, Ordering ordering = null); <summary> Moves an <see cref="IMedia"/> object to a new location </summary> <param name="media">The <see cref="IMedia"/> to move</param> <param name="parentId">Id of the Media's new Parent</param> <param name="userId">Id of the User moving the Media</param> <returns>True if moving succeeded, otherwise False</returns> Attempt<OperationResult> Move(IMedia media, int parentId, int userId = Constants.Security.SuperUserId); <summary> Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin </summary> <param name="media">The <see cref="IMedia"/> to delete</param> <param name="userId">Id of the User deleting the Media</param> Attempt<OperationResult> MoveToRecycleBin(IMedia media, int userId = Constants.Security.SuperUserId); <summary> Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin </summary> <param name="userId">Optional Id of the User emptying the Recycle Bin</param> OperationResult EmptyRecycleBin(int userId = Constants.Security.SuperUserId); <summary> Returns true if there is any media in the recycle bin </summary> bool RecycleBinSmells(); <summary> Deletes all media of specified type. All children of deleted media is moved to Recycle Bin. </summary> <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param> <param name="userId">Optional Id of the user deleting Media</param> void DeleteMediaOfType(int mediaTypeId, int userId = Constants.Security.SuperUserId); <summary> Deletes all media of the specified types. All Descendants of deleted media that is not of these types is moved to Recycle Bin. </summary> <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks> <param name="mediaTypeIds">Ids of the <see cref="IMediaType"/>s</param> <param name="userId">Optional Id of the user issuing the delete operation</param> void DeleteMediaOfTypes(IEnumerable<int> mediaTypeIds, int userId = Constants.Security.SuperUserId); <summary> Permanently deletes an <see cref="IMedia"/> object </summary> <remarks> Please note that this method will completely remove the Media from the database, but current not from the file system. </remarks> <param name="media">The <see cref="IMedia"/> to delete</param> <param name="userId">Id of the User deleting the Media</param> Attempt<OperationResult> Delete(IMedia media, int userId = Constants.Security.SuperUserId); <summary> Saves a single <see cref="IMedia"/> object </summary> <param name="media">The <see cref="IMedia"/> to save</param> <param name="userId">Id of the User saving the Media</param> Attempt<OperationResult> Save(IMedia media, int userId = Constants.Security.SuperUserId); <summary> Saves a collection of <see cref="IMedia"/> objects </summary> <param name="medias">Collection of <see cref="IMedia"/> to save</param> <param name="userId">Id of the User saving the Media</param> Attempt<OperationResult> Save(IEnumerable<IMedia> medias, int userId = Constants.Security.SuperUserId); <summary> Gets an <see cref="IMedia"/> object by its 'UniqueId' </summary> <param name="key">Guid key of the Media to retrieve</param> <returns><see cref="IMedia"/></returns> IMedia GetById(Guid key); <summary> Gets a collection of <see cref="IMedia"/> objects by Level </summary> <param name="level">The level to retrieve Media from</param> <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetByLevel(int level); <summary> Gets a specific version of an <see cref="IMedia"/> item. </summary> <param name="versionId">Id of the version to retrieve</param> <returns>An <see cref="IMedia"/> item</returns> IMedia GetVersion(int versionId); <summary> Gets a collection of an <see cref="IMedia"/> objects versions by Id </summary> <param name="id"></param> <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetVersions(int id); <summary> Checks whether an <see cref="IMedia"/> item has any children </summary> <param name="id">Id of the <see cref="IMedia"/></param> <returns>True if the media has any children otherwise False</returns> bool HasChildren(int id); <summary> Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date. </summary> <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param> <param name="versionDate">Latest version date</param> <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersions(int id, DateTime versionDate, int userId = Constants.Security.SuperUserId); <summary> Permanently deletes specific version(s) from an <see cref="IMedia"/> object. </summary> <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param> <param name="versionId">Id of the version to delete</param> <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param> <param name="userId">Optional Id of the User deleting versions of a Content object</param> void DeleteVersion(int id, int versionId, bool deletePriorVersions, int userId = Constants.Security.SuperUserId); <summary> Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property. </summary> <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param> <returns><see cref="IMedia"/></returns> IMedia GetMediaByPath(string mediaPath); <summary> Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. </summary> <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param> <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(int id); <summary> Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media. </summary> <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param> <returns>An Enumerable list of <see cref="IMedia"/> objects</returns> IEnumerable<IMedia> GetAncestors(IMedia media); <summary> Gets the parent of the current media as an <see cref="IMedia"/> item. </summary> <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param> <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(int id); <summary> Gets the parent of the current media as an <see cref="IMedia"/> item. </summary> <param name="media"><see cref="IMedia"/> to retrieve the parent from</param> <returns>Parent <see cref="IMedia"/> object</returns> IMedia GetParent(IMedia media); <summary> Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according to the ordering of items in the passed in <see cref="IEnumerable{T}"/>. </summary> <param name="items"></param> <param name="userId"></param> <returns>True if sorting succeeded, otherwise False</returns> bool Sort(IEnumerable<IMedia> items, int userId = Constants.Security.SuperUserId); <summary> Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> that this Media should based on. </summary> <remarks> This method returns an <see cref="IMedia"/> object that has been persisted to the database and therefor has an identity. </remarks> <param name="name">Name of the Media object</param> <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param> <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> <param name="userId">Optional id of the user creating the media item</param> <returns><see cref="IMedia"/></returns> IMedia <API key>(string name, IMedia parent, string mediaTypeAlias, int userId = Constants.Security.SuperUserId); <summary> Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/> that this Media should based on. </summary> <remarks> This method returns an <see cref="IMedia"/> object that has been persisted to the database and therefor has an identity. </remarks> <param name="name">Name of the Media object</param> <param name="parentId">Id of Parent for the new Media item</param> <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param> <param name="userId">Optional id of the user creating the media item</param> <returns><see cref="IMedia"/></returns> IMedia <API key>(string name, int parentId, string mediaTypeAlias, int userId = Constants.Security.SuperUserId); <summary> Gets the content of a media as a stream. </summary> <param name="filepath">The filesystem path to the media.</param> <returns>The content of the media.</returns> Stream <API key>(string filepath); <summary> Sets the content of a media. </summary> <param name="filepath">The filesystem path to the media.</param> <param name="content">The content of the media.</param> void SetMediaFileContent(string filepath, Stream content); <summary> Deletes a media file. </summary> <param name="filepath">The filesystem path to the media.</param> void DeleteMediaFile(string filepath); <summary> Gets the size of a media. </summary> <param name="filepath">The filesystem path to the media.</param> <returns>The size of the media.</returns> long GetMediaFileSize(string filepath); } }
#!/usr/bin/env python # 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, # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # in all copies or substantial portions of the Software. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # 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. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test that the Flatten() function is available and works. """ import TestSCons test = TestSCons.TestSCons() test.subdir('work') test.write(['work', 'SConstruct'], """ def cat(env, source, target): target = str(target[0]) f = open(target, "wb") for src in source: f.write(open(str(src), "rb").read()) f.close() env = Environment(BUILDERS={'Cat':Builder(action=cat)}) f1 = env.Cat('../file1.out', 'file1.in') f2 = env.Cat('../file2.out', ['file2a.in', 'file2b.in']) print list(map(str, Flatten(['begin', f1, 'middle', f2, 'end']))) print list(map(str, env.Flatten([f1, [['a', 'b'], 'c'], f2]))) SConscript('SConscript', "env") """) test.write(['work', 'SConscript'], """ Import("env") print Flatten([1, [2, 3], 4]) print env.Flatten([[[[1], 2], 3], 4]) """) test.write('file1.in', "file1.in\n") test.write('file2a.in', "file2a.in\n") test.write('file2b.in', "file2b.in\n") def double_backslash(f): p = test.workpath(f) return p.replace('\\', '\\\\') expect = """\ ['begin', '%s', 'middle', '%s', 'end'] ['%s', 'a', 'b', 'c', '%s'] [1, 2, 3, 4] [1, 2, 3, 4] """ % (double_backslash('file1.out'), double_backslash('file2.out'), double_backslash('file1.out'), double_backslash('file2.out')) test.run(chdir = "work", arguments = ".", stdout = test.wrap_stdout(read_str = expect, build_str = "scons: `.' is up to date.\n")) test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
if(jQuery) (function($) { $.extend($.fn, { miniColors: function(o, data) { var create = function(input, o, data) { // Creates a new instance of the miniColors selector // Determine initial color (defaults to white) var color = expandHex(input.val()) || 'ffffff', hsb = hex2hsb(color), rgb = hsb2rgb(hsb), alpha = parseFloat(input.attr('data-opacity')).toFixed(2); if( alpha > 1 ) alpha = 1; if( alpha < 0 ) alpha = 0; // Create trigger var trigger = $('<a class="miniColors-trigger" style="background-color: #' + color + '" href="#"></a>'); trigger.insertAfter(input); trigger.wrap('<span class="<API key>"></span>'); if( o.wrapperClassName ) { trigger.parent().addClass( o.wrapperClassName ); } if( o.opacity ) { trigger.css('backgroundColor', 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + alpha + ')'); } // Set input data and update attributes input .addClass('miniColors') .data('original-maxlength', input.attr('maxlength') || null) .data('<API key>', input.attr('autocomplete') || null) .data('letterCase', o.letterCase === 'uppercase' ? 'uppercase' : 'lowercase') .data('opacity', o.opacity ? true : false) .data('alpha', alpha) .data('trigger', trigger) .data('hsb', hsb) .data('change', o.change ? o.change : null) .data('close', o.close ? o.close : null) .data('open', o.open ? o.open : null) .attr('maxlength', 7) .attr('autocomplete', 'off') .val('#' + convertCase(color, o.letterCase)); // Handle options if( o.readonly || input.prop('readonly') ) input.prop('readonly', true); if( o.disabled || input.prop('disabled') ) disable(input); // Show selector when trigger is clicked trigger.on('click.miniColors', function(event) { event.preventDefault(); if( input.val() === '' ) input.val(' show(input); }); // Show selector when input receives focus input.on('focus.miniColors', function(event) { if( input.val() === '' ) input.val(' show(input); }); // Hide on blur input.on('blur.miniColors', function(event) { var hex = expandHex( hsb2hex(input.data('hsb')) ); input.val( hex ? '#' + convertCase(hex, input.data('letterCase')) : '' ); }); // Hide when tabbing out of the input input.on('keydown.miniColors', function(event) { if( event.keyCode === 9 ) hide(input); }); // Update when color is typed in input.on('keyup.miniColors', function(event) { setColorFromInput(input); }); // Handle pasting input.on('paste.miniColors', function(event) { // Short pause to wait for paste to complete setTimeout( function() { setColorFromInput(input); }, 5); }); }; var destroy = function(input) { // Destroys an active instance of the miniColors selector hide(); input = $(input); // Restore to original state input.data('trigger').parent().remove(); input .attr('autocomplete', input.data('<API key>')) .attr('maxlength', input.data('original-maxlength')) .removeData() .removeClass('miniColors') .off('.miniColors'); $(document).off('.miniColors'); }; var enable = function(input) { // Enables the input control and the selector input .prop('disabled', false) .data('trigger').parent().removeClass('disabled'); }; var disable = function(input) { // Disables the input control and the selector hide(input); input .prop('disabled', true) .data('trigger').parent().addClass('disabled'); }; var show = function(input) { // Shows the miniColors selector if( input.prop('disabled') ) return false; // Hide all other instances hide(); // Generate the selector var selector = $('<div class="miniColors-selector"></div>'); selector .append('<div class="miniColors-hues"><div class="<API key>"></div></div>') .append('<div class="miniColors-colors" style="background-color: #FFF;"><div class="<API key>"><div class="<API key>"></div></div>') .css('display', 'none') .addClass( input.attr('class') ); // Opacity if( input.data('opacity') ) { selector .addClass('opacity') .prepend('<div class="miniColors-opacity"><div class="<API key>"></div></div>'); } // Set background for colors var hsb = input.data('hsb'); selector .find('.miniColors-colors').css('backgroundColor', '#' + hsb2hex({ h: hsb.h, s: 100, b: 100 })).end() .find('.miniColors-opacity').css('backgroundColor', '#' + hsb2hex({ h: hsb.h, s: hsb.s, b: hsb.b })).end(); // Set colorPicker position var colorPosition = input.data('colorPosition'); if( !colorPosition ) colorPosition = <API key>(hsb); selector.find('.<API key>') .css('top', colorPosition.y + 'px') .css('left', colorPosition.x + 'px'); // Set huePicker position var huePosition = input.data('huePosition'); if( !huePosition ) huePosition = <API key>(hsb); selector.find('.<API key>').css('top', huePosition + 'px'); // Set opacity position var opacityPosition = input.data('opacityPosition'); if( !opacityPosition ) opacityPosition = <API key>(input.attr('data-opacity')); selector.find('.<API key>').css('top', opacityPosition + 'px'); // Set input data input .data('selector', selector) .data('huePicker', selector.find('.<API key>')) .data('opacityPicker', selector.find('.<API key>')) .data('colorPicker', selector.find('.<API key>')) .data('mousebutton', 0); $('BODY').append(selector); // Position the selector var trigger = input.data('trigger'), hidden = !input.is(':visible'), top = hidden ? trigger.offset().top + trigger.outerHeight() : input.offset().top + input.outerHeight(), left = hidden ? trigger.offset().left : input.offset().left, selectorWidth = selector.outerWidth(), selectorHeight = selector.outerHeight(), triggerWidth = trigger.outerWidth(), triggerHeight = trigger.outerHeight(), windowHeight = $(window).height(), windowWidth = $(window).width(), scrollTop = $(window).scrollTop(), scrollLeft = $(window).scrollLeft(); // Adjust based on viewport if( (top + selectorHeight) > windowHeight + scrollTop ) top = top - selectorHeight - triggerHeight; if( (left + selectorWidth) > windowWidth + scrollLeft ) left = left - selectorWidth + triggerWidth; // Set position and show selector.css({ top: top, left: left }).fadeIn(100); // Prevent text selection in IE selector.on('selectstart', function() { return false; }); // Hide on resize (IE7/8 trigger this when any element is resized...) if( !$.browser.msie || ($.browser.msie && $.browser.version >= 9) ) { $(window).on('resize.miniColors', function(event) { hide(input); }); } $(document) .on('mousedown.miniColors touchstart.miniColors', function(event) { input.data('mousebutton', 1); var testSubject = $(event.target).parents().andSelf(); if( testSubject.hasClass('miniColors-colors') ) { event.preventDefault(); input.data('moving', 'colors'); moveColor(input, event); } if( testSubject.hasClass('miniColors-hues') ) { event.preventDefault(); input.data('moving', 'hues'); moveHue(input, event); } if( testSubject.hasClass('miniColors-opacity') ) { event.preventDefault(); input.data('moving', 'opacity'); moveOpacity(input, event); } if( testSubject.hasClass('miniColors-selector') ) { event.preventDefault(); return; } if( testSubject.hasClass('miniColors') ) return; hide(input); }) .on('mouseup.miniColors touchend.miniColors', function(event) { event.preventDefault(); input.data('mousebutton', 0).removeData('moving'); }) .on('mousemove.miniColors touchmove.miniColors', function(event) { event.preventDefault(); if( input.data('mousebutton') === 1 ) { if( input.data('moving') === 'colors' ) moveColor(input, event); if( input.data('moving') === 'hues' ) moveHue(input, event); if( input.data('moving') === 'opacity' ) moveOpacity(input, event); } }); // Fire open callback if( input.data('open') ) { input.data('open').call(input.get(0), '#' + hsb2hex(hsb), $.extend(hsb2rgb(hsb), { a: parseFloat(input.attr('data-opacity')) })); } }; var hide = function(input) { // Hides one or more miniColors selectors // Hide all other instances if input isn't specified if( !input ) input = $('.miniColors'); input.each( function() { var selector = $(this).data('selector'); $(this).removeData('selector'); $(selector).fadeOut(100, function() { // Fire close callback if( input.data('close') ) { var hsb = input.data('hsb'), hex = hsb2hex(hsb); input.data('close').call(input.get(0), '#' + hex, $.extend(hsb2rgb(hsb), { a: parseFloat(input.attr('data-opacity')) })); } $(this).remove(); }); }); $(document).off('.miniColors'); }; var moveColor = function(input, event) { var colorPicker = input.data('colorPicker'); colorPicker.hide(); var position = { x: event.pageX, y: event.pageY }; // Touch support if( event.originalEvent.changedTouches ) { position.x = event.originalEvent.changedTouches[0].pageX; position.y = event.originalEvent.changedTouches[0].pageY; } position.x = position.x - input.data('selector').find('.miniColors-colors').offset().left - 6; position.y = position.y - input.data('selector').find('.miniColors-colors').offset().top - 6; if( position.x <= -5 ) position.x = -5; if( position.x >= 144 ) position.x = 144; if( position.y <= -5 ) position.y = -5; if( position.y >= 144 ) position.y = 144; input.data('colorPosition', position); colorPicker.css('left', position.x).css('top', position.y).show(); // Calculate saturation var s = Math.round((position.x + 5) * 0.67); if( s < 0 ) s = 0; if( s > 100 ) s = 100; // Calculate brightness var b = 100 - Math.round((position.y + 5) * 0.67); if( b < 0 ) b = 0; if( b > 100 ) b = 100; // Update HSB values var hsb = input.data('hsb'); hsb.s = s; hsb.b = b; // Set color setColor(input, hsb, true); }; var moveHue = function(input, event) { var huePicker = input.data('huePicker'); huePicker.hide(); var position = event.pageY; // Touch support if( event.originalEvent.changedTouches ) { position = event.originalEvent.changedTouches[0].pageY; } position = position - input.data('selector').find('.miniColors-colors').offset().top - 1; if( position <= -1 ) position = -1; if( position >= 149 ) position = 149; input.data('huePosition', position); huePicker.css('top', position).show(); // Calculate hue var h = Math.round((150 - position - 1) * 2.4); if( h < 0 ) h = 0; if( h > 360 ) h = 360; // Update HSB values var hsb = input.data('hsb'); hsb.h = h; // Set color setColor(input, hsb, true); }; var moveOpacity = function(input, event) { var opacityPicker = input.data('opacityPicker'); opacityPicker.hide(); var position = event.pageY; // Touch support if( event.originalEvent.changedTouches ) { position = event.originalEvent.changedTouches[0].pageY; } position = position - input.data('selector').find('.miniColors-colors').offset().top - 1; if( position <= -1 ) position = -1; if( position >= 149 ) position = 149; input.data('opacityPosition', position); opacityPicker.css('top', position).show(); // Calculate opacity var alpha = parseFloat((150 - position - 1) / 150).toFixed(2); if( alpha < 0 ) alpha = 0; if( alpha > 1 ) alpha = 1; // Update opacity input .data('alpha', alpha) .attr('data-opacity', alpha); // Set color setColor(input, input.data('hsb'), true); }; var setColor = function(input, hsb, updateInput) { input.data('hsb', hsb); var hex = hsb2hex(hsb), selector = $(input.data('selector')); if( updateInput ) input.val( '#' + convertCase(hex, input.data('letterCase')) ); selector .find('.miniColors-colors').css('backgroundColor', '#' + hsb2hex({ h: hsb.h, s: 100, b: 100 })).end() .find('.miniColors-opacity').css('backgroundColor', '#' + hex).end(); var rgb = hsb2rgb(hsb); // Set background color (also fallback for non RGBA browsers) input.data('trigger').css('backgroundColor', '#' + hex); // Set background color + opacity if( input.data('opacity') ) { input.data('trigger').css('backgroundColor', 'rgba(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ', ' + input.attr('data-opacity') + ')'); } // Fire change callback if( input.data('change') ) { if( (hex + ',' + input.attr('data-opacity')) === input.data('lastChange') ) return; input.data('change').call(input.get(0), '#' + hex, $.extend(hsb2rgb(hsb), { a: parseFloat(input.attr('data-opacity')) })); input.data('lastChange', hex + ',' + input.attr('data-opacity')); } }; var setColorFromInput = function(input) { input.val('#' + cleanHex(input.val())); var hex = expandHex(input.val()); if( !hex ) return false; // Get HSB equivalent var hsb = hex2hsb(hex); // Set colorPicker position var colorPosition = <API key>(hsb); var colorPicker = $(input.data('colorPicker')); colorPicker.css('top', colorPosition.y + 'px').css('left', colorPosition.x + 'px'); input.data('colorPosition', colorPosition); // Set huePosition position var huePosition = <API key>(hsb); var huePicker = $(input.data('huePicker')); huePicker.css('top', huePosition + 'px'); input.data('huePosition', huePosition); // Set opacity position var opacityPosition = <API key>(input.attr('data-opacity')); var opacityPicker = $(input.data('opacityPicker')); opacityPicker.css('top', opacityPosition + 'px'); input.data('opacityPosition', opacityPosition); setColor(input, hsb); return true; }; var convertCase = function(string, letterCase) { if( letterCase === 'uppercase' ) { return string.toUpperCase(); } else { return string.toLowerCase(); } }; var <API key> = function(hsb) { var x = Math.ceil(hsb.s / 0.67); if( x < 0 ) x = 0; if( x > 150 ) x = 150; var y = 150 - Math.ceil(hsb.b / 0.67); if( y < 0 ) y = 0; if( y > 150 ) y = 150; return { x: x - 5, y: y - 5 }; }; var <API key> = function(hsb) { var y = 150 - (hsb.h / 2.4); if( y < 0 ) h = 0; if( y > 150 ) h = 150; return y; }; var <API key> = function(alpha) { var y = 150 * alpha; if( y < 0 ) y = 0; if( y > 150 ) y = 150; return 150 - y; }; var cleanHex = function(hex) { return hex.replace(/[^A-F0-9]/ig, ''); }; var expandHex = function(hex) { hex = cleanHex(hex); if( !hex ) return null; if( hex.length === 3 ) hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; return hex.length === 6 ? hex : null; }; var hsb2rgb = function(hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s*255/100); var v = Math.round(hsb.b*255/100); if(s === 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255 - s) * v / 255; var t3 = (t1 - t2) * (h % 60) / 60; if( h === 360 ) h = 0; if( h < 60 ) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3; } else if( h < 120 ) {rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3; } else if( h < 180 ) {rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3; } else if( h < 240 ) {rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3; } else if( h < 300 ) {rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3; } else if( h < 360 ) {rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3; } else { rgb.r = 0; rgb.g = 0; rgb.b = 0; } } return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) }; }; var rgb2hex = function(rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function(nr, val) { if (val.length === 1) hex[nr] = '0' + val; }); return hex.join(''); }; var hex2rgb = function(hex) { hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return { r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF) }; }; var rgb2hsb = function(rgb) { var hsb = { h: 0, s: 0, b: 0 }; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; hsb.s = max !== 0 ? 255 * delta / max : 0; if( hsb.s !== 0 ) { if( rgb.r === max ) { hsb.h = (rgb.g - rgb.b) / delta; } else if( rgb.g === max ) { hsb.h = 2 + (rgb.b - rgb.r) / delta; } else { hsb.h = 4 + (rgb.r - rgb.g) / delta; } } else { hsb.h = -1; } hsb.h *= 60; if( hsb.h < 0 ) { hsb.h += 360; } hsb.s *= 100/255; hsb.b *= 100/255; return hsb; }; var hex2hsb = function(hex) { var hsb = rgb2hsb(hex2rgb(hex)); if( hsb.s === 0 ) hsb.h = 360; return hsb; }; var hsb2hex = function(hsb) { return rgb2hex(hsb2rgb(hsb)); }; // Handle calls to $([selector]).miniColors() switch(o) { case 'readonly': $(this).each( function() { if( !$(this).hasClass('miniColors') ) return; $(this).prop('readonly', data); }); return $(this); case 'disabled': $(this).each( function() { if( !$(this).hasClass('miniColors') ) return; if( data ) { disable($(this)); } else { enable($(this)); } }); return $(this); case 'value': // Getter if( data === undefined ) { if( !$(this).hasClass('miniColors') ) return; var input = $(this), hex = expandHex(input.val()); return hex ? '#' + convertCase(hex, input.data('letterCase')) : null; } // Setter $(this).each( function() { if( !$(this).hasClass('miniColors') ) return; $(this).val(data); setColorFromInput($(this)); }); return $(this); case 'opacity': // Getter if( data === undefined ) { if( !$(this).hasClass('miniColors') ) return; if( $(this).data('opacity') ) { return parseFloat($(this).attr('data-opacity')); } else { return null; } } // Setter $(this).each( function() { if( !$(this).hasClass('miniColors') ) return; if( data < 0 ) data = 0; if( data > 1 ) data = 1; $(this).attr('data-opacity', data).data('alpha', data); setColorFromInput($(this)); }); return $(this); case 'destroy': $(this).each( function() { if( !$(this).hasClass('miniColors') ) return; destroy($(this)); }); return $(this); default: if( !o ) o = {}; $(this).each( function() { // Must be called on an input element if( $(this)[0].tagName.toLowerCase() !== 'input' ) return; // If a trigger is present, the control was already created if( $(this).data('trigger') ) return; // Create the control create($(this), o, data); }); return $(this); } } }); })(jQuery);
<html><head><link rel="canonical" href="/2014/06/04/<API key>"><meta http-equiv="refresh" content="0; url=/2014/06/04/<API key>"></head><body></body></html>
<TS language="fil" version="2.1"> <context> <name>AboutDialog</name> </context> <context> <name>AddressBookPage</name> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> </context> <context> <name>BitcoinGUI</name> </context> <context> <name>ClientModel</name> </context> <context> <name>CoinControlDialog</name> </context> <context> <name>EditAddressDialog</name> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> </context> <context> <name>OverviewPage</name> </context> <context> <name>PaymentServer</name> </context> <context> <name>QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name><API key></name> </context> <context> <name><API key></name> </context> <context> <name>SendCoinsDialog</name> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name><API key></name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name><API key></name> </context> <context> <name><API key></name> </context> <context> <name>TransactionView</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> </context> </TS>
Ext.ns('Ext.ux.grid'); Ext.ux.grid.MetaGrid = Ext.extend(Object, { /** * @cfg {Boolean} maskEmpty * Defaults to <tt>true</tt> to mask the grid if there's no data to make it * even more obvious that the grid is empty. This will apply a mask to the * grid's body with a message in the middle if there are zero rows - quite * hard for the user to miss. */ maskEmpty: false, paging: { perPage: 25 }, stripeRows: true, /** * @cfg {Boolean} trackMouseOver * Defaults to <tt>true</tt>. See Ext.grid.GridPanel. */ trackMouseOver: true, constructor: function (config) { Ext.apply(this, config); }, // @private init: function(grid) { this.grid = grid; this.grid.on({ render: this.onRender, destroy: this.onDestroy, scope: this }); grid.store.on({ // register to the store's metachange event metachange: { fn: this.onMetaChange, scope: this }, loadexception: { fn: function(proxy, options, response, e){ if (Ext.isFirebug) { console.warn('store loadexception: ', arguments); } else { Ext.Msg.alert('store loadexception: ', arguments); } } }, scope: this }); // mask the grid if there is no data if so configured if (this.maskEmpty) { grid.store.on( 'load', function() { if (this.store.getTotalCount() == 0) { var el = this.getGridEl(); if (typeof el == 'object'){ el.mask('No Data', 'x-mask'); } } }, grid // scope it to grid ); } if (grid.filters) { grid.filters = new Ext.grid.GridFilters({ filters:[] }); this.plugins.push(grid.filters); this.paging.plugins = []; this.pagingPlugins.push(grid.filters); } /* //Create Paging Toolbar this.pagingToolbar = new Ext.PagingToolbar({ store: grid.store, pageSize: this.pageSize || 25, //default is 20 plugins: this.pagingPlugins, displayInfo: true,//default is false (to not show displayMsg) displayMsg: 'Displaying {0} - {1} of {2}', emptyMsg: "No data to display",//display message when no records found items: [{ text: 'Change data', scope: this }] }); //Add a bottom bar this.bbar = this.pagingToolbar; */ /* * JSONReader provides metachange functionality which allows you to create * dynamic records natively * It does not allow you to create the grid's column model dynamically. */ if (grid.columns && (grid.columns instanceof Array)) { grid.colModel = new Ext.grid.ColumnModel(grid.columns); delete grid.columns; } // Create a empty colModel if none given if (!grid.colModel) { grid.colModel = new Ext.grid.ColumnModel([]); } }, // @private onRender : function() { var params = { //this is only parameters for the FIRST page load, reconfigure: true, start: 0, //pass start/limit parameters for paging limit: this.paging.perPage }; this.grid.store.load({params: params}); }, // @private onDestroy: function() { }, /** * Configure the reader using the server supplied meta data. * This grid is observing the store's metachange event (which will be triggered * when the metaData property is detected in the returned json data object). * This method is specified as the handler for the that metachange event. * This method interrogates the metaData property of the json packet (passed * to this method as the 2nd argument ). * @param {Object} store * @param {Object} meta The reader's meta property that exposes the JSON metadata */ onMetaChange: function(store, meta){ var cols = [], script; Ext.each(meta.fields, function(col){ // do not add to column model if ignoreColumn == true if (col.ignoreColumn) { return; } // if not specified assign dataIndex to name if (typeof col.dataIndex == "undefined" && col.name) { col.dataIndex = col.name; } //if using gridFilters extension if (this.grid.filters) { if (col.filter !== undefined) { if ((col.filter.type !== undefined)) { col.filter.dataIndex = col.dataIndex; this.filters.addFilter(col.filter); } } delete col.filter; } // if renderer specified if (typeof col.renderer == "string") { // if specified Ext.util or a function will eval to get that function if (col.renderer.indexOf("Ext") < 0 && col.renderer.indexOf("function") < 0) { col.renderer = this.grid[col.renderer].createDelegate(this.grid); } else { col.renderer = eval(col.renderer); } } // if listeners specified in meta data l = col.listeners; if (typeof l == "object") { for (var e in l) { if (typeof e == "string") { for (var c in l[e]) { if (typeof c == "string") { l[e][c] = eval(l[e][c]); } } } } } // if convert specified assume it's a function and eval it if (col.convert) { col.convert = eval(col.convert); } // column editor if (col.editor) { col.editor = Ext.create(col.editor, 'textfield'); } // check if script property specified on the column // use this property to pass back custom code wrapped inside a self evaluating function: // (function () { <<do whatever>> })() if (col.script){ script = eval(col.script); Ext.apply(col, script); } // if plugin specified add it if (col.ptype !== undefined) { // requires overrides to Ext.Component and Ext.ComponentMgr col = this.grid.addPlugin(col); } // add ability to change to <API key> if (col.selModel){ col = this.setSelectionModel(col.selModel); } // add column to colModel config array cols.push(col); }, this); // end of columns loop var cm = new Ext.grid.ColumnModel({ columns: cols, defaults: meta.cmDefaults || {}, listeners: meta.cmListeners || {} }); // apply any passed grid configs (eg, autoExpandColumn, etc) if (meta.gridConfig) { Ext.apply(this.grid, meta.gridConfig); // explicitly apply any viewConfigs to view if (meta.gridConfig.viewConfig){ Ext.apply(this.grid.getView(), meta.gridConfig.viewConfig); // will have limited success, scroller won't be changed, etc. // if setting forceFit=true might need: //this.grid.getView().scroller.setStyle('overflow-x', 'hidden'); } } // use meta.storeConfig to provide capability to change the store, // perhaps change to a GroupingStore, etc. var newStore; if (meta.storeConfig) { var storeConfig = Ext.apply({}, meta.storeConfig); newStore = Ext.StoreMgr.lookup(storeConfig); } else { newStore = store; } // Reconfigure the grid to use a different Store and Column Model. The View // will be bound to the new objects and refreshed. this.grid.reconfigure(newStore, cm); // update the store for the pagingtoolbar also if(this.grid.pagingToolbar){ this.grid.pagingToolbar.bindStore(newStore); } if (this.grid.stateful) { this.grid.initState(); } }, // experimental, dynamically change selection model setSelectionModel : function(sm){ delete this.grid.selModel; this.grid.selModel = new Ext.grid[sm.type](sm.cfg); sm = this.grid.selModel; sm.grid = this.grid; var view = this.grid.getView(); view.mainBody.on('mousedown', sm.onMouseDown, sm); Ext.fly(view.innerHd).on('mousedown', sm.onHdMouseDown, sm); return sm; } }); // register ptype Ext.preg('ux-grid-metagrid', Ext.ux.grid.MetaGrid);
// Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro.Models { using Fixtures.Azure; using Fixtures.Azure.AcceptanceTestsLro; using Newtonsoft.Json; using System.Linq; <summary> Defines headers for <API key> operation. </summary> public partial class <API key> { <summary> Initializes a new instance of the <API key> class. </summary> public <API key>() { } <summary> Initializes a new instance of the <API key> class. </summary> <param name="azureAsyncOperation">Location to poll for result status: will be set to /lro/error/deleteasync/retry/failed/operationResults/invalidjsonpolling</param> <param name="location">Location to poll for result status: will be set to /lro/error/deleteasync/retry/failed/operationResults/invalidjsonpolling</param> <param name="retryAfter">Number of milliseconds until the next poll should be sent, will be set to zero</param> public <API key>(string azureAsyncOperation = default(string), string location = default(string), int? retryAfter = default(int?)) { AzureAsyncOperation = azureAsyncOperation; Location = location; RetryAfter = retryAfter; } <summary> Gets or sets location to poll for result status: will be set to /lro/error/deleteasync/retry/failed/operationResults/invalidjsonpolling </summary> [JsonProperty(PropertyName = "<API key>")] public string AzureAsyncOperation { get; set; } <summary> Gets or sets location to poll for result status: will be set to /lro/error/deleteasync/retry/failed/operationResults/invalidjsonpolling </summary> [JsonProperty(PropertyName = "Location")] public string Location { get; set; } <summary> Gets or sets number of milliseconds until the next poll should be sent, will be set to zero </summary> [JsonProperty(PropertyName = "Retry-After")] public int? RetryAfter { get; set; } } }
using System; namespace Piranha.Data { <summary> Base interface for all models. </summary> public interface IModel { <summary> Gets/sets the unique id. </summary> Guid Id { get; set; } } }
/** * @fileoverview Tests for no-duplicate-case rule. * @author Dieter Oberkofler */ "use strict"; // Requirements const rule = require("../../../lib/rules/no-duplicate-case"), { RuleTester } = require("../../../lib/rule-tester"); // Tests const ruleTester = new RuleTester(); ruleTester.run("no-duplicate-case", rule, { valid: [ "var a = 1; switch (a) {case 1: break; case 2: break; default: break;}", "var a = 1; switch (a) {case 1: break; case '1': break; default: break;}", "var a = 1; switch (a) {case 1: break; case true: break; default: break;}", "var a = 1; switch (a) {default: break;}", "var a = 1, p = {p: {p1: 1, p2: 1}}; switch (a) {case p.p.p1: break; case p.p.p2: break; default: break;}", "var a = 1, f = function(b) { return b ? { p1: 1 } : { p1: 2 }; }; switch (a) {case f(true).p1: break; case f(true, false).p1: break; default: break;}", "var a = 1, f = function(s) { return { p1: s } }; switch (a) {case f(a + 1).p1: break; case f(a + 2).p1: break; default: break;}", "var a = 1, f = function(s) { return { p1: s } }; switch (a) {case f(a == 1 ? 2 : 3).p1: break; case f(a === 1 ? 2 : 3).p1: break; default: break;}", "var a = 1, f1 = function() { return { p1: 1 } }, f2 = function() { return { p1: 2 } }; switch (a) {case f1().p1: break; case f2().p1: break; default: break;}", "var a = [1,2]; switch(a.toString()){case ([1,2]).toString():break; case ([1]).toString():break; default:break;}", "switch(a) { case a: break; } switch(a) { case a: break; }", "switch(a) { case toString: break; }" ], invalid: [ { code: "var a = 1; switch (a) {case 1: break; case 1: break; case 2: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 39 }] }, { code: "var a = '1'; switch (a) {case '1': break; case '1': break; case '2': break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 43 }] }, { code: "var a = 1, one = 1; switch (a) {case one: break; case one: break; case 2: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 50 }] }, { code: "var a = 1, p = {p: {p1: 1, p2: 1}}; switch (a) {case p.p.p1: break; case p.p.p1: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 69 }] }, { code: "var a = 1, f = function(b) { return b ? { p1: 1 } : { p1: 2 }; }; switch (a) {case f(true).p1: break; case f(true).p1: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 103 }] }, { code: "var a = 1, f = function(s) { return { p1: s } }; switch (a) {case f(a + 1).p1: break; case f(a + 1).p1: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 87 }] }, { code: "var a = 1, f = function(s) { return { p1: s } }; switch (a) {case f(a === 1 ? 2 : 3).p1: break; case f(a === 1 ? 2 : 3).p1: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 97 }] }, { code: "var a = 1, f1 = function() { return { p1: 1 } }; switch (a) {case f1().p1: break; case f1().p1: break; default: break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 83 }] }, { code: "var a = [1, 2]; switch(a.toString()){case ([1, 2]).toString():break; case ([1, 2]).toString():break; default:break;}", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 70 }] }, { code: "switch (a) { case a: case a: }", errors: [{ messageId: "unexpected", type: "SwitchCase", column: 22 }] }, { code: "switch (a) { case a: break; case b: break; case a: break; case c: break; case a: break; }", errors: [ { messageId: "unexpected", type: "SwitchCase", column: 44 }, { messageId: "unexpected", type: "SwitchCase", column: 74 } ] } ] });
'use strict'; import H from '../../parts/Globals.js'; import '../../parts/Utilities.js'; var Annotation = H.Annotation, MockPoint = Annotation.MockPoint; /** * @class * @extends Annotation * @memberOf Highcharts **/ function VerticalLine() { H.Annotation.apply(this, arguments); } VerticalLine.connectorFirstPoint = function (target) { var annotation = target.annotation, point = annotation.points[0], xy = MockPoint.pointToPixels(point, true), y = xy.y, offset = annotation.options.typeOptions.label.offset; if (annotation.chart.inverted) { y = xy.x; } return { x: point.x, xAxis: point.series.xAxis, y: y + offset }; }; VerticalLine.<API key> = function (target) { var annotation = target.annotation, typeOptions = annotation.options.typeOptions, point = annotation.points[0], yOffset = typeOptions.yOffset, xy = MockPoint.pointToPixels(point, true), y = xy[annotation.chart.inverted ? 'x' : 'y']; if (typeOptions.label.offset < 0) { yOffset *= -1; } return { x: point.x, xAxis: point.series.xAxis, y: y + yOffset }; }; H.extendAnnotation(VerticalLine, null, /** @lends Annotation.VerticalLine# */ { getPointsOptions: function () { return [ this.options.typeOptions.point ]; }, addShapes: function () { var typeOptions = this.options.typeOptions, connector = this.initShape( H.merge(typeOptions.connector, { type: 'path', points: [ VerticalLine.connectorFirstPoint, VerticalLine.<API key> ] }), false ); typeOptions.connector = connector.options; }, addLabels: function () { var typeOptions = this.options.typeOptions, labelOptions = typeOptions.label, x = 0, y = labelOptions.offset, verticalAlign = labelOptions.offset < 0 ? 'bottom' : 'top', align = 'center'; if (this.chart.inverted) { x = labelOptions.offset; y = 0; verticalAlign = 'middle'; align = labelOptions.offset < 0 ? 'right' : 'left'; } var label = this.initLabel( H.merge(labelOptions, { verticalAlign: verticalAlign, align: align, x: x, y: y }) ); typeOptions.label = label.options; } }, /** * A vertical line annotation. * * @extends annotations.crookedLine * @excluding labels, shapes, controlPointOptions * @sample highcharts/<API key>/vertical-line/ * Vertical line * @product highstock * @optionparent annotations.verticalLine */ { typeOptions: { /** * @ignore */ yOffset: 10, /** * Label options. * * @extends annotations.crookedLine.labelOptions */ label: { offset: -40, point: function (target) { return target.annotation.points[0]; }, allowOverlap: true, backgroundColor: 'none', borderWidth: 0, crop: true, overflow: 'none', shape: 'rect', text: '{y:.2f}' }, /** * Connector options. * * @extends annotations.crookedLine.shapeOptions * @excluding height, r, type, width */ connector: { strokeWidth: 1, markerEnd: 'arrow' } } }); Annotation.types.verticalLine = VerticalLine; export default VerticalLine;
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitfilter', ['uikit-util'], factory) : (global = global || self, global.UIkitFilter = factory(global.UIkit.util)); }(this, function (uikitUtil) { 'use strict'; var targetClass = 'uk-animation-target'; var Animate = { props: { animation: Number }, data: { animation: 150 }, computed: { target: function() { return this.$el; } }, methods: { animate: function(action) { var this$1 = this; addStyle(); var children = uikitUtil.toNodes(this.target.children); var propsFrom = children.map(function (el) { return getProps(el, true); }); var oldHeight = uikitUtil.height(this.target); var oldScrollY = window.pageYOffset; action(); uikitUtil.Transition.cancel(this.target); children.forEach(uikitUtil.Transition.cancel); reset(this.target); this.$update(this.target); uikitUtil.fastdom.flush(); var newHeight = uikitUtil.height(this.target); children = children.concat(uikitUtil.toNodes(this.target.children).filter(function (el) { return !uikitUtil.includes(children, el); })); var propsTo = children.map(function (el, i) { return el.parentNode && i in propsFrom ? propsFrom[i] ? uikitUtil.isVisible(el) ? <API key>(el) : {opacity: 0} : {opacity: uikitUtil.isVisible(el) ? 1 : 0} : false; } ); propsFrom = propsTo.map(function (props, i) { var from = children[i].parentNode === this$1.target ? propsFrom[i] || getProps(children[i]) : false; if (from) { if (!props) { delete from.opacity; } else if (!('opacity' in props)) { var opacity = from.opacity; if (opacity % 1) { props.opacity = 1; } else { delete from.opacity; } } } return from; }); uikitUtil.addClass(this.target, targetClass); children.forEach(function (el, i) { return propsFrom[i] && uikitUtil.css(el, propsFrom[i]); }); uikitUtil.css(this.target, 'height', oldHeight); uikitUtil.scrollTop(window, oldScrollY); return uikitUtil.Promise.all(children.map(function (el, i) { return propsFrom[i] && propsTo[i] ? uikitUtil.Transition.start(el, propsTo[i], this$1.animation, 'ease') : uikitUtil.Promise.resolve(); } ).concat(uikitUtil.Transition.start(this.target, {height: newHeight}, this.animation, 'ease'))).then(function () { children.forEach(function (el, i) { return uikitUtil.css(el, {display: propsTo[i].opacity === 0 ? 'none' : '', zIndex: ''}); }); reset(this$1.target); this$1.$update(this$1.target); uikitUtil.fastdom.flush(); // needed for IE11 }, uikitUtil.noop); } } }; function getProps(el, opacity) { var zIndex = uikitUtil.css(el, 'zIndex'); return uikitUtil.isVisible(el) ? uikitUtil.assign({ display: '', opacity: opacity ? uikitUtil.css(el, 'opacity') : '0', pointerEvents: 'none', position: 'absolute', zIndex: zIndex === 'auto' ? uikitUtil.index(el) : zIndex }, <API key>(el)) : false; } function reset(el) { uikitUtil.css(el.children, { height: '', left: '', opacity: '', pointerEvents: '', position: '', top: '', width: '' }); uikitUtil.removeClass(el, targetClass); uikitUtil.css(el, 'height', ''); } function <API key>(el) { var ref = el.<API key>(); var height = ref.height; var width = ref.width; var ref$1 = uikitUtil.position(el); var top = ref$1.top; var left = ref$1.left; top += uikitUtil.toFloat(uikitUtil.css(el, 'marginTop')); return {top: top, left: left, height: height, width: width}; } var style; function addStyle() { if (style) { return; } style = uikitUtil.append(document.head, '<style>').sheet; style.insertRule( ("." + targetClass + " > * {\n margin-top: 0 !important;\n transform: none !important;\n }"), 0 ); } var Component = { mixins: [Animate], args: 'target', props: { target: Boolean, selActive: Boolean }, data: { target: null, selActive: false, attrItem: 'uk-filter-control', cls: 'uk-active', animation: 250 }, computed: { toggles: { get: function(ref, $el) { var attrItem = ref.attrItem; return uikitUtil.$$(("[" + (this.attrItem) + "],[data-" + (this.attrItem) + "]"), $el); }, watch: function() { this.updateState(); } }, target: function(ref, $el) { var target = ref.target; return uikitUtil.$(target, $el); }, children: { get: function() { return uikitUtil.toNodes(this.target && this.target.children); }, watch: function(list, old) { if (!isEqualList(list, old)) { this.updateState(); } } } }, events: [ { name: 'click', delegate: function() { return ("[" + (this.attrItem) + "],[data-" + (this.attrItem) + "]"); }, handler: function(e) { e.preventDefault(); this.apply(e.current); } } ], connected: function() { var this$1 = this; this.updateState(); if (this.selActive !== false) { var actives = uikitUtil.$$(this.selActive, this.$el); this.toggles.forEach(function (el) { return uikitUtil.toggleClass(el, this$1.cls, uikitUtil.includes(actives, el)); }); } }, methods: { apply: function(el) { this.setState(mergeState(el, this.attrItem, this.getState())); }, getState: function() { var this$1 = this; return this.toggles .filter(function (item) { return uikitUtil.hasClass(item, this$1.cls); }) .reduce(function (state, el) { return mergeState(el, this$1.attrItem, state); }, {filter: {'': ''}, sort: []}); }, setState: function(state, animate) { var this$1 = this; if ( animate === void 0 ) animate = true; state = uikitUtil.assign({filter: {'': ''}, sort: []}, state); uikitUtil.trigger(this.$el, 'beforeFilter', [this, state]); var ref = this; var children = ref.children; this.toggles.forEach(function (el) { return uikitUtil.toggleClass(el, this$1.cls, !!matchFilter(el, this$1.attrItem, state)); }); var apply = function () { var selector = getSelector(state); children.forEach(function (el) { return uikitUtil.css(el, 'display', selector && !uikitUtil.matches(el, selector) ? 'none' : ''); }); var ref = state.sort; var sort = ref[0]; var order = ref[1]; if (sort) { var sorted = sortItems(children, sort, order); if (!uikitUtil.isEqual(sorted, children)) { sorted.forEach(function (el) { return uikitUtil.append(this$1.target, el); }); } } }; if (animate) { this.animate(apply).then(function () { return uikitUtil.trigger(this$1.$el, 'afterFilter', [this$1]); }); } else { apply(); uikitUtil.trigger(this.$el, 'afterFilter', [this]); } }, updateState: function() { var this$1 = this; uikitUtil.fastdom.write(function () { return this$1.setState(this$1.getState(), false); }); } } }; function getFilter(el, attr) { return uikitUtil.parseOptions(uikitUtil.data(el, attr), ['filter']); } function mergeState(el, attr, state) { var filterBy = getFilter(el, attr); var filter = filterBy.filter; var group = filterBy.group; var sort = filterBy.sort; var order = filterBy.order; if ( order === void 0 ) order = 'asc'; if (filter || uikitUtil.isUndefined(sort)) { if (group) { if (filter) { delete state.filter['']; state.filter[group] = filter; } else { delete state.filter[group]; if (uikitUtil.isEmpty(state.filter) || '' in state.filter) { state.filter = {'': filter || ''}; } } } else { state.filter = {'': filter || ''}; } } if (!uikitUtil.isUndefined(sort)) { state.sort = [sort, order]; } return state; } function matchFilter(el, attr, ref) { var stateFilter = ref.filter; if ( stateFilter === void 0 ) stateFilter = {'': ''}; var ref_sort = ref.sort; var stateSort = ref_sort[0]; var stateOrder = ref_sort[1]; var ref$1 = getFilter(el, attr); var filter = ref$1.filter; if ( filter === void 0 ) filter = ''; var group = ref$1.group; if ( group === void 0 ) group = ''; var sort = ref$1.sort; var order = ref$1.order; if ( order === void 0 ) order = 'asc'; return uikitUtil.isUndefined(sort) ? group in stateFilter && filter === stateFilter[group] || !filter && group && !(group in stateFilter) && !stateFilter[''] : stateSort === sort && stateOrder === order; } function isEqualList(listA, listB) { return listA.length === listB.length && listA.every(function (el) { return ~listB.indexOf(el); }); } function getSelector(ref) { var filter = ref.filter; var selector = ''; uikitUtil.each(filter, function (value) { return selector += value || ''; }); return selector; } function sortItems(nodes, sort, order) { return uikitUtil.assign([], nodes).sort(function (a, b) { return uikitUtil.data(a, sort).localeCompare(uikitUtil.data(b, sort), undefined, {numeric: true}) * (order === 'asc' || -1); }); } /* global UIkit, 'filter' */ if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('filter', Component); } return Component; }));
// copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // 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: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 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. #import <Foundation/Foundation.h> #import <GLKit/GLKit.h> @class LCGLLineGraph; @interface LCGLDataLine : NSObject @property (nonatomic, strong) UIColor *color; - (id)initWithColor:(UIColor*)aColor forGraph:(LCGLLineGraph*)aGraph; - (void)addLineDataValue:(double)value; - (void)addLineDataArray:(NSArray*)dataArray; - (void)resetLineData; - (void)<API key>:(NSString*)text; - (void)<API key>:(UIImage*)image; - (void)render; - (void)renderLegend:(NSUInteger)lineIndex; - (NSUInteger)maxDataLineElements; - (void)setDataLineZoom:(GLfloat)zoom; @end
using System; using ClosedXML.Excel; namespace ClosedXML_Examples.Misc { public class Hyperlinks : IXLExample { #region Variables // Public // Private #endregion #region Properties // Public // Private // Override #endregion #region Events // Public // Private // Override #endregion #region Methods // Public public void Create(String filePath) { var wb = new XLWorkbook(); var ws = wb.Worksheets.Add("Hyperlinks"); wb.Worksheets.Add("Second Sheet"); Int32 ro = 0; // You can create a link with pretty much anything you can put on a // browser: http, ftp, mailto, gopher, news, nntp, etc. ws.Cell(++ro, 1).Value = "Link to a web page, no tooltip - Yahoo!"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink(@"http: ws.Cell(++ro, 1).Value = "Link to a web page, with a tooltip - Yahoo!"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink(@"http: ws.Cell(++ro, 1).Value = "Link to a file - same folder"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink("Test.xlsx"); ws.Cell(++ro, 1).Value = "Link to a file - Absolute"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink(@"D:\Test.xlsx"); ws.Cell(++ro, 1).Value = "Link to a file - relative address"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink(@"../Test.xlsx"); ws.Cell(++ro, 1).Value = "Link to an address in this worksheet"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink("B1"); ws.Cell(++ro, 1).Value = "Link to an address in another worksheet"; ws.Cell(ro, 1).Hyperlink = new XLHyperlink("'Second Sheet'!A1"); // You can also set the properties of a hyperlink directly: ws.Cell(++ro, 1).Value = "Link to a range in this worksheet"; ws.Cell(ro, 1).Hyperlink.InternalAddress = "B1:C2"; ws.Cell(ro, 1).Hyperlink.Tooltip = "SquareBox"; ws.Cell(++ro, 1).Value = "Link to an email message"; ws.Cell(ro, 1).Hyperlink.ExternalAddress = new Uri(@"mailto:SantaClaus@NorthPole.com?subject=Presents"); // Deleting a hyperlink ws.Cell(++ro, 1).Value = "This is no longer a link"; ws.Cell(ro, 1).Hyperlink.InternalAddress = "A1"; ws.Cell(ro, 1).Hyperlink.Delete(); // Setting a hyperlink preserves previous formatting: ws.Cell(++ro, 1).Value = "Odd looking link"; ws.Cell(ro, 1).Style.Font.FontColor = XLColor.Red; ws.Cell(ro, 1).Style.Font.Underline = <API key>.Double; ws.Cell(ro, 1).Hyperlink = new XLHyperlink(ws.Range("B1:C2")); // Hyperlink via formula ws.Cell( ++ro, 1 ).SetValue( "Send Email" ) .SetFormulaA1( "=HYPERLINK(\"mailto:test@test.com\", \"Send Email\")" ) .Hyperlink = new XLHyperlink( "mailto:test@test.com", "'Send Email'" ); // List all hyperlinks in a worksheet: var <API key> = ws.Hyperlinks; // List all hyperlinks in a range: var hyperlinksInRange = ws.Range("A1:A3").Hyperlinks; // Clearing a cell with a hyperlink ws.Cell(++ro, 1).Value = "ERROR!"; ws.Cell(ro, 1).Hyperlink.InternalAddress = "A1"; ws.Cell(ro, 1).Clear(); // Deleting a cell with a hyperlink ws.Cell(++ro, 1).Value = "ERROR!"; ws.Cell(ro, 1).Hyperlink.InternalAddress = "A1"; ws.Cell(ro, 1).Clear(); ws.Columns().AdjustToContents(); wb.SaveAs(filePath); } // Private // Override #endregion } }
#!/usr/bin/env python # Electrum - lightweight Bitcoin client # 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, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # included in all copies or substantial portions of the Software. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # 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. import os import util from bitcoin import * MAX_TARGET = <API key> class Blockchain(util.PrintError): '''Manages blockchain headers and their verification''' def __init__(self, config, network): self.config = config self.network = network self.headers_url = "https://headers.electrum.org/blockchain_headers" self.local_height = 0 self.set_local_height() def height(self): return self.local_height def init(self): self.init_headers_file() self.set_local_height() self.print_error("%d blocks" % self.local_height) def verify_header(self, header, prev_header, bits, target): prev_hash = self.hash_header(prev_header) assert prev_hash == header.get('prev_block_hash'), "prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')) assert bits == header.get('bits'), "bits mismatch: %s vs %s" % (bits, header.get('bits')) _hash = self.hash_header(header) assert int('0x' + _hash, 16) <= target, "insufficient proof of work: %s vs target %s" % (int('0x' + _hash, 16), target) def verify_chain(self, chain): first_header = chain[0] prev_header = self.read_header(first_header.get('block_height') - 1) for header in chain: height = header.get('block_height') bits, target = self.get_target(height / 2016, chain) self.verify_header(header, prev_header, bits, target) prev_header = header def verify_chunk(self, index, data): num = len(data) / 80 prev_header = None if index != 0: prev_header = self.read_header(index*2016 - 1) bits, target = self.get_target(index) for i in range(num): raw_header = data[i*80:(i+1) * 80] header = self.deserialize_header(raw_header) self.verify_header(header, prev_header, bits, target) prev_header = header def serialize_header(self, res): s = int_to_hex(res.get('version'), 4) \ + rev_hex(res.get('prev_block_hash')) \ + rev_hex(res.get('merkle_root')) \ + int_to_hex(int(res.get('timestamp')), 4) \ + int_to_hex(int(res.get('bits')), 4) \ + int_to_hex(int(res.get('nonce')), 4) return s def deserialize_header(self, s): hex_to_int = lambda s: int('0x' + s[::-1].encode('hex'), 16) h = {} h['version'] = hex_to_int(s[0:4]) h['prev_block_hash'] = hash_encode(s[4:36]) h['merkle_root'] = hash_encode(s[36:68]) h['timestamp'] = hex_to_int(s[68:72]) h['bits'] = hex_to_int(s[72:76]) h['nonce'] = hex_to_int(s[76:80]) return h def hash_header(self, header): if header is None: return '0' * 64 return hash_encode(Hash(self.serialize_header(header).decode('hex'))) def path(self): return util.get_headers_path(self.config) def init_headers_file(self): filename = self.path() if os.path.exists(filename): return try: import urllib, socket socket.setdefaulttimeout(30) self.print_error("downloading ", self.headers_url) urllib.urlretrieve(self.headers_url, filename) self.print_error("done.") except Exception: self.print_error("download failed. creating file", filename) open(filename, 'wb+').close() def save_chunk(self, index, chunk): filename = self.path() f = open(filename, 'rb+') f.seek(index * 2016 * 80) h = f.write(chunk) f.close() self.set_local_height() def save_header(self, header): data = self.serialize_header(header).decode('hex') assert len(data) == 80 height = header.get('block_height') filename = self.path() f = open(filename, 'rb+') f.seek(height * 80) h = f.write(data) f.close() self.set_local_height() def set_local_height(self): name = self.path() if os.path.exists(name): h = os.path.getsize(name)/80 - 1 if self.local_height != h: self.local_height = h def read_header(self, block_height): name = self.path() if os.path.exists(name): f = open(name, 'rb') f.seek(block_height * 80) h = f.read(80) f.close() if len(h) == 80: h = self.deserialize_header(h) return h def get_target(self, index, chain=None): if index == 0: return 0x1d00ffff, MAX_TARGET first = self.read_header((index-1) * 2016) last = self.read_header(index*2016 - 1) if last is None: for h in chain: if h.get('block_height') == index*2016 - 1: last = h assert last is not None # bits to target bits = last.get('bits') bitsN = (bits >> 24) & 0xff assert bitsN >= 0x03 and bitsN <= 0x1d, "First part of bits should be in [0x03, 0x1d]" bitsBase = bits & 0xffffff assert bitsBase >= 0x8000 and bitsBase <= 0x7fffff, "Second part of bits should be in [0x8000, 0x7fffff]" target = bitsBase << (8 * (bitsN-3)) # new target nActualTimespan = last.get('timestamp') - first.get('timestamp') nTargetTimespan = 14 * 24 * 60 * 60 nActualTimespan = max(nActualTimespan, nTargetTimespan / 4) nActualTimespan = min(nActualTimespan, nTargetTimespan * 4) new_target = min(MAX_TARGET, (target*nActualTimespan) / nTargetTimespan) # convert new target to bits c = ("%064x" % new_target)[2:] while c[:2] == '00' and len(c) > 6: c = c[2:] bitsN, bitsBase = len(c) / 2, int('0x' + c[:6], 16) if bitsBase >= 0x800000: bitsN += 1 bitsBase >>= 8 new_bits = bitsN << 24 | bitsBase return new_bits, bitsBase << (8 * (bitsN-3)) def connect_header(self, chain, header): '''Builds a header chain until it connects. Returns True if it has successfully connected, False if verification failed, otherwise the height of the next header needed.''' chain.append(header) # Ordered by decreasing height previous_height = header['block_height'] - 1 previous_header = self.read_header(previous_height) # Missing header, request it if not previous_header: return previous_height # Does it connect to my chain? prev_hash = self.hash_header(previous_header) if prev_hash != header.get('prev_block_hash'): self.print_error("reorg") return previous_height # The chain is complete. Reverse to order by increasing height chain.reverse() try: self.verify_chain(chain) self.print_error("new height:", previous_height + len(chain)) for header in chain: self.save_header(header) return True except BaseException as e: self.print_error(str(e)) return False def connect_chunk(self, idx, hexdata): try: data = hexdata.decode('hex') self.verify_chunk(idx, data) self.print_error("validated chunk %d" % idx) self.save_chunk(idx, data) return idx + 1 except BaseException as e: self.print_error('verify_chunk failed', str(e)) return idx - 1
package com.google.gwt.webworker.client.messages; /** * Base interface for all DTOs that adds a type tag for routing messages. * * @author <a href="mailto:evidolob@codenvy.com">Evgen Vidolob</a> */ public interface Message { int NON_ROUTABLE_TYPE = -2; String TYPE_FIELD = "_type"; /** Every DTO needs to report a type for the purposes of routing messages on the client. */ int getType(); }
package io.liveoak.security.impl.interceptor; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import io.liveoak.common.DefaultReturnFields; import io.liveoak.common.security.AuthzConstants; import io.liveoak.common.security.AuthzDecision; import io.liveoak.common.security.<API key>; import io.liveoak.interceptor.extension.<API key>; import io.liveoak.security.extension.SecurityExtension; import io.liveoak.security.integration.<API key>; import io.liveoak.security.integration.<API key>; import io.liveoak.spi.RequestContext; import io.liveoak.spi.RequestType; import io.liveoak.spi.ResourcePath; import io.liveoak.spi.Services; import io.liveoak.spi.exceptions.<API key>; import io.liveoak.spi.state.ResourceState; import io.liveoak.testtools.<API key>; import io.liveoak.testtools.MockExtension; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class <API key> extends <API key> { private <API key> mockPolicy; private static MockAuthInterceptor mockAuthInterceptor = new MockAuthInterceptor(); @BeforeClass public static void loadExtensions() throws Exception { loadExtension("interceptor", new <API key>(), <API key>()); loadExtension("authz", new SecurityExtension()); loadExtension("mock-resource", new MockExtension(<API key>.class)); loadExtension("mock-policy", new MockExtension(<API key>.class)); loadExtension("<API key>", new <API key>(mockAuthInterceptor), JsonNodeFactory.instance.objectNode()); <API key>("authz", "authz", getSecurityConfig()); <API key>("mock-resource", "mock-resource", JsonNodeFactory.instance.objectNode()); <API key>("mock-policy", "mock-policy", JsonNodeFactory.instance.objectNode()); } private static ObjectNode <API key>() { ObjectNode config = JsonNodeFactory.instance.objectNode(); ObjectNode mockAuth = JsonNodeFactory.instance.objectNode() .put("interceptor-name", "mock-auth") .put("<API key>", "/testApp/mock-resource"); ObjectNode authz = JsonNodeFactory.instance.objectNode() .put("interceptor-name", "authz") .put("<API key>", "/testApp/mock-resource"); config.putArray("local").add(mockAuth).add(authz); return config; } private static ObjectNode getSecurityConfig() throws Exception { ObjectNode config = JsonNodeFactory.instance.objectNode(); ObjectNode policyConfig = JsonNodeFactory.instance.objectNode(); policyConfig.put("policyName", "Mock Policy"); policyConfig.put("<API key>", "/testApp/mock-policy"); config.putArray(<API key>.POLICIES_PROPERTY).add(policyConfig); return config; } @Before public void before() throws Exception { <API key> authzRootResource = (<API key>) system.service(Services.resource("testApp", "authz")); this.mockPolicy = (<API key>) system.service(Services.resource("testApp", "mock-policy")); } @Test public void testAuthzInbound() throws Exception { mockPolicy.setWorker(new <API key>.AuthzWorker() { @Override public AuthzDecision isAuthorized(RequestContext ctx) { RequestContext ctxToAuthorize = (RequestContext) ctx.requestAttributes().getAttribute(AuthzConstants.<API key>); if (ctxToAuthorize == null || !ctxToAuthorize.securityContext().isAuthenticated()) { return AuthzDecision.REJECT; } else { return AuthzDecision.ACCEPT; } } }); mockAuthInterceptor.setSubject("john"); RequestContext.Builder reqContext = new RequestContext.Builder() .requestType(RequestType.READ) .resourcePath(new ResourcePath("/testApp/mock-resource")) .securityContext(new <API key>()); ResourceState fullState = client.read(reqContext.returnFields(new DefaultReturnFields("*(*(*))")), "/testApp/mock-resource"); Assert.assertEquals(3, fullState.members().size()); ResourceState todos = fullState.members().get(0); Assert.assertEquals("todos", todos.id()); Assert.assertEquals("someValue", todos.getProperty("<API key>")); Assert.assertEquals(3, todos.members().size()); ResourceState todo3 = todos.members().get(2); Assert.assertEquals("todo3", todo3.id()); Assert.assertEquals(0, todo3.members().size()); Assert.assertEquals("secret todo", todo3.getProperty("title")); Assert.assertEquals("bob", todo3.getProperty("user")); mockAuthInterceptor.setSubject(null); try { client.read(reqContext, "/testApp/mock-resource"); Assert.fail("Not expected to reach this"); } catch (<API key> e) { } } @Test public void testAuthzOutbound() throws Exception { mockPolicy.setWorker(new <API key>.AuthzWorker() { @Override public AuthzDecision isAuthorized(RequestContext ctx) { ResourceState responseState = (ResourceState) ctx.requestAttributes().getAttribute(AuthzConstants.<API key>); if (responseState == null) { return AuthzDecision.ACCEPT; } else { String title = (String) responseState.getProperty("title"); if (title != null && title.startsWith("secret")) { return AuthzDecision.REJECT; } else { return AuthzDecision.ACCEPT; } } } }); mockAuthInterceptor.setSubject("john"); RequestContext.Builder reqContext = new RequestContext.Builder() .requestType(RequestType.READ) .resourcePath(new ResourcePath("/testApp/mock-resource")) .securityContext(new <API key>()); ResourceState state1 = client.read(reqContext.returnFields(new DefaultReturnFields("*")), "/testApp/mock-resource"); ResourceState state2 = client.read(reqContext.returnFields(new DefaultReturnFields("*(*)")), "/testApp/mock-resource"); ResourceState state3 = client.read(reqContext.returnFields(new DefaultReturnFields("*(*(*))")), "/testApp/mock-resource"); Assert.assertEquals(3, state1.members().size()); ResourceState todos = state1.members().get(0); Assert.assertEquals("todos", todos.id()); Assert.assertEquals("chat", state1.members().get(1).id()); Assert.assertEquals("secured", state1.members().get(2).id()); // No any properties or members as it's not expanded Assert.assertEquals(0, todos.getPropertyNames().size()); Assert.assertEquals(0, todos.members().size()); Assert.assertEquals(2, state2.members().size()); todos = state2.members().get(0); Assert.assertEquals("todos", todos.id()); Assert.assertEquals(3, todos.members().size()); Assert.assertEquals("todo1", todos.members().get(0).id()); Assert.assertEquals("todo2", todos.members().get(1).id()); Assert.assertEquals("todo3", todos.members().get(2).id()); // No any properties as it's not expanded Assert.assertEquals(0, todos.members().get(0).getPropertyNames().size()); Assert.assertEquals(2, state3.members().size()); todos = state3.members().get(0); Assert.assertEquals("todos", todos.id()); Assert.assertEquals(2, todos.members().size()); Assert.assertEquals("todo1", todos.members().get(0).id()); Assert.assertEquals("todo2", todos.members().get(1).id()); // Expanded, so properties of todo are here Assert.assertEquals(2, todos.members().get(0).getPropertyNames().size()); } }
package org.jboss.windup.reporting.service; import org.apache.tinkerpop.gremlin.structure.Vertex; /** * @author <a href="mailto:jesse.sightler@gmail.com">Jesse Sightler</a> */ public interface <API key> { void accumulate(Vertex effortReportVertex); }
package org.openhealthtools.mdht.uml.cda.ui.properties; import org.eclipse.core.commands.operations.IUndoableOperation; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.<API key>; import org.eclipse.emf.transaction.util.TransactionUtil; import org.eclipse.emf.workspace.<API key>; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.views.properties.tabbed.<API key>; import org.eclipse.ui.views.properties.tabbed.<API key>; import org.eclipse.uml2.uml.Generalization; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.uml2.uml.Stereotype; import org.openhealthtools.mdht.uml.cda.core.profile.ConformsTo; import org.openhealthtools.mdht.uml.cda.core.util.CDAProfileUtil; import org.openhealthtools.mdht.uml.cda.core.util.<API key>; /** * The properties section for Generalization. * * $Id: $ */ public class <API key> extends ValidationSection { private Button isParentIdRequired; private boolean <API key> = false; @Override protected Stereotype <API key>() { String qname = <API key>.CDA_PROFILE_NAME + NamedElement.SEPARATOR + <API key>.CONFORMS_TO; Stereotype stereotype = modelElement.<API key>(qname); return stereotype; } @Override public void setInput(IWorkbenchPart part, ISelection selection) { super.setInput(part, selection); EObject element = getEObject(); Assert.isTrue(element instanceof Generalization); this.modelElement = (Generalization) element; } @Override protected void modifyFields() { super.modifyFields(); if (!(<API key>)) { return; } try { <API key> editingDomain = TransactionUtil.getEditingDomain(modelElement); IUndoableOperation operation = new <API key>(editingDomain, "temp") { @Override protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) { Stereotype <API key> = CDAProfileUtil.<API key>( modelElement, <API key>.CONFORMS_TO); if (<API key> == null) { <API key> = CDAProfileUtil.applyCDAStereotype( modelElement, <API key>.CONFORMS_TO); } ConformsTo conformsTo = CDAProfileUtil.getConformsTo((Generalization) modelElement); if (conformsTo != null) { if (<API key>) { <API key> = false; this.setLabel("Set RequiresParentId"); conformsTo.setRequiresParentId(isParentIdRequired.getSelection()); } else { return Status.CANCEL_STATUS; } } else { return Status.CANCEL_STATUS; } return Status.OK_STATUS; } }; execute(operation); } catch (Exception e) { throw new RuntimeException(e.getCause()); } } @Override public void createControls(final Composite parent, final <API key> <API key>) { super.createControls(parent, <API key>); Composite composite = getWidgetFactory().createGroup(parent, "Generalization"); FormLayout layout = new FormLayout(); layout.marginWidth = <API key>.HSPACE + 2; layout.marginHeight = <API key>.VSPACE; layout.spacing = <API key>.VMARGIN + 1; composite.setLayout(layout); FormData data = null; <API key>(composite, 0, 1); // Parent required checkbox isParentIdRequired = getWidgetFactory().createButton(composite, "Requires Parent Template ID", SWT.CHECK); data = new FormData(); data.left = new FormAttachment(ruleIdText, <API key>.HSPACE); data.top = new FormAttachment(ruleIdText, 0, SWT.CENTER); isParentIdRequired.setLayoutData(data); isParentIdRequired.<API key>(new SelectionListener() { public void <API key>(SelectionEvent e) { <API key> = true; modifyFields(); } public void widgetSelected(SelectionEvent e) { <API key> = true; modifyFields(); } }); <API key>(composite); data = new FormData(); data.right = new FormAttachment(100, 0); data.top = new FormAttachment(isParentIdRequired, 0, SWT.CENTER); <API key>.setLayoutData(data); } @Override public void refresh() { super.refresh(); ConformsTo conformsTo = CDAProfileUtil.getConformsTo((Generalization) modelElement); if (conformsTo != null) { isParentIdRequired.setSelection(conformsTo.isRequiresParentId()); } else { isParentIdRequired.setSelection(false); } if (isReadOnly()) { isParentIdRequired.setEnabled(false); <API key>.setEnabled(false); } else { isParentIdRequired.setEnabled(true); <API key>.setEnabled(conformsTo != null); } } }
package org.python.pydev.debug.model.remote; import org.python.pydev.debug.model.AbstractDebugTarget; /** * ChangeVariable network command. * * ChangeVariable gets the value of the variable from network as XML. */ public class <API key> extends <API key> { String locator; boolean isError = false; int responseCode; String payload; String expression; public <API key>(AbstractDebugTarget debugger, String locator, String expression) { super(debugger); this.locator = locator; this.expression = expression; } @Override public String getOutgoing() { return makeCommand(getCommandId(), sequence, locator + "\t" + expression); } @Override public boolean needResponse() { return false; } protected int getCommandId() { return CMD_CHANGE_VARIABLE; } }
package org.bndtools.utils.swt; import java.beans.<API key>; import java.beans.<API key>; import java.util.concurrent.<API key>; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; public class FilterPanelPart { private static final String PROP_FILTER = "filter"; private static final long SEARCH_DELAY = 1000; private final <API key> scheduler; private String filter; private Composite panel; private Text txtFilter; private final <API key> propSupport = new <API key>(this); private final Lock scheduledFilterLock = new ReentrantLock(); private final Runnable updateFilterTask = new Runnable() { @Override public void run() { Display display = panel.getDisplay(); Runnable update = new Runnable() { @Override public void run() { String newFilter = txtFilter.getText(); setFilter(newFilter); } }; if (display.getThread() == Thread.currentThread()) update.run(); else display.asyncExec(update); } }; private ScheduledFuture<?> <API key> = null; public FilterPanelPart(<API key> scheduler) { this.scheduler = scheduler; } public Control createControl(Composite parent) { return createControl(parent, 0, 0); } public Control createControl(Composite parent, int marginWidth, int marginHeight) { // CREATE CONTROLS panel = new Composite(parent, SWT.NONE); panel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); txtFilter = new Text(panel, SWT.SEARCH | SWT.ICON_SEARCH | SWT.ICON_CANCEL); txtFilter.setMessage("Enter search string"); // INITIAL PROPERTIES if (filter != null) txtFilter.setText(filter); // LAYOUT GridLayout layout = new GridLayout(2, false); layout.marginHeight = marginHeight; layout.marginWidth = marginWidth; panel.setLayout(layout); txtFilter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); // LISTENERS txtFilter.<API key>(new SelectionAdapter() { @Override public void <API key>(SelectionEvent ev) { try { scheduledFilterLock.lock(); if (<API key> != null) <API key>.cancel(true); } finally { scheduledFilterLock.unlock(); } String newFilter = (ev.detail == SWT.CANCEL) ? "" : txtFilter.getText(); setFilter(newFilter); } }); txtFilter.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent ev) { try { scheduledFilterLock.lock(); if (<API key> != null) <API key>.cancel(true); <API key> = scheduler.schedule(updateFilterTask, SEARCH_DELAY, TimeUnit.MILLISECONDS); } finally { scheduledFilterLock.unlock(); } } }); return panel; } public Text getFilterControl() { return txtFilter; } public String getFilter() { return filter; } public void setFilter(String filter) { String old = this.filter; this.filter = filter; propSupport.firePropertyChange(PROP_FILTER, old, filter); } public void setFocus() { if (txtFilter != null && !txtFilter.isDisposed()) txtFilter.setFocus(); } public void <API key>(<API key> listener) { propSupport.<API key>(PROP_FILTER, listener); } public void <API key>(<API key> listener) { propSupport.<API key>(PROP_FILTER, listener); } }
package org.eclipse.smarthome.config.xml; import java.net.URI; import java.util.Collection; import java.util.Locale; import org.eclipse.smarthome.config.core.ConfigDescription; import org.eclipse.smarthome.config.core.<API key>; import org.eclipse.smarthome.config.core.i18n.<API key>; import org.osgi.framework.Bundle; public abstract class <API key> extends <API key><URI, ConfigDescription> implements <API key> { @Override public synchronized Collection<ConfigDescription> <API key>(Locale locale) { return getAll(locale); } @Override public synchronized ConfigDescription <API key>(URI uri, Locale locale) { return get(uri, locale); } @Override protected ConfigDescription localize(Bundle bundle, ConfigDescription configDescription, Locale locale) { <API key> <API key> = <API key>(); if (<API key> == null) { return null; } return <API key>.<API key>(bundle, configDescription, locale); } protected abstract <API key> <API key>(); }
package org.openhealthtools.mdht.uml.cda.ihe.tests; import java.util.Map; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.ecore.EObject; import org.junit.Test; import org.openhealthtools.mdht.uml.cda.ihe.BreastSection; import org.openhealthtools.mdht.uml.cda.ihe.IHEFactory; import org.openhealthtools.mdht.uml.cda.ihe.operations.<API key>; import org.openhealthtools.mdht.uml.cda.operations.CDAValidationTest; /** * <!-- begin-user-doc --> * A static utility class that provides operations related to '<em><b>Breast Section</b></em>' model objects. * <!-- end-user-doc --> * * <p> * The following operations are supported: * <ul> * <li>{@link org.openhealthtools.mdht.uml.cda.ihe.BreastSection#<API key>(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Breast Section Template Id</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.ihe.BreastSection#<API key>(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate Breast Section Code</em>}</li> * </ul> * </p> * * @generated */ public class BreastSectionTest extends CDAValidationTest { /** * * @generated */ @Test public void <API key>() { OperationsTestCase<BreastSection> <API key> = new OperationsTestCase<BreastSection>( "<API key>", operationsForOCL.getOCLValue("<API key>"), objectFactory) { @Override protected void updateToFail(BreastSection target) { } @Override protected void updateToPass(BreastSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return <API key>.<API key>( (BreastSection) objectToTest, diagnostician, map); } }; <API key>.doValidationTest(); } /** * * @generated */ @Test public void <API key>() { OperationsTestCase<BreastSection> <API key> = new OperationsTestCase<BreastSection>( "<API key>", operationsForOCL.getOCLValue("<API key>"), objectFactory) { @Override protected void updateToFail(BreastSection target) { } @Override protected void updateToPass(BreastSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return <API key>.<API key>( (BreastSection) objectToTest, diagnostician, map); } }; <API key>.doValidationTest(); } /** * * @generated */ private static class OperationsForOCL extends <API key> { public String getOCLValue(String fieldName) { String oclValue = null; try { oclValue = (String) this.getClass().getSuperclass().getDeclaredField(fieldName).get(this); } catch (Exception e) { oclValue = "NO OCL FOUND FOR PROPERTY " + fieldName; } return oclValue; } } /** * * @generated */ private static class ObjectFactory implements TestObjectFactory<BreastSection> { public BreastSection create() { return IHEFactory.eINSTANCE.createBreastSection(); } } /** * * @generated */ private static OperationsForOCL operationsForOCL = new OperationsForOCL(); /** * * @generated */ private static ObjectFactory objectFactory = new ObjectFactory(); /** * Tests Operations Constructor for 100% coverage * @generated */ private static class <API key> extends <API key> { }; /** * Tests Operations Constructor for 100% coverage * @generated */ @Test public void testConstructor() { @SuppressWarnings("unused") <API key> <API key> = new <API key>(); } // testConstructor /** * * @generated */ @Override protected EObject getObjectToTest() { return null; } } // <API key>
package org.eclipse.che.ide.ext.java.jdt.internal.text.correction; public class NameMatcher { /** * Returns a similarity value of the two names. * The range of is from 0 to 256. no similarity is negative * * @param name1 * the first name * @param name2 * the second name * @return <code>true</code> is returned if the names are similar */ public static boolean isSimilarName(String name1, String name2) { return getSimilarity(name1, name2) >= 0; } /** * Returns a similarity value of the two names. * The range of is from 0 to 256. no similarity is negative * * @param name1 * the first name * @param name2 * the second name * @return the similarity valuer */ public static int getSimilarity(String name1, String name2) { if (name1.length() > name2.length()) { String tmp = name1; name1 = name2; name2 = tmp; } int name1len = name1.length(); int name2len = name2.length(); int nMatched = 0; int i = 0; while (i < name1len && isSimilarChar(name1.charAt(i), name2.charAt(i))) { i++; nMatched++; } int k = name1len; int diff = name2len - name1len; while (k > i && isSimilarChar(name1.charAt(k - 1), name2.charAt(k + diff - 1))) { k nMatched++; } if (nMatched == name2len) { return 200; } if (name2len - nMatched > nMatched) { return -1; } int tolerance = name2len / 4 + 1; return (tolerance - (k - i)) * 256 / tolerance; } private static boolean isSimilarChar(char ch1, char ch2) { return Character.toLowerCase(ch1) == Character.toLowerCase(ch2); } }
/* Fig. 8.15: fig08_15.c Using sprintf */ #include <stdio.h> int main( void ) { char s[ 80 ]; /* create char array */ int x; /* x value to be input */ double y; /* y value to be input */ printf( "Enter an integer and a double:\n" ); scanf( "%d%lf", &x, &y ); sprintf( s, "integer:%6d\ndouble:%8.2f", x, y ); printf( "%s\n%s\n", "The formatted output stored in array s is:", s ); return 0; /* indicates successful termination */ } /* end main */
<?php class <API key> extends <API key> { const CRON_STRING_PATH = 'crontab/jobs/<API key>/schedule/cron_expr'; const <API key> = 'paypal/fetch_reports/schedule'; /** * Cron settings after save * @return void */ protected function _afterSave() { $cronExprString = ''; $time = explode(',', Mage::getModel('core/config_data')->load('paypal/fetch_reports/time', 'path')->getValue()); if (Mage::getModel('core/config_data')->load('paypal/fetch_reports/active', 'path')->getValue()) { $interval = Mage::getModel('core/config_data')->load(self::<API key>, 'path')->getValue(); $cronExprString = "{$time[1]} {$time[0]} */{$interval} * *"; } Mage::getModel('core/config_data') ->load(self::CRON_STRING_PATH, 'path') ->setValue($cronExprString) ->setPath(self::CRON_STRING_PATH) ->save(); return parent::_afterSave(); } }
#include "qgsmapcanvas.h" #include "qgsmaplayer.h" #include "qgsproject.h" #include "<API key>.h" #include "<API key>.h" #include "qgsmaptopixel.h" #include <QPainter> #include <QPaintEvent> #include <QResizeEvent> #include <QMouseEvent> #include "qgslogger.h" #include <limits> <API key>::<API key>( QWidget *parent, QgsMapCanvas *mapCanvas ) : QWidget( parent ) , mMapCanvas( mapCanvas ) { <API key>( true ); setObjectName( QStringLiteral( "theOverviewCanvas" ) ); mPanningWidget = new QgsPanningWidget( this ); mSettings.setTransformContext( mMapCanvas->mapSettings().transformContext() ); mSettings.setFlag( QgsMapSettings::DrawLabeling, false ); connect( mMapCanvas, &QgsMapCanvas::extentsChanged, this, &<API key>::drawExtentRect ); connect( mMapCanvas, &QgsMapCanvas::<API key>, this, &<API key>::<API key> ); connect( mMapCanvas, &QgsMapCanvas::<API key>, this, &<API key>::<API key> ); } void <API key>::resizeEvent( QResizeEvent *e ) { mPixmap = QPixmap(); mSettings.setOutputSize( e->size() ); updateFullExtent(); refresh(); QWidget::resizeEvent( e ); } void <API key>::showEvent( QShowEvent *e ) { refresh(); QWidget::showEvent( e ); } void <API key>::paintEvent( QPaintEvent *pe ) { if ( !mPixmap.isNull() ) { QPainter paint( this ); paint.drawPixmap( pe->rect().topLeft(), mPixmap, pe->rect() ); } } void <API key>::drawExtentRect() { if ( !mMapCanvas ) return; const QgsRectangle &extent = mMapCanvas->extent(); // show only when valid extent is set if ( extent.isEmpty() || mSettings.visibleExtent().isEmpty() ) { mPanningWidget->hide(); return; } const QPolygonF &vPoly = mMapCanvas->mapSettings().visiblePolygon(); const QgsMapToPixel &cXf = mSettings.mapToPixel(); QVector< QPoint > pts; pts.push_back( cXf.transform( QgsPointXY( vPoly[0] ) ).toQPointF().toPoint() ); pts.push_back( cXf.transform( QgsPointXY( vPoly[1] ) ).toQPointF().toPoint() ); pts.push_back( cXf.transform( QgsPointXY( vPoly[2] ) ).toQPointF().toPoint() ); pts.push_back( cXf.transform( QgsPointXY( vPoly[3] ) ).toQPointF().toPoint() ); mPanningWidget->setPolygon( QPolygon( pts ) ); mPanningWidget->show(); // show if hidden } void <API key>::mousePressEvent( QMouseEvent *e ) { // if (mPanningWidget->isHidden()) // return; // set offset in panning widget if inside it // for better experience with panning :) if ( mPanningWidget->geometry().contains( e->pos() ) ) { <API key> = e->pos() - mPanningWidget->pos(); } else { // use center of the panning widget if outside QSize s = mPanningWidget->size(); <API key> = QPoint( s.width() / 2, s.height() / 2 ); } updatePanningWidget( e->pos() ); } void <API key>::mouseReleaseEvent( QMouseEvent *e ) { // if (mPanningWidget->isHidden()) // return; if ( e->button() == Qt::LeftButton ) { // set new extent const QgsMapToPixel &cXf = mSettings.mapToPixel(); QRect rect = mPanningWidget->geometry(); QgsPointXY center = cXf.toMapCoordinates( rect.center() ); mMapCanvas->setCenter( center ); mMapCanvas->refresh(); } } void <API key>::mouseMoveEvent( QMouseEvent *e ) { // move with panning widget if tracking cursor if ( ( e->buttons() & Qt::LeftButton ) == Qt::LeftButton ) { updatePanningWidget( e->pos() ); } } void <API key>::updatePanningWidget( QPoint pos ) { // if (mPanningWidget->isHidden()) // return; mPanningWidget->move( pos.x() - <API key>.x(), pos.y() - <API key>.y() ); } void <API key>::refresh() { if ( !isVisible() ) return; updateFullExtent(); if ( !mSettings.hasValidSettings() ) { mPixmap = QPixmap(); update(); return; // makes no sense to render anything } if ( mJob ) { QgsDebugMsg( QStringLiteral( "oveview - canceling old" ) ); mJob->cancel(); QgsDebugMsg( QStringLiteral( "oveview - deleting old" ) ); delete mJob; // get rid of previous job (if any) } QgsDebugMsg( QStringLiteral( "oveview - starting new" ) ); // TODO: setup overview mode mJob = new <API key>( mSettings ); connect( mJob, &QgsMapRendererJob::finished, this, &<API key>::<API key> ); mJob->start(); setBackgroundColor( mMapCanvas->mapSettings().backgroundColor() ); // schedule repaint update(); // update panning widget drawExtentRect(); } void <API key>::<API key>() { QgsDebugMsg( QStringLiteral( "overview - finished" ) ); mPixmap = QPixmap::fromImage( mJob->renderedImage() ); delete mJob; mJob = nullptr; // schedule repaint update(); } void <API key>::<API key>( bool deferred ) { if ( !deferred ) refresh(); } void <API key>::setBackgroundColor( const QColor &color ) { mSettings.setBackgroundColor( color ); // set erase color QPalette palette; palette.setColor( backgroundRole(), color ); setPalette( palette ); } void <API key>::setLayers( const QList<QgsMapLayer *> &layers ) { Q_FOREACH ( QgsMapLayer *ml, mSettings.layers() ) { disconnect( ml, &QgsMapLayer::repaintRequested, this, &<API key>::<API key> ); } mSettings.setLayers( layers ); Q_FOREACH ( QgsMapLayer *ml, mSettings.layers() ) { connect( ml, &QgsMapLayer::repaintRequested, this, &<API key>::<API key> ); } updateFullExtent(); refresh(); } void <API key>::updateFullExtent() { QgsRectangle rect; if ( mSettings.hasValidSettings() ) rect = mSettings.fullExtent(); else rect = mMapCanvas->fullExtent(); // expand a bit to keep features on margin rect.scale( 1.1 ); mSettings.setExtent( rect ); drawExtentRect(); } void <API key>::<API key>() { mSettings.setDestinationCrs( mMapCanvas->mapSettings().destinationCrs() ); } void <API key>::<API key>() { mSettings.setTransformContext( mMapCanvas->mapSettings().transformContext() ); } QList<QgsMapLayer *> <API key>::layers() const { return mSettings.layers(); } @cond PRIVATE QgsPanningWidget::QgsPanningWidget( QWidget *parent ) : QWidget( parent ) { setObjectName( QStringLiteral( "panningWidget" ) ); setMinimumSize( 5, 5 ); setAttribute( Qt::<API key> ); } void QgsPanningWidget::setPolygon( const QPolygon &p ) { if ( p == mPoly ) return; mPoly = p; //ensure polygon is closed if ( mPoly.at( 0 ) != mPoly.at( mPoly.length() - 1 ) ) mPoly.append( mPoly.at( 0 ) ); setGeometry( p.boundingRect() ); update(); } void QgsPanningWidget::paintEvent( QPaintEvent *pe ) { Q_UNUSED( pe ); QPainter p; p.begin( this ); p.setPen( Qt::red ); QPolygonF t = mPoly.translated( -mPoly.boundingRect().left(), -mPoly.boundingRect().top() ); // drawPolygon causes issues on windows - corners of path may be missing resulting in triangles being drawn // instead of rectangles! (Same cause as #13343) QPainterPath path; path.addPolygon( t ); p.drawPath( path ); p.end(); } @endcond
<?php error_reporting(E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR); require('./roots.php'); require($root_path.'include/<API key>.php'); define('LANG_FILE','nursing.php'); $local_user='ck_pflege_user'; require_once($root_path.'include/<API key>.php'); ?> <?php html_rtl($lang); ?> <?php echo setCharSet(); ?> <title></title> </head><center> <body> <p> &nbsp; <p> &nbsp; <p> <table border=0> <tr> <td><img <?php echo createMascot($root_path,'mascot1_r.gif') ?>></td> <td><font size=3 face="verdana,arial" color="#990000"><b> <?php echo str_replace('~str~',strtoupper($ward_id),$LDWardNoClose); ?></b> </font> </td> </tr> </table> <p> <font size=2 face="verdana,arial" color="#990000"> <a href="<API key>.php<?php echo URL_APPEND."&mode=show&ward_id=$ward_id&ward_nr=$ward_nr"; ?>"> <?php echo $LDBackToWardProfile.'... '.$LDClkHere ?></a> <p> <a href="nursing-station.php<?php echo URL_APPEND."&edit=1&ward_id=$ward_id&ward_nr=$ward_nr&retpath=ward_mng"; ?>"> <?php echo $LDShowWardOccupancy.'... '.$LDClkHere ?></a> </center> </body> </html>
#include <linux/kernel.h> #include <linux/fs.h> #include <linux/gfp.h> #include <linux/mm.h> #include <linux/export.h> #include <linux/blkdev.h> #include <linux/backing-dev.h> #include <linux/<API key>.h> #include <linux/pagevec.h> #include <linux/pagemap.h> #include <linux/syscalls.h> #include <linux/file.h> /* * Initialise a struct file's readahead state. Assumes that the caller has * memset *ra to zero. */ void file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping) { ra->ra_pages = mapping->backing_dev_info->ra_pages; ra->prev_pos = -1; } EXPORT_SYMBOL_GPL(file_ra_state_init); #define list_to_page(head) (list_entry((head)->prev, struct page, lru)) /* * see if a page needs releasing upon read_cache_pages() failure * - the caller of read_cache_pages() may have set PG_private or PG_fscache * before calling, such as the NFS fs marking pages that are cached locally * on disk, thus we need to give the fs a chance to clean up in the event of * an error */ static void <API key>(struct address_space *mapping, struct page *page) { if (page_has_private(page)) { if (!trylock_page(page)) BUG(); page->mapping = mapping; do_invalidatepage(page, 0); page->mapping = NULL; unlock_page(page); } page_cache_release(page); } /* * release a list of pages, invalidating them first if need be */ static void <API key>(struct address_space *mapping, struct list_head *pages) { struct page *victim; while (!list_empty(pages)) { victim = list_to_page(pages); list_del(&victim->lru); <API key>(mapping, victim); } } /** * read_cache_pages - populate an address space with some pages & start reads against them * @mapping: the address_space * @pages: The address of a list_head which contains the target pages. These * pages have their ->index populated and are otherwise uninitialised. * @filler: callback routine for filling a single page. * @data: private data for the callback routine. * * Hides the details of the LRU cache etc from the filesystems. */ int read_cache_pages(struct address_space *mapping, struct list_head *pages, int (*filler)(void *, struct page *), void *data) { struct page *page; int ret = 0; while (!list_empty(pages)) { page = list_to_page(pages); list_del(&page->lru); if (<API key>(page, mapping, page->index, GFP_KERNEL)) { <API key>(mapping, page); continue; } page_cache_release(page); ret = filler(data, page); if (unlikely(ret)) { <API key>(mapping, pages); break; } <API key>(PAGE_CACHE_SIZE); } return ret; } EXPORT_SYMBOL(read_cache_pages); static int read_pages(struct address_space *mapping, struct file *filp, struct list_head *pages, unsigned nr_pages) { struct blk_plug plug; unsigned page_idx; int ret; blk_start_plug(&plug); if (mapping->a_ops->readpages) { ret = mapping->a_ops->readpages(filp, mapping, pages, nr_pages); /* Clean up the remaining pages */ put_pages_list(pages); goto out; } for (page_idx = 0; page_idx < nr_pages; page_idx++) { struct page *page = list_to_page(pages); list_del(&page->lru); if (!<API key>(page, mapping, page->index, GFP_KERNEL)) { mapping->a_ops->readpage(filp, page); } page_cache_release(page); } ret = 0; out: blk_finish_plug(&plug); return ret; } /* * <API key>() actually reads a chunk of disk. It allocates all * the pages first, then submits them all for I/O. This avoids the very bad * behaviour which would occur if page allocations are causing VM writeback. * We really don't want to intermingle reads and writes like that. * * Returns the number of pages requested, or the maximum amount of I/O allowed. */ static int <API key>(struct address_space *mapping, struct file *filp, pgoff_t offset, unsigned long nr_to_read, unsigned long lookahead_size) { struct inode *inode = mapping->host; struct page *page; unsigned long end_index; /* The last page we want to read */ LIST_HEAD(page_pool); int page_idx; int ret = 0; loff_t isize = i_size_read(inode); if (isize == 0) goto out; end_index = ((isize - 1) >> PAGE_CACHE_SHIFT); /* * Preallocate as many pages as we will need. */ for (page_idx = 0; page_idx < nr_to_read; page_idx++) { pgoff_t page_offset = offset + page_idx; if (page_offset > end_index) break; rcu_read_lock(); page = radix_tree_lookup(&mapping->page_tree, page_offset); rcu_read_unlock(); if (page) continue; page = <API key>(mapping); if (!page) break; page->index = page_offset; page->flags |= (1L << PG_readahead); list_add(&page->lru, &page_pool); if (page_idx == nr_to_read - lookahead_size) SetPageReadahead(page); ret++; } /* * Now start the IO. We ignore I/O errors - if the page is not * uptodate then the caller will launch readpage again, and * will then handle the error. */ if (ret) read_pages(mapping, filp, &page_pool, ret); BUG_ON(!list_empty(&page_pool)); out: return ret; } /* * Chunk the readahead into 2 megabyte units, so that we don't pin too much * memory at once. */ int <API key>(struct address_space *mapping, struct file *filp, pgoff_t offset, unsigned long nr_to_read) { int ret = 0; if (unlikely(!mapping->a_ops->readpage && !mapping->a_ops->readpages)) return -EINVAL; nr_to_read = max_sane_readahead(nr_to_read); while (nr_to_read) { int err; unsigned long this_chunk = (2 * 1024 * 1024) / PAGE_CACHE_SIZE; if (this_chunk > nr_to_read) this_chunk = nr_to_read; err = <API key>(mapping, filp, offset, this_chunk, 0); if (err < 0) { ret = err; break; } ret += err; offset += this_chunk; nr_to_read -= this_chunk; } return ret; } /* * Given a desired number of PAGE_CACHE_SIZE readahead pages, return a * sensible upper limit. */ unsigned long max_sane_readahead(unsigned long nr) { return min(nr, (node_page_state(numa_node_id(), NR_INACTIVE_FILE) + node_page_state(numa_node_id(), NR_FREE_PAGES)) / 2); } /* * Submit IO for the read-ahead request in file_ra_state. */ unsigned long ra_submit(struct file_ra_state *ra, struct address_space *mapping, struct file *filp) { int actual; actual = <API key>(mapping, filp, ra->start, ra->size, ra->async_size); return actual; } /* * Set the initial window size, round to next power of 2 and square * for small size, x 4 for medium, and x 2 for large * for 128k (32 page) max ra * 1-8 page = 32k initial, > 8 page = 128k initial */ static unsigned long get_init_ra_size(unsigned long size, unsigned long max) { unsigned long newsize = roundup_pow_of_two(size); if (newsize <= max / 32) newsize = newsize * 4; else if (newsize <= max / 4) newsize = newsize * 2; else newsize = max; return newsize; } /* * Get the previous window size, ramp it up, and * return it as the new window size. */ static unsigned long get_next_ra_size(struct file_ra_state *ra, unsigned long max) { unsigned long cur = ra->size; unsigned long newsize; if (cur < max / 16) newsize = 4 * cur; else newsize = 2 * cur; return min(newsize, max); } /* * Count contiguously cached pages from @offset-1 to @offset-@max, * this count is a conservative estimation of * - length of the sequential read sequence, or * - thrashing threshold in memory tight systems */ static pgoff_t count_history_pages(struct address_space *mapping, struct file_ra_state *ra, pgoff_t offset, unsigned long max) { pgoff_t head; rcu_read_lock(); head = <API key>(&mapping->page_tree, offset - 1, max); rcu_read_unlock(); return offset - 1 - head; } /* * page cache context based read-ahead */ static int <API key>(struct address_space *mapping, struct file_ra_state *ra, pgoff_t offset, unsigned long req_size, unsigned long max) { pgoff_t size; size = count_history_pages(mapping, ra, offset, max); /* * not enough history pages: * it could be a random read */ if (size <= req_size) return 0; /* * starts from beginning of file: * it is a strong indication of long-run stream (or whole-file-read) */ if (size >= offset) size *= 2; ra->start = offset; ra->size = min(size + req_size, max); ra->async_size = 1; return 1; } /* * A minimal readahead algorithm for trivial sequential/random reads. */ static unsigned long ondemand_readahead(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, bool <API key>, pgoff_t offset, unsigned long req_size) { unsigned long max = max_sane_readahead(ra->ra_pages); /* * start of file */ if (!offset) goto initial_readahead; /* * It's the expected callback offset, assume sequential access. * Ramp up sizes, and push forward the readahead window. */ if ((offset == (ra->start + ra->size - ra->async_size) || offset == (ra->start + ra->size))) { ra->start += ra->size; ra->size = get_next_ra_size(ra, max); ra->async_size = ra->size; goto readit; } /* * Hit a marked page without valid readahead state. * E.g. interleaved reads. * Query the pagecache for async_size, which normally equals to * readahead size. Ramp it up and use it as the new readahead size. */ if (<API key>) { pgoff_t start; rcu_read_lock(); start = <API key>(&mapping->page_tree, offset+1,max); rcu_read_unlock(); if (!start || start - offset > max) return 0; ra->start = start; ra->size = start - offset; /* old async_size */ ra->size += req_size; ra->size = get_next_ra_size(ra, max); ra->async_size = ra->size; goto readit; } /* * oversize read */ if (req_size > max) goto initial_readahead; /* * sequential cache miss */ if (offset - (ra->prev_pos >> PAGE_CACHE_SHIFT) <= 1UL) goto initial_readahead; /* * Query the page cache and look for the traces(cached history pages) * that a sequential stream would leave behind. */ if (<API key>(mapping, ra, offset, req_size, max)) goto readit; /* * standalone, small random read * Read as is, and do not pollute the readahead state. */ return <API key>(mapping, filp, offset, req_size, 0); initial_readahead: ra->start = offset; ra->size = get_init_ra_size(req_size, max); ra->async_size = ra->size > req_size ? ra->size - req_size : ra->size; readit: /* * Will this read hit the readahead marker made by itself? * If so, trigger the readahead marker hit now, and merge * the resulted next readahead window into the current one. */ if (offset == ra->start && ra->size == ra->async_size) { ra->async_size = get_next_ra_size(ra, max); ra->size += ra->async_size; } return ra_submit(ra, mapping, filp); } /** * <API key> - generic file readahead * @mapping: address_space which holds the pagecache and I/O vectors * @ra: file_ra_state which holds the readahead state * @filp: passed on to ->readpage() and ->readpages() * @offset: start offset into @mapping, in pagecache page-sized units * @req_size: hint: total size of the read which the caller is performing in * pagecache pages * * <API key>() should be called when a cache miss happened: * it will submit the read. The readahead logic may decide to piggyback more * pages onto the read request if access patterns suggest it will improve * performance. */ void <API key>(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, pgoff_t offset, unsigned long req_size) { /* no read-ahead */ if (!ra->ra_pages) return; /* be dumb */ if (filp && (filp->f_mode & FMODE_RANDOM)) { <API key>(mapping, filp, offset, req_size); return; } /* do read-ahead */ ondemand_readahead(mapping, ra, filp, false, offset, req_size); } EXPORT_SYMBOL_GPL(<API key>); /** * <API key> - file readahead for marked pages * @mapping: address_space which holds the pagecache and I/O vectors * @ra: file_ra_state which holds the readahead state * @filp: passed on to ->readpage() and ->readpages() * @page: the page at @offset which has the PG_readahead flag set * @offset: start offset into @mapping, in pagecache page-sized units * @req_size: hint: total size of the read which the caller is performing in * pagecache pages * * <API key>() should be called when a page is used which * has the PG_readahead flag; this is a marker to suggest that the application * has used up enough of the readahead window that we should start pulling in * more pages. */ void <API key>(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, struct page *page, pgoff_t offset, unsigned long req_size) { /* no read-ahead */ if (!ra->ra_pages) return; /* * Same bit is used for PG_readahead and PG_reclaim. */ if (PageWriteback(page)) return; ClearPageReadahead(page); /* * Defer asynchronous read-ahead on IO congestion. */ if (bdi_read_congested(mapping->backing_dev_info)) return; /* do read-ahead */ ondemand_readahead(mapping, ra, filp, true, offset, req_size); } EXPORT_SYMBOL_GPL(<API key>); static ssize_t do_readahead(struct address_space *mapping, struct file *filp, pgoff_t index, unsigned long nr) { if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage) return -EINVAL; <API key>(mapping, filp, index, nr); return 0; } SYSCALL_DEFINE3(readahead, int, fd, loff_t, offset, size_t, count) { ssize_t ret; struct fd f; ret = -EBADF; f = fdget(fd); if (f.file) { if (f.file->f_mode & FMODE_READ) { struct address_space *mapping = f.file->f_mapping; pgoff_t start = offset >> PAGE_CACHE_SHIFT; pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT; unsigned long len = end - start + 1; ret = do_readahead(mapping, f.file, start, len); } fdput(f); } return ret; }
#! /bin/sh su vagrant <<EOF mkdir -p $@ EOF
<?php namespace Joomla\Database; /** * Joomla Framework Query Building Class. * * @since 1.0 * * @method string q() q($text, $escape = true) Alias for quote method * @method string qn() qn($name, $as = null) Alias for quoteName method * @method string e() e($text, $extra = false) Alias for escape method */ abstract class DatabaseQuery { /** * The database driver. * * @var DatabaseDriver * @since 1.0 */ protected $db = null; /** * The SQL query (if a direct query string was provided). * * @var string * @since 1.0 */ protected $sql = null; /** * The query type. * * @var string * @since 1.0 */ protected $type = ''; /** * The query element for a generic query (type = null). * * @var Query\QueryElement * @since 1.0 */ protected $element = null; /** * The select element. * * @var Query\QueryElement * @since 1.0 */ protected $select = null; /** * The delete element. * * @var Query\QueryElement * @since 1.0 */ protected $delete = null; /** * The update element. * * @var Query\QueryElement * @since 1.0 */ protected $update = null; /** * The insert element. * * @var Query\QueryElement * @since 1.0 */ protected $insert = null; /** * The from element. * * @var Query\QueryElement * @since 1.0 */ protected $from = null; /** * The join element. * * @var Query\QueryElement * @since 1.0 */ protected $join = null; /** * The set element. * * @var Query\QueryElement * @since 1.0 */ protected $set = null; /** * The where element. * * @var Query\QueryElement * @since 1.0 */ protected $where = null; /** * The group by element. * * @var Query\QueryElement * @since 1.0 */ protected $group = null; /** * The having element. * * @var Query\QueryElement * @since 1.0 */ protected $having = null; /** * The column list for an INSERT statement. * * @var Query\QueryElement * @since 1.0 */ protected $columns = null; /** * The values list for an INSERT statement. * * @var Query\QueryElement * @since 1.0 */ protected $values = null; /** * The order element. * * @var Query\QueryElement * @since 1.0 */ protected $order = null; /** * The auto increment insert field element. * * @var object * @since 1.0 */ protected $autoIncrementField = null; /** * The call element. * * @var Query\QueryElement * @since 1.0 */ protected $call = null; /** * The exec element. * * @var Query\QueryElement * @since 1.0 */ protected $exec = null; /** * The union element. * * @var Query\QueryElement * @since 1.0 */ protected $union = null; /** * Magic method to provide method alias support for quote() and quoteName(). * * @param string $method The called method. * @param array $args The array of arguments passed to the method. * * @return string The aliased method's return value or null. * * @since 1.0 */ public function __call($method, $args) { if (empty($args)) { return; } switch ($method) { case 'q': return $this->quote($args[0], isset($args[1]) ? $args[1] : true); break; case 'qn': return $this->quoteName($args[0], isset($args[1]) ? $args[1] : null); break; case 'e': return $this->escape($args[0], isset($args[1]) ? $args[1] : false); break; } } /** * Class constructor. * * @param DatabaseDriver $db The database driver. * * @since 1.0 */ public function __construct(DatabaseDriver $db = null) { $this->db = $db; } /** * Magic function to convert the query to a string. * * @return string The completed query. * * @since 1.0 */ public function __toString() { $query = ''; if ($this->sql) { return $this->sql; } switch ($this->type) { case 'element': $query .= (string) $this->element; break; case 'select': $query .= (string) $this->select; $query .= (string) $this->from; if ($this->join) { // Special case for joins foreach ($this->join as $join) { $query .= (string) $join; } } if ($this->where) { $query .= (string) $this->where; } if ($this->group) { $query .= (string) $this->group; } if ($this->having) { $query .= (string) $this->having; } if ($this->order) { $query .= (string) $this->order; } break; case 'union': $query .= (string) $this->union; break; case 'delete': $query .= (string) $this->delete; $query .= (string) $this->from; if ($this->join) { // Special case for joins foreach ($this->join as $join) { $query .= (string) $join; } } if ($this->where) { $query .= (string) $this->where; } break; case 'update': $query .= (string) $this->update; if ($this->join) { // Special case for joins foreach ($this->join as $join) { $query .= (string) $join; } } $query .= (string) $this->set; if ($this->where) { $query .= (string) $this->where; } break; case 'insert': $query .= (string) $this->insert; // Set method if ($this->set) { $query .= (string) $this->set; } elseif ($this->values) // Columns-Values method { if ($this->columns) { $query .= (string) $this->columns; } $elements = $this->values->getElements(); if (!($elements[0] instanceof $this)) { $query .= ' VALUES '; } $query .= (string) $this->values; } break; case 'call': $query .= (string) $this->call; break; case 'exec': $query .= (string) $this->exec; break; } if ($this instanceof Query\LimitableInterface) { $query = $this->processLimit($query, $this->limit, $this->offset); } return $query; } /** * Magic function to get protected variable value * * @param string $name The name of the variable. * * @return mixed * * @since 1.0 */ public function __get($name) { return isset($this->$name) ? $this->$name : null; } /** * Add a single column, or array of columns to the CALL clause of the query. * * Note that you must not mix insert, update, delete and select method calls when building a query. * The call method can, however, be called multiple times in the same query. * * Usage: * $query->call('a.*')->call('b.id'); * $query->call(array('a.*', 'b.id')); * * @param mixed $columns A string or an array of field names. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function call($columns) { $this->type = 'call'; if (is_null($this->call)) { $this->call = new Query\QueryElement('CALL', $columns); } else { $this->call->append($columns); } return $this; } /** * Casts a value to a char. * * Ensure that the value is properly quoted before passing to the method. * * Usage: * $query->select($query->castAsChar('a')); * * @param string $value The value to cast as a char. * * @return string Returns the cast value. * * @since 1.0 */ public function castAsChar($value) { return $value; } /** * Gets the number of characters in a string. * * Note, use 'length' to find the number of bytes in a string. * * Usage: * $query->select($query->charLength('a')); * * @param string $field A value. * @param string $operator Comparison operator between charLength integer value and $condition * @param string $condition Integer value to compare charLength with. * * @return string The required char length call. * * @since 1.0 */ public function charLength($field, $operator = null, $condition = null) { return 'CHAR_LENGTH(' . $field . ')' . (isset($operator) && isset($condition) ? ' ' . $operator . ' ' . $condition : ''); } /** * Clear data from the query or a specific clause of the query. * * @param string $clause Optionally, the name of the clause to clear, or nothing to clear the whole query. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function clear($clause = null) { $this->sql = null; switch ($clause) { case 'select': $this->select = null; $this->type = null; break; case 'delete': $this->delete = null; $this->type = null; break; case 'update': $this->update = null; $this->type = null; break; case 'insert': $this->insert = null; $this->type = null; $this->autoIncrementField = null; break; case 'from': $this->from = null; break; case 'join': $this->join = null; break; case 'set': $this->set = null; break; case 'where': $this->where = null; break; case 'group': $this->group = null; break; case 'having': $this->having = null; break; case 'order': $this->order = null; break; case 'columns': $this->columns = null; break; case 'values': $this->values = null; break; case 'exec': $this->exec = null; $this->type = null; break; case 'call': $this->call = null; $this->type = null; break; case 'limit': $this->offset = 0; $this->limit = 0; break; case 'union': $this->union = null; break; default: $this->type = null; $this->select = null; $this->delete = null; $this->update = null; $this->insert = null; $this->from = null; $this->join = null; $this->set = null; $this->where = null; $this->group = null; $this->having = null; $this->order = null; $this->columns = null; $this->values = null; $this->autoIncrementField = null; $this->exec = null; $this->call = null; $this->union = null; $this->offset = 0; $this->limit = 0; break; } return $this; } /** * Adds a column, or array of column names that would be used for an INSERT INTO statement. * * @param mixed $columns A column name, or array of column names. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function columns($columns) { if (is_null($this->columns)) { $this->columns = new Query\QueryElement('()', $columns); } else { $this->columns->append($columns); } return $this; } /** * Concatenates an array of column names or values. * * Usage: * $query->select($query->concatenate(array('a', 'b'))); * * @param array $values An array of values to concatenate. * @param string $separator As separator to place between each value. * * @return string The concatenated values. * * @since 1.0 */ public function concatenate($values, $separator = null) { if ($separator) { return 'CONCATENATE(' . implode(' || ' . $this->quote($separator) . ' || ', $values) . ')'; } else { return 'CONCATENATE(' . implode(' || ', $values) . ')'; } } /** * Gets the current date and time. * * Usage: * $query->where('published_up < '.$query->currentTimestamp()); * * @return string * * @since 1.0 */ public function currentTimestamp() { return 'CURRENT_TIMESTAMP()'; } /** * Returns a PHP date() function compliant date format for the database driver. * * This method is provided for use where the query object is passed to a function for modification. * If you have direct access to the database object, it is recommended you use the getDateFormat method directly. * * @return string The format string. * * @since 1.0 * @throws \RuntimeException */ public function dateFormat() { if (!($this->db instanceof DatabaseDriver)) { throw new \RuntimeException('<API key>'); } return $this->db->getDateFormat(); } /** * Creates a formatted dump of the query for debugging purposes. * * Usage: * echo $query->dump(); * * @return string * * @since 1.0 */ public function dump() { return '<pre class="jdatabasequery">' . str_replace('#__', $this->db->getPrefix(), $this) . '</pre>'; } /** * Add a table name to the DELETE clause of the query. * * Note that you must not mix insert, update, delete and select method calls when building a query. * * Usage: * $query->delete('#__a')->where('id = 1'); * * @param string $table The name of the table to delete from. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function delete($table = null) { $this->type = 'delete'; $this->delete = new Query\QueryElement('DELETE', null); if (!empty($table)) { $this->from($table); } return $this; } /** * Method to escape a string for usage in an SQL statement. * * This method is provided for use where the query object is passed to a function for modification. * If you have direct access to the database object, it is recommended you use the escape method directly. * * Note that 'e' is an alias for this method as it is in <API key>. * * @param string $text The string to be escaped. * @param boolean $extra Optional parameter to provide extra escaping. * * @return string The escaped string. * * @since 1.0 * @throws \RuntimeException if the internal db property is not a valid object. */ public function escape($text, $extra = false) { if (!($this->db instanceof DatabaseDriver)) { throw new \RuntimeException('<API key>'); } return $this->db->escape($text, $extra); } /** * Add a single column, or array of columns to the EXEC clause of the query. * * Note that you must not mix insert, update, delete and select method calls when building a query. * The exec method can, however, be called multiple times in the same query. * * Usage: * $query->exec('a.*')->exec('b.id'); * $query->exec(array('a.*', 'b.id')); * * @param mixed $columns A string or an array of field names. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function exec($columns) { $this->type = 'exec'; if (is_null($this->exec)) { $this->exec = new Query\QueryElement('EXEC', $columns); } else { $this->exec->append($columns); } return $this; } /** * Add a table to the FROM clause of the query. * * Note that while an array of tables can be provided, it is recommended you use explicit joins. * * Usage: * $query->select('*')->from('#__a'); * * @param mixed $tables A string or array of table names. * This can be a JDatabaseQuery object (or a child of it) when used * as a subquery in FROM clause along with a value for $subQueryAlias. * @param string $subQueryAlias Alias used when $tables is a JDatabaseQuery. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 * @throws \RuntimeException */ public function from($tables, $subQueryAlias = null) { if (is_null($this->from)) { if ($tables instanceof $this) { if (is_null($subQueryAlias)) { throw new \RuntimeException('<API key>'); } $tables = '( ' . (string) $tables . ' ) AS ' . $this->quoteName($subQueryAlias); } $this->from = new Query\QueryElement('FROM', $tables); } else { $this->from->append($tables); } return $this; } /** * Used to get a string to extract year from date column. * * Usage: * $query->select($query->year($query->quoteName('dateColumn'))); * * @param string $date Date column containing year to be extracted. * * @return string Returns string to extract year from a date. * * @since 1.0 */ public function year($date) { return 'YEAR(' . $date . ')'; } /** * Used to get a string to extract month from date column. * * Usage: * $query->select($query->month($query->quoteName('dateColumn'))); * * @param string $date Date column containing month to be extracted. * * @return string Returns string to extract month from a date. * * @since 1.0 */ public function month($date) { return 'MONTH(' . $date . ')'; } /** * Used to get a string to extract day from date column. * * Usage: * $query->select($query->day($query->quoteName('dateColumn'))); * * @param string $date Date column containing day to be extracted. * * @return string Returns string to extract day from a date. * * @since 1.0 */ public function day($date) { return 'DAY(' . $date . ')'; } /** * Used to get a string to extract hour from date column. * * Usage: * $query->select($query->hour($query->quoteName('dateColumn'))); * * @param string $date Date column containing hour to be extracted. * * @return string Returns string to extract hour from a date. * * @since 1.0 */ public function hour($date) { return 'HOUR(' . $date . ')'; } /** * Used to get a string to extract minute from date column. * * Usage: * $query->select($query->minute($query->quoteName('dateColumn'))); * * @param string $date Date column containing minute to be extracted. * * @return string Returns string to extract minute from a date. * * @since 1.0 */ public function minute($date) { return 'MINUTE(' . $date . ')'; } /** * Used to get a string to extract seconds from date column. * * Usage: * $query->select($query->second($query->quoteName('dateColumn'))); * * @param string $date Date column containing second to be extracted. * * @return string Returns string to extract second from a date. * * @since 1.0 */ public function second($date) { return 'SECOND(' . $date . ')'; } /** * Add a grouping column to the GROUP clause of the query. * * Usage: * $query->group('id'); * * @param mixed $columns A string or array of ordering columns. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function group($columns) { if (is_null($this->group)) { $this->group = new Query\QueryElement('GROUP BY', $columns); } else { $this->group->append($columns); } return $this; } /** * A conditions to the HAVING clause of the query. * * Usage: * $query->group('id')->having('COUNT(id) > 5'); * * @param mixed $conditions A string or array of columns. * @param string $glue The glue by which to join the conditions. Defaults to AND. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function having($conditions, $glue = 'AND') { if (is_null($this->having)) { $glue = strtoupper($glue); $this->having = new Query\QueryElement('HAVING', $conditions, " $glue "); } else { $this->having->append($conditions); } return $this; } /** * Add an INNER JOIN clause to the query. * * Usage: * $query->innerJoin('b ON b.id = a.id')->innerJoin('c ON c.id = b.id'); * * @param string $condition The join condition. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function innerJoin($condition) { $this->join('INNER', $condition); return $this; } /** * Add a table name to the INSERT clause of the query. * * Note that you must not mix insert, update, delete and select method calls when building a query. * * Usage: * $query->insert('#__a')->set('id = 1'); * $query->insert('#__a')->columns('id, title')->values('1,2')->values('3,4'); * $query->insert('#__a')->columns('id, title')->values(array('1,2', '3,4')); * * @param mixed $table The name of the table to insert data into. * @param boolean $incrementField The name of the field to auto increment. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function insert($table, $incrementField=false) { $this->type = 'insert'; $this->insert = new Query\QueryElement('INSERT INTO', $table); $this->autoIncrementField = $incrementField; return $this; } /** * Add a JOIN clause to the query. * * Usage: * $query->join('INNER', 'b ON b.id = a.id); * * @param string $type The type of join. This string is prepended to the JOIN keyword. * @param string $conditions A string or array of conditions. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function join($type, $conditions) { if (is_null($this->join)) { $this->join = array(); } $this->join[] = new Query\QueryElement(strtoupper($type) . ' JOIN', $conditions); return $this; } /** * Add a LEFT JOIN clause to the query. * * Usage: * $query->leftJoin('b ON b.id = a.id')->leftJoin('c ON c.id = b.id'); * * @param string $condition The join condition. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function leftJoin($condition) { $this->join('LEFT', $condition); return $this; } /** * Get the length of a string in bytes. * * Note, use 'charLength' to find the number of characters in a string. * * Usage: * query->where($query->length('a').' > 3'); * * @param string $value The string to measure. * * @return integer * * @since 1.0 */ public function length($value) { return 'LENGTH(' . $value . ')'; } /** * Get the null or zero representation of a timestamp for the database driver. * * This method is provided for use where the query object is passed to a function for modification. * If you have direct access to the database object, it is recommended you use the nullDate method directly. * * Usage: * $query->where('modified_date <> '.$query->nullDate()); * * @param boolean $quoted Optionally wraps the null date in database quotes (true by default). * * @return string Null or zero representation of a timestamp. * * @since 1.0 * @throws \RuntimeException */ public function nullDate($quoted = true) { if (!($this->db instanceof DatabaseDriver)) { throw new \RuntimeException('<API key>'); } $result = $this->db->getNullDate($quoted); if ($quoted) { return $this->db->quote($result); } return $result; } /** * Add a ordering column to the ORDER clause of the query. * * Usage: * $query->order('foo')->order('bar'); * $query->order(array('foo','bar')); * * @param mixed $columns A string or array of ordering columns. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function order($columns) { if (is_null($this->order)) { $this->order = new Query\QueryElement('ORDER BY', $columns); } else { $this->order->append($columns); } return $this; } /** * Add an OUTER JOIN clause to the query. * * Usage: * $query->outerJoin('b ON b.id = a.id')->outerJoin('c ON c.id = b.id'); * * @param string $condition The join condition. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function outerJoin($condition) { $this->join('OUTER', $condition); return $this; } /** * Method to quote and optionally escape a string to database requirements for insertion into the database. * * This method is provided for use where the query object is passed to a function for modification. * If you have direct access to the database object, it is recommended you use the quote method directly. * * Note that 'q' is an alias for this method as it is in DatabaseDriver. * * Usage: * $query->quote('fulltext'); * $query->q('fulltext'); * $query->q(array('option', 'fulltext')); * * @param mixed $text A string or an array of strings to quote. * @param boolean $escape True to escape the string, false to leave it unchanged. * * @return string The quoted input string. * * @since 1.0 * @throws \RuntimeException if the internal db property is not a valid object. */ public function quote($text, $escape = true) { if (!($this->db instanceof DatabaseDriver)) { throw new \RuntimeException('<API key>'); } return $this->db->quote($text, $escape); } /** * Wrap an SQL statement identifier name such as column, table or database names in quotes to prevent injection * risks and reserved word conflicts. * * This method is provided for use where the query object is passed to a function for modification. * If you have direct access to the database object, it is recommended you use the quoteName method directly. * * Note that 'qn' is an alias for this method as it is in DatabaseDriver. * * Usage: * $query->quoteName('#__a'); * $query->qn('#__a'); * * @param mixed $name The identifier name to wrap in quotes, or an array of identifier names to wrap in quotes. * Each type supports dot-notation name. * @param mixed $as The AS query part associated to $name. It can be string or array, in latter case it has to be * same length of $name; if is null there will not be any AS part for string or array element. * * @return mixed The quote wrapped name, same type of $name. * * @since 1.0 * @throws \RuntimeException if the internal db property is not a valid object. */ public function quoteName($name, $as = null) { if (!($this->db instanceof DatabaseDriver)) { throw new \RuntimeException('<API key>'); } return $this->db->quoteName($name, $as); } /** * Add a RIGHT JOIN clause to the query. * * Usage: * $query->rightJoin('b ON b.id = a.id')->rightJoin('c ON c.id = b.id'); * * @param string $condition The join condition. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function rightJoin($condition) { $this->join('RIGHT', $condition); return $this; } /** * Add a single column, or array of columns to the SELECT clause of the query. * * Note that you must not mix insert, update, delete and select method calls when building a query. * The select method can, however, be called multiple times in the same query. * * Usage: * $query->select('a.*')->select('b.id'); * $query->select(array('a.*', 'b.id')); * * @param mixed $columns A string or an array of field names. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function select($columns) { $this->type = 'select'; if (is_null($this->select)) { $this->select = new Query\QueryElement('SELECT', $columns); } else { $this->select->append($columns); } return $this; } /** * Add a single condition string, or an array of strings to the SET clause of the query. * * Usage: * $query->set('a = 1')->set('b = 2'); * $query->set(array('a = 1', 'b = 2'); * * @param mixed $conditions A string or array of string conditions. * @param string $glue The glue by which to join the condition strings. Defaults to ,. * Note that the glue is set on first use and cannot be changed. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function set($conditions, $glue = ',') { if (is_null($this->set)) { $glue = strtoupper($glue); $this->set = new Query\QueryElement('SET', $conditions, PHP_EOL . "\t$glue "); } else { $this->set->append($conditions); } return $this; } /** * Allows a direct query to be provided to the database driver's setQuery() method, but still allow queries * to have bounded variables. * * Usage: * $query->setQuery('select * from #__users'); * * @param mixed $sql A SQL query string or DatabaseQuery object * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function setQuery($sql) { $this->sql = $sql; return $this; } /** * Add a table name to the UPDATE clause of the query. * * Note that you must not mix insert, update, delete and select method calls when building a query. * * Usage: * $query->update('#__foo')->set(...); * * @param string $table A table to update. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function update($table) { $this->type = 'update'; $this->update = new Query\QueryElement('UPDATE', $table); return $this; } /** * Adds a tuple, or array of tuples that would be used as values for an INSERT INTO statement. * * Usage: * $query->values('1,2,3')->values('4,5,6'); * $query->values(array('1,2,3', '4,5,6')); * * @param string $values A single tuple, or array of tuples. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function values($values) { if (is_null($this->values)) { $this->values = new Query\QueryElement('()', $values, '),('); } else { $this->values->append($values); } return $this; } /** * Add a single condition, or an array of conditions to the WHERE clause of the query. * * Usage: * $query->where('a = 1')->where('b = 2'); * $query->where(array('a = 1', 'b = 2')); * * @param mixed $conditions A string or array of where conditions. * @param string $glue The glue by which to join the conditions. Defaults to AND. * Note that the glue is set on first use and cannot be changed. * * @return DatabaseQuery Returns this object to allow chaining. * * @since 1.0 */ public function where($conditions, $glue = 'AND') { if (is_null($this->where)) { $glue = strtoupper($glue); $this->where = new Query\QueryElement('WHERE', $conditions, " $glue "); } else { $this->where->append($conditions); } return $this; } /** * Method to provide deep copy support to nested objects and arrays when cloning. * * @return void * * @since 1.0 */ public function __clone() { foreach ($this as $k => $v) { if ($k === 'db') { continue; } if (is_object($v) || is_array($v)) { $this->{$k} = unserialize(serialize($v)); } } } /** * Add a query to UNION with the current query. * Multiple unions each require separate statements and create an array of unions. * * Usage: * $query->union('SELECT name FROM #__foo') * $query->union('SELECT name FROM #__foo','distinct') * $query->union(array('SELECT name FROM #__foo', 'SELECT name FROM #__bar')) * * @param mixed $query The Query object or string to union. * @param boolean $distinct True to only return distinct rows from the union. * @param string $glue The glue by which to join the conditions. * * @return mixed The Query object on success or boolean false on failure. * * @since 1.0 */ public function union($query, $distinct = false, $glue = '') { // Clear any ORDER BY clause in UNION query if (!is_null($this->order)) { $this->clear('order'); } // Set up the DISTINCT flag, the name with parentheses, and the glue. if ($distinct) { $name = 'UNION DISTINCT ()'; $glue = ')' . PHP_EOL . 'UNION DISTINCT ('; } else { $glue = ')' . PHP_EOL . 'UNION ('; $name = 'UNION ()'; } // Get the Query\QueryElement if it does not exist if (is_null($this->union)) { $this->union = new Query\QueryElement($name, $query, "$glue"); } else // Otherwise append the second UNION. { $this->union->append($query); } return $this; } /** * Add a query to UNION DISTINCT with the current query. Simply a proxy to Union with the Distinct clause. * * Usage: * $query->unionDistinct('SELECT name FROM #__foo') * * @param mixed $query The Query object or string to union. * @param string $glue The glue by which to join the conditions. * * @return mixed The Query object on success or boolean false on failure. * * @since 1.0 */ public function unionDistinct($query, $glue = '') { $distinct = true; // Apply the distinct flag to the union. return $this->union($query, $distinct, $glue); } /** * Find and replace sprintf-like tokens in a format string. * Each token takes one of the following forms: * %% - A literal percent character. * %[t] - Where [t] is a type specifier. * %[n]$[x] - Where [n] is an argument specifier and [t] is a type specifier. * * Types: * a - Numeric: Replacement text is coerced to a numeric type but not quoted or escaped. * e - Escape: Replacement text is passed to $this->escape(). * E - Escape (extra): Replacement text is passed to $this->escape() with true as the second argument. * n - Name Quote: Replacement text is passed to $this->quoteName(). * q - Quote: Replacement text is passed to $this->quote(). * Q - Quote (no escape): Replacement text is passed to $this->quote() with false as the second argument. * r - Raw: Replacement text is used as-is. (Be careful) * * Date Types: * - Replacement text automatically quoted (use uppercase for Name Quote). * - Replacement text should be a string in date format or name of a date column. * y/Y - Year * m/M - Month * d/D - Day * h/H - Hour * i/I - Minute * s/S - Second * * Invariable Types: * - Takes no argument. * - Argument index not incremented. * t - Replacement text is the result of $this->currentTimestamp(). * z - Replacement text is the result of $this->nullDate(false). * Z - Replacement text is the result of $this->nullDate(true). * * Usage: * $query->format('SELECT %1$n FROM %2$n WHERE %3$n = %4$a', 'foo', '#__foo', 'bar', 1); * Returns: SELECT `foo` FROM `#__foo` WHERE `bar` = 1 * * Notes: * The argument specifier is optional but recommended for clarity. * The argument index used for unspecified tokens is incremented only when used. * * @param string $format The formatting string. * * @return string Returns a string produced according to the formatting string. * * @since 1.0 */ public function format($format) { $query = $this; $args = array_slice(func_get_args(), 1); array_unshift($args, null); $i = 1; $func = function ($match) use ($query, $args, &$i) { if (isset($match[6]) && $match[6] == '%') { return '%'; } // No argument required, do not increment the argument index. switch ($match[5]) { case 't': return $query->currentTimestamp(); break; case 'z': return $query->nullDate(false); break; case 'Z': return $query->nullDate(true); break; } // Increment the argument index only if argument specifier not provided. $index = is_numeric($match[4]) ? (int) $match[4] : $i++; if (!$index || !isset($args[$index])) { // TODO - What to do? sprintf() throws a Warning in these cases. $replacement = ''; } else { $replacement = $args[$index]; } switch ($match[5]) { case 'a': return 0 + $replacement; break; case 'e': return $query->escape($replacement); break; case 'E': return $query->escape($replacement, true); break; case 'n': return $query->quoteName($replacement); break; case 'q': return $query->quote($replacement); break; case 'Q': return $query->quote($replacement, false); break; case 'r': return $replacement; break; // Dates case 'y': return $query->year($query->quote($replacement)); break; case 'Y': return $query->year($query->quoteName($replacement)); break; case 'm': return $query->month($query->quote($replacement)); break; case 'M': return $query->month($query->quoteName($replacement)); break; case 'd': return $query->day($query->quote($replacement)); break; case 'D': return $query->day($query->quoteName($replacement)); break; case 'h': return $query->hour($query->quote($replacement)); break; case 'H': return $query->hour($query->quoteName($replacement)); break; case 'i': return $query->minute($query->quote($replacement)); break; case 'I': return $query->minute($query->quoteName($replacement)); break; case 's': return $query->second($query->quote($replacement)); break; case 'S': return $query->second($query->quoteName($replacement)); break; } return ''; }; /** * Regexp to find an replace all tokens. * Matched fields: * 0: Full token * 1: Everything following '%' * 2: Everything following '%' unless '%' * 3: Argument specifier and '$' * 4: Argument specifier * 5: Type specifier * 6: '%' if full token is '%%' */ return <API key>('#%(((([\d]+)\$)?([<API key>]))|(%))#', $func, $format); } }
package com.xgame.server.common; import java.nio.ByteBuffer; import java.nio.channels.<API key>; public class AuthSessionPackage { public ByteBuffer buffer; public <API key> channel; public AuthSessionPackage( ByteBuffer buffer, <API key> channel ) { this.buffer = buffer; this.channel = channel; } public AuthSessionPackage() { } }
<?php // Definition of ezsrRatingObject class // SOFTWARE NAME: eZ Star Rating // SOFTWARE RELEASE: 5.0.0 // NOTICE: > // This program is free software; you can redistribute it and/or // modify it under the terms of version 2.0 of the GNU General // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // You should have received a copy of version 2.0 of the GNU General // Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. class <API key> extends eZPersistentObject { /** * Used by {@link <API key>::userHasRated()} to cache value. * * @var bool $currentUserHasRated */ protected $currentUserHasRated = null; /** * Construct, use {@link <API key>::create()} to create new objects. * * @param array $row */ protected function __construct( $row ) { $this->eZPersistentObject( $row ); } static function definition() { static $def = array( 'fields' => array( 'id' => array( 'name' => 'id', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'created_at' => array( 'name' => 'created_at', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'user_id' => array( 'name' => 'user_id', 'datatype' => 'integer', 'default' => 0, 'required' => true, 'foreign_class' => 'eZUser', 'foreign_attribute' => 'contentobject_id', 'multiplicity' => '0..1' ), 'session_key' => array( 'name' => 'session_key', 'datatype' => 'string', 'default' => '', 'required' => true ), 'rating' => array( 'name' => 'rating', 'datatype' => 'integer', 'default' => 0, 'required' => true ), 'contentobject_id' => array( 'name' => 'contentobject_id', 'datatype' => 'integer', 'default' => 0, 'required' => true, 'foreign_class' => 'eZContentObject', 'foreign_attribute' => 'id', 'multiplicity' => '1..*' ), '<API key>' => array( 'name' => '<API key>', 'datatype' => 'integer', 'default' => 0, 'required' => true, 'foreign_class' => '<API key>', 'foreign_attribute' => 'id', 'multiplicity' => '1..*' ), ), 'keys' => array( 'id' ), 'function_attributes' => array( 'average_rating' => 'getAverageRating' ), 'increment_key' => 'id', 'class_name' => '<API key>', 'name' => 'ezstarrating_data' ); return $def; } /** * Fetch Average Rating * Will create a unstored one if none could be fetched ( it will have rating_avrage and rating_count of 0 ) * * @return ezsrRatingObject */ function getAverageRating() { $avgRating = ezsrRatingObject::fetchByObjectId( $this->attribute('contentobject_id'), $this->attribute('<API key>') ); if ( !$avgRating instanceof ezsrRatingObject ) { $avgRating = ezsrRatingObject::create( array('contentobject_id' => $this->attribute('contentobject_id'), '<API key>' => $this->attribute('<API key>') ) ); } return $avgRating; } /** * Figgure out if current user has rated, since eZ Publish changes session id as of 4.1 * on login / logout, a couple of things needs to be checked. * 1. Session variable '<API key>' for list of attribute_id's * 2a. (annonymus user) check against session key * 2b. (logged in user) check against user id * * @param bool $returnRatedObject Return object if user has rated and [eZStarRating]AllowChangeRating=enabled * @return bool|<API key> */ function userHasRated( $returnRatedObject = false ) { if ( $this->currentUserHasRated === null ) { $http = eZHTTPTool::instance(); if ( $http->hasSessionVariable('<API key>') ) $attributeIdList = explode( ',', $http->sessionVariable('<API key>') ); else $attributeIdList = array(); $ini = eZINI::instance(); $<API key> = $this->attribute('<API key>'); if ( in_array( $<API key>, $attributeIdList ) && $ini->variable( 'eZStarRating', 'UseUserSession' ) === 'enabled' ) { $this->currentUserHasRated = true; } $returnRatedObject = $returnRatedObject && $ini->variable( 'eZStarRating', 'AllowChangeRating' ) === 'enabled'; if ( $this->currentUserHasRated === null || $returnRatedObject ) { $sessionKey = $this->attribute('session_key'); $userId = $this->attribute('user_id'); if ( $userId == eZUser::anonymousId() ) { $cond = array( 'user_id' => $userId, // for table index 'session_key' => $sessionKey, 'contentobject_id' => $this->attribute('contentobject_id'), // for table index '<API key>' => $<API key> ); } else { $cond = array( 'user_id' => $userId, 'contentobject_id' => $this->attribute('contentobject_id'), // for table index '<API key>' => $<API key> ); } if ( $returnRatedObject ) { $this->currentUserHasRated = eZPersistentObject::fetchObject( self::definition(), null, $cond ); if ( $this->currentUserHasRated === null) $this->currentUserHasRated = false; } else { $this->currentUserHasRated = eZPersistentObject::count( self::definition(), $cond, 'id' ) != 0; } } } return $this->currentUserHasRated; } /** * Override store function to add some custom logic for setting create time and * store <API key> in session to avoid several ratings from same user. * * @param array $fieldFilters */ function store( $fieldFilters = null ) { if ( $this->attribute( 'user_id' ) == eZUser::currentUserID() ) { // Store attribute id in session to avoid multiple ratings by same user even if he logs out (gets new session key) $http = eZHTTPTool::instance(); $attributeIdList = $this->attribute( '<API key>' ); if ( $http->hasSessionVariable('<API key>') ) { $attributeIdList = $http->sessionVariable('<API key>') . ',' . $attributeIdList; } $http->setSessionVariable('<API key>', $attributeIdList ); } eZPersistentObject::store( $fieldFilters ); } /** * Remove rating data by content object id and optionally attribute id. * * @param int $contentobjectID * @param int $<API key> */ static function removeByObjectId( $contentobjectID, $<API key> = null ) { $cond = array( 'contentobject_id' => $contentobjectID ); if ( $<API key> !== null ) { $cond['<API key>'] = $<API key>; } eZPersistentObject::removeObject( self::definition(), $cond ); } /** * Fetch rating by rating id! * * @param int $id * @return null|<API key> */ static function fetch( $id ) { $cond = array( 'id' => $id ); $return = eZPersistentObject::fetchObject( self::definition(), null, $cond ); return $return; } /** * Fetch rating data by content object id and optionally attribute id! * * @param int $contentobjectID * @param int $<API key> * @return null|<API key> */ static function fetchByObjectId( $contentobjectID, $<API key> = null ) { $cond = array( 'contentobject_id' => $contentobjectID ); if ( $<API key> !== null ) { $cond['<API key>'] = $<API key>; } $return = eZPersistentObject::fetchObjectList( self::definition(), null, $cond ); return $return; } /** * Create a <API key> and store it. * Note: No access checks or input validation is done other then on rating * * @param int $contentobjectId * @param int $<API key> * @param int $rate (above 0 and bellow or equal 5) * @param bool $<API key> * @return null|<API key> */ static function rate( $contentobjectId, $<API key>, $rate ) { $rating = null; if ( is_numeric( $contentobjectId ) && is_numeric( $<API key> ) && is_numeric( $rate) && $rate <= 5 && $rate > 0 ) { $row = array ('<API key>' => $<API key>, 'contentobject_id' => $contentobjectId, 'rating' => $rate); $rating = self::create( $row ); if ( !$rating->userHasRated() ) { $rating->store(); $avgRating = $rating->getAverageRating(); $avgRating-><API key>(); $avgRating->store(); // clear the cache for all nodes associated with this object <API key>::<API key>( $contentobjectId, true, false ); } } return $rating; } /** * Create a <API key> by definition data (but do not store it, thats up to you!) * NOTE: you have to provide the following attributes: * contentobject_id * <API key> * rating (this is only requried if you plan to store the object) * * @param array $row * @return <API key> */ static function create( $row = array() ) { if ( !isset( $row['session_key'] ) ) { $http = eZHTTPTool::instance(); $row['session_key'] = $http->sessionID(); } if ( !isset( $row['user_id'] ) ) { $row['user_id'] = eZUser::currentUserID(); } if ( !isset( $row['created_at'] ) ) { $row['created_at'] = time(); } if ( !isset( $row['contentobject_id'] ) ) { eZDebug::writeError( 'Missing \'contentobject_id\' parameter!', __METHOD__ ); } if ( !isset( $row['<API key>'] ) ) { eZDebug::writeError( 'Missing \'<API key>\' parameter!', __METHOD__ ); } $object = new self( $row ); return $object; } /** * Fetch rating ( avrage + total + raw rating data ) by conditions * * @param array $params (see inline doc for possible conditions) * @return array Array of rating data */ static function fetchByConds( $params ) { /** * Conditions possible in $param (array hash): * int 'contentobject_id' * int '<API key>' * int 'user_id' * string 'session_key' * bool 'as_object' By default: true * * Conditions can be combined as you wish, */ $conds = array(); $limit = null; $sorts = array(); $asObject = isset( $params['as_object'] ) ? $params['as_object'] : true; if ( isset( $params['contentobject_id'] ) ) { $conds['contentobject_id'] = $params['contentobject_id']; } else if ( isset( $params['object_id'] ) )// Alias { $conds['contentobject_id'] = $params['object_id']; } if ( isset( $params['<API key>'] ) ) { if ( !isset( $conds['contentobject_id'] ) ) $conds['contentobject_id'] = array( '!=', 0 );// to make sure index is used $conds['<API key>'] = $params['<API key>']; } if ( isset( $params['user_id'] ) ) { $conds['user_id'] = $params['user_id']; } if ( isset( $params['session_key'] ) ) { if ( !isset( $conds['user_id'] ) ) $conds['user_id'] = array( '!=', 0 );// to make sure index is used $conds['session_key'] = $params['session_key']; } if ( isset( $params['limit'] ) ) { $limit = array( 'length' => $params['limit'], 'offset' => (isset( $params['offset'] ) ? $params['offset'] : 0 ) ); } else if ( isset( $params['offset'] ) ) { $limit = array( 'offset' => $params['offset'] ); } if ( isset( $params['sort_by'] ) ) { if ( isset( $params['sort_by'][1] ) && is_array( $params['sort_by'] ) ) $sorts = array( $params['sort_by'][0] => ( $params['sort_by'][1] ? 'asc' : 'desc' ) ); else $sorts[ $params['sort_by'] ] = 'asc'; } $rows = eZPersistentObject::fetchObjectList( self::definition(), null, $conds, $sorts, $limit, $asObject ); if ( $rows === null ) { eZDebug::writeError( 'The ezstarrating table seems to be missing, contact your administrator', __METHOD__ ); return false; } return $rows; } } ?>
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Invenio is free software; you can redistribute it and/or ## published by the Free Software Foundation; either version 2 of the ## Invenio is distributed in the hope that it will be useful, but ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ WebMessage database models. """ # General imports from invenio.base.globals import cfg from invenio.ext.sqlalchemy import db # Create your models here. from string import strip from invenio.modules.accounts.models import User, Usergroup from sqlalchemy.ext.associationproxy import association_proxy class MsgMESSAGE(db.Model): """Represents a MsgMESSAGE record.""" def __str__(self): return "From: %s<%s>, Subject: <%s> %s" % \ (self.user_from.nickname or _('None'), self.user_from.email or _('unknown'), self.subject, self.body) __tablename__ = 'msgMESSAGE' id = db.Column(db.Integer(15, unsigned=True), nullable=False, primary_key=True, autoincrement=True) id_user_from = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id), nullable=True, server_default='0') _sent_to_user_nicks = db.Column(db.Text, name='sent_to_user_nicks', nullable=False) <API key> = db.Column(db.Text, name='sent_to_group_names', nullable=False) subject = db.Column(db.Text, nullable=False) body = db.Column(db.Text, nullable=True) sent_date = db.Column(db.DateTime, nullable=False, server_default='1900-01-01 00:00:00') # db.func.now() -> 'NOW()' received_date = db.Column(db.DateTime, server_default='1900-01-01 00:00:00') user_from = db.relationship(User, backref='sent_messages') #recipients = db.relationship(User, # secondary=lambda: UserMsgMESSAGE.__table__, # collection_class=set) recipients = association_proxy('sent_to_users', 'user_to', creator=lambda u:UserMsgMESSAGE(user_to=u)) @db.hybrid_property def sent_to_user_nicks(self): """ Alias for column 'sent_to_user_nicks'. """ return self._sent_to_user_nicks @db.hybrid_property def sent_to_group_names(self): """ Alias for column 'sent_to_group_names'. """ return self.<API key> @db.validates('_sent_to_user_nicks') def <API key>(self, key, value): user_nicks = filter(len, map(strip, value.split(cfg['<API key>']))) assert len(user_nicks) == len(set(user_nicks)) if len(user_nicks) > 0: assert len(user_nicks) == \ User.query.filter(User.nickname.in_(user_nicks)).count() return cfg['<API key>'].join(user_nicks) @db.validates('<API key>') def <API key>(self, key, value): group_names = filter(len, map(strip, value.split(cfg['<API key>']))) assert len(group_names) == len(set(group_names)) if len(group_names) > 0: assert len(group_names) == \ Usergroup.query.filter(Usergroup.name.in_(group_names)).count() return cfg['<API key>'].join(group_names) @sent_to_user_nicks.setter def sent_to_user_nicks(self, value): old_user_nicks = self.user_nicks self._sent_to_user_nicks = value to_add = set(self.user_nicks)-set(old_user_nicks) to_del = set(old_user_nicks)-set(self.user_nicks) if len(self.group_names): to_del = to_del-set([u.nickname for u in User.query.\ join(User.usergroups).filter( Usergroup.name.in_(self.group_names)).\ all()]) if len(to_del): is_to_del = lambda u: u.nickname in to_del remove_old = filter(is_to_del, self.recipients) for u in remove_old: self.recipients.remove(u) if len(to_add): for u in User.query.filter(User.nickname.\ in_(to_add)).all(): if u not in self.recipients: self.recipients.append(u) @sent_to_group_names.setter def sent_to_group_names(self, value): old_group_names = self.group_names self.<API key> = value groups_to_add = set(self.group_names)-set(old_group_names) groups_to_del = set(old_group_names)-set(self.group_names) if len(groups_to_del): to_del = set([u.nickname for u in User.query.\ join(User.usergroups).filter( Usergroup.name.in_(groups_to_del)).\ all()])-set(self.user_nicks) is_to_del = lambda u: u.nickname in to_del remove_old = filter(is_to_del, self.recipients) for u in remove_old: self.recipients.remove(u) if len(groups_to_add): for u in User.query.join(User.usergroups).filter(db.and_( Usergroup.name.in_(groups_to_add), db.not_(User.nickname.in_(self.user_nicks)))).all(): if u not in self.recipients: self.recipients.append(u) @property def user_nicks(self): if not self._sent_to_user_nicks: return [] return filter(len, map(strip, self._sent_to_user_nicks.split(cfg['<API key>']))) @property def group_names(self): if not self.<API key>: return [] return filter(len, map(strip, self.sent_to_group_names.split(cfg['<API key>']))) #TODO consider moving following lines to separate file. from invenio.modules.messages.config import <API key> from invenio.config import <API key> from invenio.utils.date import datetext_format from datetime import datetime def email_alert(mapper, connection, target): """ Sends email alerts to message recipients. """ from invenio.ext.template import <API key> from invenio.ext.email import send_email, <API key> m = target is_reminder = m.received_date is not None \ and m.received_date > datetime.now() alert = send_email if is_reminder: alert = lambda *args, **kwargs: <API key>(*args, <API key>=[ m.received_date.strftime(datetext_format)], **kwargs) for u in m.recipients: if isinstance(u.settings, dict) and \ u.settings.get('<API key>', True): try: alert( cfg['<API key>'], u.email, subject = m.subject, content = <API key>( 'messages/email_alert.html', message=m, user=u)) except: # FIXME tests are not in request context pass # Registration of email_alert invoked from blueprint # in order to use <API key>. # Reading config <API key> # required app context. def <API key>(): if cfg['<API key>']: from sqlalchemy import event # Register after insert callback. event.listen(MsgMESSAGE, 'after_insert', email_alert) class UserMsgMESSAGE(db.Model): """Represents a UserMsgMESSAGE record.""" __tablename__ = 'user_msgMESSAGE' id_user_to = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(User.id), nullable=False, server_default='0', primary_key=True) id_msgMESSAGE = db.Column(db.Integer(15, unsigned=True), db.ForeignKey(MsgMESSAGE.id), nullable=False, server_default='0', primary_key=True) status = db.Column(db.Char(1), nullable=False, server_default='N') user_to = db.relationship(User, backref='received_messages', collection_class=set) message = db.relationship(MsgMESSAGE, backref='sent_to_users', collection_class=set) __all__ = ['MsgMESSAGE', 'UserMsgMESSAGE']
<?php /* * Obscures peek preview dialog until server replies. */ ?> <style> .peek-obscurer { font-size: 200%; margin: 0; padding: 0; background-color: white; position: absolute; width: 100%; height: 100%; top: 0; left: 0; } .peek-obscurer img { float: left; margin-right: 1em; } </style> <p class="peek-obscurer"> Working... <img src="<?php print $<API key>; ?>throbber.png" alt="Working"> </p>
#include <linux/module.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/spinlock.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/mfd/pmic8901.h> #include <mach/rpm.h> #include <mach/rpm-regulator.h> #include "rpm_resources.h" /* Debug Definitions */ enum { <API key> = BIT(0), <API key> = BIT(1), <API key> = BIT(2), <API key> = BIT(3), }; static int <API key>; module_param_named( debug_mask, <API key>, int, S_IRUSR | S_IWUSR ); #define MICRO_TO_MILLI(uV) ((uV) / 1000) #define MILLI_TO_MICRO(mV) ((mV) * 1000) /* LDO register word 1 */ #define LDO_VOLTAGE 0x00000FFF #define LDO_VOLTAGE_SHIFT 0 #define LDO_PEAK_CURRENT 0x00FFF000 #define <API key> 12 #define LDO_MODE 0x03000000 #define LDO_MODE_SHIFT 24 #define LDO_PIN_CTRL 0x3C000000 #define LDO_PIN_CTRL_SHIFT 26 #define LDO_PIN_FN 0xC0000000 #define LDO_PIN_FN_SHIFT 30 /* LDO register word 2 */ #define <API key> 0x00000001 #define <API key> 0 #define LDO_AVG_CURRENT 0x00001FFE #define <API key> 1 /* SMPS register word 1 */ #define SMPS_VOLTAGE 0x00000FFF #define SMPS_VOLTAGE_SHIFT 0 #define SMPS_PEAK_CURRENT 0x00FFF000 #define <API key> 12 #define SMPS_MODE 0x03000000 #define SMPS_MODE_SHIFT 24 #define SMPS_PIN_CTRL 0x3C000000 #define SMPS_PIN_CTRL_SHIFT 26 #define SMPS_PIN_FN 0xC0000000 #define SMPS_PIN_FN_SHIFT 30 /* SMPS register word 2 */ #define <API key> 0x00000001 #define <API key> 0 #define SMPS_AVG_CURRENT 0x00001FFE #define <API key> 1 #define SMPS_FREQ 0x001FE000 #define SMPS_FREQ_SHIFT 13 #define SMPS_CLK_SRC 0x00600000 #define SMPS_CLK_SRC_SHIFT 21 /* SWITCH register word 1 */ #define SWITCH_STATE 0x0001 #define SWITCH_STATE_SHIFT 0 #define <API key> 0x0002 #define <API key> 1 #define SWITCH_PIN_CTRL 0x003C #define <API key> 2 #define SWITCH_PIN_FN 0x00C0 #define SWITCH_PIN_FN_SHIFT 6 /* NCP register word 1 */ #define NCP_VOLTAGE 0x0FFF #define NCP_VOLTAGE_SHIFT 0 #define NCP_STATE 0x1000 #define NCP_STATE_SHIFT 12 /* * This is used when voting for LPM or HPM by subtracting or adding to the * hpm_min_load of a regulator. It has units of uA. */ #define LOAD_THRESHOLD_STEP 1000 /* This is the maximum uA load that can be passed to the RPM. */ #define MAX_POSSIBLE_LOAD (MILLI_TO_MICRO(0xFFF)) /* Voltage regulator types */ #define IS_LDO(id) ((id >= <API key> && \ id <= <API key>) || \ (id >= <API key> && \ id <= <API key>)) #define IS_SMPS(id) ((id >= <API key> && \ id <= <API key>) || \ (id >= <API key> && \ id <= <API key>)) #define IS_SWITCH(id) ((id >= <API key> && \ id <= <API key>) || \ (id >= <API key> && \ id <= <API key>) || \ (id == <API key>)) #define IS_NCP(id) (id == <API key>) //jinho.jang 2010.03.09 - ES2.0 mipi fix //#define ES2P0_MIPI_FIX #ifdef ES2P0_MIPI_FIX #else #define IS_8901_SMPS(id) ((id >= <API key> && \ id <= <API key>)) #endif struct vreg { struct msm_rpm_iv_pair req[2]; struct msm_rpm_iv_pair prev_active_req[2]; struct msm_rpm_iv_pair prev_sleep_req[2]; struct rpm_vreg_pdata *pdata; int save_uV; const int hpm_min_load; unsigned pc_vote; unsigned optimum; unsigned mode_initialized; int active_min_mV_vote[<API key>]; int sleep_min_mV_vote[<API key>]; enum rpm_vreg_id id; }; #define <API key> 0 #define VREG_2(_vreg_id, _rpm_id, _hpm_min_load) \ [RPM_VREG_ID_##_vreg_id] = { \ .req = { \ [0] = { .id = MSM_RPM_ID_##_rpm_id##_0, }, \ [1] = { .id = MSM_RPM_ID_##_rpm_id##_1, }, \ }, \ .hpm_min_load = RPM_VREG_##_hpm_min_load, \ } #define VREG_1(_vreg_id, _rpm_id) \ [RPM_VREG_ID_##_vreg_id] = { \ .req = { \ [0] = { .id = MSM_RPM_ID_##_rpm_id, }, \ [1] = { .id = -1, }, \ }, \ } static struct vreg vregs[RPM_VREG_ID_MAX] = { VREG_2(PM8058_L0, LDO0, <API key>), VREG_2(PM8058_L1, LDO1, <API key>), VREG_2(PM8058_L2, LDO2, <API key>), VREG_2(PM8058_L3, LDO3, <API key>), VREG_2(PM8058_L4, LDO4, LDO_50_HPM_MIN_LOAD), VREG_2(PM8058_L5, LDO5, <API key>), VREG_2(PM8058_L6, LDO6, LDO_50_HPM_MIN_LOAD), VREG_2(PM8058_L7, LDO7, LDO_50_HPM_MIN_LOAD), VREG_2(PM8058_L8, LDO8, <API key>), VREG_2(PM8058_L9, LDO9, <API key>), VREG_2(PM8058_L10, LDO10, <API key>), VREG_2(PM8058_L11, LDO11, <API key>), VREG_2(PM8058_L12, LDO12, <API key>), VREG_2(PM8058_L13, LDO13, <API key>), VREG_2(PM8058_L14, LDO14, <API key>), VREG_2(PM8058_L15, LDO15, <API key>), VREG_2(PM8058_L16, LDO16, <API key>), VREG_2(PM8058_L17, LDO17, <API key>), VREG_2(PM8058_L18, LDO18, <API key>), VREG_2(PM8058_L19, LDO19, <API key>), VREG_2(PM8058_L20, LDO20, <API key>), VREG_2(PM8058_L21, LDO21, <API key>), VREG_2(PM8058_L22, LDO22, <API key>), VREG_2(PM8058_L23, LDO23, <API key>), VREG_2(PM8058_L24, LDO24, <API key>), VREG_2(PM8058_L25, LDO25, <API key>), VREG_2(PM8058_S0, SMPS0, SMPS_HPM_MIN_LOAD), VREG_2(PM8058_S1, SMPS1, SMPS_HPM_MIN_LOAD), VREG_2(PM8058_S2, SMPS2, SMPS_HPM_MIN_LOAD), VREG_2(PM8058_S3, SMPS3, SMPS_HPM_MIN_LOAD), VREG_2(PM8058_S4, SMPS4, SMPS_HPM_MIN_LOAD), VREG_1(PM8058_LVS0, LVS0), VREG_1(PM8058_LVS1, LVS1), VREG_2(PM8058_NCP, NCP, NCP_HPM_MIN_LOAD), VREG_2(PM8901_L0, LDO0B, <API key>), VREG_2(PM8901_L1, LDO1B, <API key>), VREG_2(PM8901_L2, LDO2B, <API key>), VREG_2(PM8901_L3, LDO3B, <API key>), VREG_2(PM8901_L4, LDO4B, <API key>), VREG_2(PM8901_L5, LDO5B, <API key>), VREG_2(PM8901_L6, LDO6B, <API key>), VREG_2(PM8901_S0, SMPS0B, FTSMPS_HPM_MIN_LOAD), VREG_2(PM8901_S1, SMPS1B, FTSMPS_HPM_MIN_LOAD), VREG_2(PM8901_S2, SMPS2B, FTSMPS_HPM_MIN_LOAD), VREG_2(PM8901_S3, SMPS3B, FTSMPS_HPM_MIN_LOAD), VREG_2(PM8901_S4, SMPS4B, FTSMPS_HPM_MIN_LOAD), VREG_1(PM8901_LVS0, LVS0B), VREG_1(PM8901_LVS1, LVS1B), VREG_1(PM8901_LVS2, LVS2B), VREG_1(PM8901_LVS3, LVS3B), VREG_1(PM8901_MVS0, MVS), }; static void print_rpm_request(struct vreg *vreg, int set); static void print_rpm_vote(struct vreg *vreg, enum rpm_vreg_voter voter, int set, int voter_mV, int aggregate_mV); static void print_rpm_duplicate(struct vreg *vreg, int set, int cnt); #ifdef ES2P0_MIPI_FIX #else static unsigned int smps_get_mode(struct regulator_dev *dev); static unsigned int ldo_get_mode(struct regulator_dev *dev); static unsigned int switch_get_mode(struct regulator_dev *dev); /* Spin lock needed for sleep-selectable regulators. */ static DEFINE_SPINLOCK(pm8058_noirq_lock); #endif static int voltage_from_req(struct vreg *vreg) { int shift = 0; uint32_t value = 0, mask = 0; value = vreg->req[0].value; if (IS_SMPS(vreg->id)) { mask = SMPS_VOLTAGE; shift = SMPS_VOLTAGE_SHIFT; } else if (IS_LDO(vreg->id)) { mask = LDO_VOLTAGE; shift = LDO_VOLTAGE_SHIFT; } else if (IS_NCP(vreg->id)) { mask = NCP_VOLTAGE; shift = NCP_VOLTAGE_SHIFT; } return (value & mask) >> shift; } static void voltage_to_req(int voltage, struct vreg *vreg) { int shift = 0; uint32_t *value = NULL, mask = 0; value = &(vreg->req[0].value); if (IS_SMPS(vreg->id)) { mask = SMPS_VOLTAGE; shift = SMPS_VOLTAGE_SHIFT; } else if (IS_LDO(vreg->id)) { mask = LDO_VOLTAGE; shift = LDO_VOLTAGE_SHIFT; } else if (IS_NCP(vreg->id)) { mask = NCP_VOLTAGE; shift = NCP_VOLTAGE_SHIFT; } *value &= ~mask; *value |= (voltage << shift) & mask; } static int vreg_send_request(struct vreg *vreg, enum rpm_vreg_voter voter, int set, unsigned mask0, unsigned val0, unsigned mask1, unsigned val1, unsigned cnt, int update_voltage) { struct msm_rpm_iv_pair *prev_req; int rc = 0, max_mV_vote = 0, i; unsigned prev0, prev1; int *min_mV_vote; if (set == MSM_RPM_CTX_SET_0) { min_mV_vote = vreg->active_min_mV_vote; prev_req = vreg->prev_active_req; } else { min_mV_vote = vreg->sleep_min_mV_vote; prev_req = vreg->prev_sleep_req; } prev0 = vreg->req[0].value; vreg->req[0].value &= ~mask0; vreg->req[0].value |= val0 & mask0; prev1 = vreg->req[1].value; vreg->req[1].value &= ~mask1; vreg->req[1].value |= val1 & mask1; if (update_voltage) min_mV_vote[voter] = voltage_from_req(vreg); /* Find the highest voltage voted for and use it. */ for (i = 0; i < <API key>; i++) max_mV_vote = max(max_mV_vote, min_mV_vote[i]); voltage_to_req(max_mV_vote, vreg); if (<API key> & <API key>) print_rpm_vote(vreg, voter, set, min_mV_vote[voter], max_mV_vote); /* Ignore duplicate requests */ if (vreg->req[0].value != prev_req[0].value || vreg->req[1].value != prev_req[1].value) { rc = msm_rpmrs_set_noirq(set, vreg->req, cnt); if (rc) { vreg->req[0].value = prev0; vreg->req[1].value = prev1; pr_err("%s: msm_rpmrs_set_noirq failed - " "set=%s, id=%d, rc=%d\n", __func__, (set == MSM_RPM_CTX_SET_0 ? "active" : "sleep"), vreg->req[0].id, rc); } else { /* Only save if nonzero and active set. */ if (max_mV_vote && (set == MSM_RPM_CTX_SET_0)) vreg->save_uV = MILLI_TO_MICRO(max_mV_vote); if (<API key> & <API key>) print_rpm_request(vreg, set); prev_req[0].value = vreg->req[0].value; prev_req[1].value = vreg->req[1].value; } } else if (<API key> & <API key>) { print_rpm_duplicate(vreg, set, cnt); } return rc; } static int vreg_set_noirq(struct vreg *vreg, enum rpm_vreg_voter voter, int sleep, unsigned mask0, unsigned val0, unsigned mask1, unsigned val1, unsigned cnt, int update_voltage) { #ifdef ES2P0_MIPI_FIX static DEFINE_SPINLOCK(pm8058_noirq_lock); #endif unsigned long flags; int rc; unsigned val0_sleep, mask0_sleep; if (voter < 0 || voter >= <API key>) return -EINVAL; spin_lock_irqsave(&pm8058_noirq_lock, flags); /* * Send sleep set request first so that subsequent set_mode, etc calls * use the voltage from the active set. */ if (sleep) rc = vreg_send_request(vreg, voter, <API key>, mask0, val0, mask1, val1, cnt, update_voltage); else { /* * Vote for 0 V in the sleep set when active set-only is * specified. This ensures that a disable vote will be issued * at some point for the sleep set of the regulator. */ val0_sleep = val0; mask0_sleep = mask0; if (IS_SMPS(vreg->id)) { val0_sleep &= ~SMPS_VOLTAGE; mask0_sleep |= SMPS_VOLTAGE; } else if (IS_LDO(vreg->id)) { val0_sleep &= ~LDO_VOLTAGE; mask0_sleep |= LDO_VOLTAGE; } else if (IS_NCP(vreg->id)) { val0_sleep &= ~NCP_VOLTAGE; mask0_sleep |= NCP_VOLTAGE; } rc = vreg_send_request(vreg, voter, <API key>, mask0_sleep, val0_sleep, mask1, val1, cnt, update_voltage); } rc = vreg_send_request(vreg, voter, MSM_RPM_CTX_SET_0, mask0, val0, mask1, val1, cnt, update_voltage); <API key>(&pm8058_noirq_lock, flags); return rc; } /** * <API key> - vote for a min_uV value of specified regualtor * @vreg: ID for regulator * @voter: ID for the voter * @min_uV: minimum acceptable voltage (in uV) that is voted for * @sleep_also: 0 for active set only, non-0 for active set and sleep set * * Returns 0 on success or errno. * * This function is used to vote for the voltage of a regulator without * using the regulator framework. It is needed by consumers which hold spin * locks or have interrupts disabled because the regulator framework can sleep. * It is also needed by consumers which wish to only vote for active set * regulator voltage. * * If sleep_also == 0, then a sleep-set value of 0V will be voted for. * * This function may only be called for regulators which have the sleep flag * specified in their private data. */ int <API key>(enum rpm_vreg_id vreg_id, enum rpm_vreg_voter voter, int min_uV, int sleep_also) { int rc; unsigned val0 = 0, val1 = 0, mask0 = 0, mask1 = 0, cnt = 2; if (vreg_id < 0 || vreg_id >= RPM_VREG_ID_MAX) return -EINVAL; if (!vregs[vreg_id].pdata->sleep_selectable) return -EINVAL; if (min_uV < vregs[vreg_id].pdata->init_data.constraints.min_uV || min_uV > vregs[vreg_id].pdata->init_data.constraints.max_uV) return -EINVAL; if (IS_SMPS(vreg_id)) { mask0 = SMPS_VOLTAGE; val0 = MICRO_TO_MILLI(min_uV) << SMPS_VOLTAGE_SHIFT; } else if (IS_LDO(vreg_id)) { mask0 = LDO_VOLTAGE; val0 = MICRO_TO_MILLI(min_uV) << LDO_VOLTAGE_SHIFT; } else if (IS_NCP(vreg_id)) { mask0 = NCP_VOLTAGE; val0 = MICRO_TO_MILLI(min_uV) << NCP_VOLTAGE_SHIFT; cnt = 1; } else { cnt = 1; } rc = vreg_set_noirq(&vregs[vreg_id], voter, sleep_also, mask0, val0, mask1, val1, cnt, 1); return rc; } EXPORT_SYMBOL_GPL(<API key>); /** * <API key> - sets the frequency of a switching regulator * @vreg: ID for regulator * @min_uV: minimum acceptable frequency of operation * * Returns 0 on success or errno. */ int <API key>(enum rpm_vreg_id vreg_id, enum rpm_vreg_freq freq) { unsigned val0 = 0, val1 = 0, mask0 = 0, mask1 = 0, cnt = 2; int rc; if (vreg_id < 0 || vreg_id >= RPM_VREG_ID_MAX) { pr_err("%s: invalid regulator id=%d\n", __func__, vreg_id); return -EINVAL; } if (freq < 0 || freq > RPM_VREG_FREQ_1p20) { pr_err("%s: invalid frequency=%d\n", __func__, freq); return -EINVAL; } if (!IS_SMPS(vreg_id)) { pr_err("%s: regulator id=%d does not support frequency\n", __func__, vreg_id); return -EINVAL; } if (!vregs[vreg_id].pdata->sleep_selectable) { pr_err("%s: regulator id=%d is not marked sleep selectable\n", __func__, vreg_id); return -EINVAL; } mask1 = SMPS_FREQ; val1 = freq << SMPS_FREQ_SHIFT; rc = vreg_set_noirq(&vregs[vreg_id], <API key>, 1, mask0, val0, mask1, val1, cnt, 0); return rc; } EXPORT_SYMBOL_GPL(<API key>); #define IS_PMIC_8901_V1(rev) ((rev) == PM_8901_REV_1p0 || \ (rev) == PM_8901_REV_1p1) #define PMIC_8901_V1_SCALE(uV) ((((uV) - 62100) * 23) / 25) static inline int vreg_hpm_min_uA(struct vreg *vreg) { return vreg->hpm_min_load; } static inline int vreg_lpm_max_uA(struct vreg *vreg) { return vreg->hpm_min_load - LOAD_THRESHOLD_STEP; } static inline unsigned saturate_load(unsigned load_uA) { return (load_uA > MAX_POSSIBLE_LOAD ? MAX_POSSIBLE_LOAD : load_uA); } #ifdef ES2P0_MIPI_FIX #else /* Change vreg->req, but do not send it to the RPM. */ static int vreg_store(struct vreg *vreg, unsigned mask0, unsigned val0, unsigned mask1, unsigned val1) { unsigned long flags = 0; if (vreg->pdata->sleep_selectable) spin_lock_irqsave(&pm8058_noirq_lock, flags); vreg->req[0].value &= ~mask0; vreg->req[0].value |= val0 & mask0; vreg->req[1].value &= ~mask1; vreg->req[1].value |= val1 & mask1; if (vreg->pdata->sleep_selectable) <API key>(&pm8058_noirq_lock, flags); return 0; } #endif static int vreg_set(struct vreg *vreg, unsigned mask0, unsigned val0, unsigned mask1, unsigned val1, unsigned cnt) { unsigned prev0 = 0, prev1 = 0; int rc; /* * Bypass the normal route for regulators that can be called to change * just the active set values. */ if (vreg->pdata->sleep_selectable) return vreg_set_noirq(vreg, <API key>, 1, mask0, val0, mask1, val1, cnt, 1); prev0 = vreg->req[0].value; vreg->req[0].value &= ~mask0; vreg->req[0].value |= val0 & mask0; prev1 = vreg->req[1].value; vreg->req[1].value &= ~mask1; vreg->req[1].value |= val1 & mask1; /* Ignore duplicate requests */ if (vreg->req[0].value == vreg->prev_active_req[0].value && vreg->req[1].value == vreg->prev_active_req[1].value) { if (<API key> & <API key>) print_rpm_duplicate(vreg, MSM_RPM_CTX_SET_0, cnt); return 0; } rc = msm_rpm_set(MSM_RPM_CTX_SET_0, vreg->req, cnt); if (rc) { vreg->req[0].value = prev0; vreg->req[1].value = prev1; pr_err("%s: msm_rpm_set fail id=%d, rc=%d\n", __func__, vreg->req[0].id, rc); } else { if (<API key> & <API key>) print_rpm_request(vreg, MSM_RPM_CTX_SET_0); vreg->prev_active_req[0].value = vreg->req[0].value; vreg->prev_active_req[1].value = vreg->req[1].value; } return rc; } #ifdef ES2P0_MIPI_FIX static int smps_set_voltage(struct regulator_dev *dev, int min_uV, int max_uV) { struct vreg *vreg = rdev_get_drvdata(dev); int rc; rc = vreg_set(vreg, SMPS_VOLTAGE, MICRO_TO_MILLI(min_uV) << SMPS_VOLTAGE_SHIFT, 0, 0, 2); if (rc) return rc; /* only save if nonzero (or not disabling) */ if (min_uV && !vreg->pdata->sleep_selectable) vreg->save_uV = min_uV; return rc; } #else static int smps_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return ((vreg->req[0].value & SMPS_VOLTAGE) >> SMPS_VOLTAGE_SHIFT) != 0; } #endif #ifdef ES2P0_MIPI_FIX /* * This secondary set_voltage callback is needed to handle v1 PMIC 8901 SMPS * voltage compensation on the Linux side. The RPM does not correct for the * output voltage error present in v1 PMIC 8901 chips. */ static int <API key>(struct regulator_dev *dev, int min_uV, int max_uV) { struct vreg *vreg = rdev_get_drvdata(dev); int scaled_min_uV = min_uV; int rc; static int pmic8901_rev; /* Scale input request voltage down if using v1 PMIC 8901. */ if (min_uV) { if (pmic8901_rev <= 0) pmic8901_rev = pm8901_rev(NULL); if (pmic8901_rev < 0) pr_err("%s: setting %s to %d uV; PMIC 8901 revision " "unavailable, no scaling can be performed.\n", __func__, dev->desc->name, min_uV); else if (IS_PMIC_8901_V1(pmic8901_rev)) scaled_min_uV = PMIC_8901_V1_SCALE(min_uV); } rc = vreg_set(vreg, SMPS_VOLTAGE, MICRO_TO_MILLI(scaled_min_uV) << SMPS_VOLTAGE_SHIFT, 0, 0, 2); if (rc) return rc; /* only save if nonzero (or not disabling) */ if (min_uV && !vreg->pdata->sleep_selectable) vreg->save_uV = min_uV; return rc; } #else static int _smps_set_voltage(struct regulator_dev *dev, int min_uV) { struct vreg *vreg = rdev_get_drvdata(dev); int scaled_min_uV = min_uV; static int pmic8901_rev; /* Scale input request voltage down if using v1 PMIC 8901. */ if (IS_8901_SMPS(vreg->id) && min_uV) { if (pmic8901_rev <= 0) pmic8901_rev = pm8901_rev(NULL); if (pmic8901_rev < 0) pr_err("%s: setting %s to %d uV; PMIC 8901 revision " "unavailable, no scaling can be performed.\n", __func__, dev->desc->name, min_uV); else if (IS_PMIC_8901_V1(pmic8901_rev)) scaled_min_uV = PMIC_8901_V1_SCALE(min_uV); } return vreg_set(vreg, SMPS_VOLTAGE, MICRO_TO_MILLI(scaled_min_uV) << SMPS_VOLTAGE_SHIFT, 0, 0, 2); } static int smps_set_voltage(struct regulator_dev *dev, int min_uV, int max_uV) { struct vreg *vreg = rdev_get_drvdata(dev); int rc = 0; if (smps_is_enabled(dev)) rc = _smps_set_voltage(dev, min_uV); if (rc) return rc; /* only save if nonzero (or not disabling) */ if (min_uV && (!vreg->pdata->sleep_selectable || !smps_is_enabled(dev))) vreg->save_uV = min_uV; return rc; } #endif static int smps_get_voltage(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return vreg->save_uV; } #ifdef ES2P0_MIPI_FIX static int smps_enable(struct regulator_dev *dev) { int rc = 0; struct vreg *vreg = rdev_get_drvdata(dev); /* enable by setting voltage */ if (MICRO_TO_MILLI(vreg->save_uV) > 0) rc = smps_set_voltage(dev, vreg->save_uV, vreg->save_uV); return rc; } static int smps_disable(struct regulator_dev *dev) { /* disable by setting voltage to zero */ return smps_set_voltage(dev, 0, 0); } static int smps_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return ((vreg->req[0].value & SMPS_VOLTAGE) >> SMPS_VOLTAGE_SHIFT) != 0; } #else static int smps_enable(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); int rc = 0; unsigned mask, val; /* enable by setting voltage */ if (MICRO_TO_MILLI(vreg->save_uV) > 0) { /* reenable pin control if it is in use */ if (smps_get_mode(dev) == REGULATOR_MODE_IDLE) { mask = SMPS_PIN_CTRL | SMPS_PIN_FN; val = vreg->pdata->pin_ctrl << SMPS_PIN_CTRL_SHIFT | vreg->pdata->pin_fn << SMPS_PIN_FN_SHIFT; vreg_store(vreg, mask, val, 0, 0); } rc = _smps_set_voltage(dev, vreg->save_uV); } return rc; } static int smps_disable(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned mask, val; /* turn off pin control */ mask = SMPS_PIN_CTRL | SMPS_PIN_FN; val = <API key> << SMPS_PIN_CTRL_SHIFT | <API key> << SMPS_PIN_FN_SHIFT; vreg_store(vreg, mask, val, 0, 0); /* disable by setting voltage to zero */ return _smps_set_voltage(dev, 0); } #endif /* * Optimum mode programming: * REGULATOR_MODE_FAST: Go to HPM (highest priority) * <API key>: Go to pin ctrl mode if there are any pin ctrl * votes, else go to LPM * * Pin ctrl mode voting via regulator set_mode: * REGULATOR_MODE_IDLE: Go to pin ctrl mode if the optimum mode is LPM, else * go to HPM * <API key>: Go to LPM if it is the optimum mode, else go to HPM * * Pin ctrl mode takes priority on the RPM when force mode is not set; * therefore, pin ctrl bits must be cleared if LPM or HPM is being voted for. */ #ifdef ES2P0_MIPI_FIX static int smps_set_mode(struct regulator_dev *dev, unsigned int mode) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned optimum = vreg->optimum; unsigned pc_vote = vreg->pc_vote; unsigned mode_initialized = vreg->mode_initialized; unsigned mask0 = 0, val0 = 0, mask1 = 0, val1 = 0; int peak_uA; int rc = 0; peak_uA = MILLI_TO_MICRO((vreg->req[0].value & SMPS_PEAK_CURRENT) >> <API key>); switch (mode) { case REGULATOR_MODE_FAST: if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } /* clear pin control */ mask0 |= SMPS_PIN_CTRL; optimum = mode; mode_initialized = 1; break; case <API key>: if (peak_uA > vreg_lpm_max_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } if (pc_vote) { mask0 |= SMPS_PIN_CTRL; val0 |= vreg->pdata->pin_ctrl << SMPS_PIN_CTRL_SHIFT; } else { /* clear pin control */ mask0 |= SMPS_PIN_CTRL; } optimum = mode; mode_initialized = 1; break; case REGULATOR_MODE_IDLE: if (pc_vote++) goto done; /* already taken care of */ if (mode_initialized && optimum == REGULATOR_MODE_FAST) { if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } /* clear pin control */ mask0 |= SMPS_PIN_CTRL; } else { mask0 = SMPS_PIN_CTRL; val0 = vreg->pdata->pin_ctrl << SMPS_PIN_CTRL_SHIFT; } break; case <API key>: if (pc_vote && --pc_vote) goto done; /* already taken care of */ if (optimum == <API key>) { if (peak_uA > vreg_lpm_max_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } } else { if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } } /* clear pin control */ mask0 |= SMPS_PIN_CTRL; break; default: return -EINVAL; } rc = vreg_set(rdev_get_drvdata(dev), mask0, val0, mask1, val1, 2); if (rc) return rc; done: vreg->mode_initialized = mode_initialized; vreg->optimum = optimum; vreg->pc_vote = pc_vote; return 0; } #else static int smps_set_mode(struct regulator_dev *dev, unsigned int mode) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned optimum = vreg->optimum; unsigned pc_vote = vreg->pc_vote; unsigned mode_initialized = vreg->mode_initialized; unsigned mask0 = 0, val0 = 0, mask1 = 0, val1 = 0; int set_hpm = -1, set_pin_control = -1; int peak_uA; int rc = 0; peak_uA = MILLI_TO_MICRO((vreg->req[0].value & SMPS_PEAK_CURRENT) >> <API key>); switch (mode) { case REGULATOR_MODE_FAST: set_hpm = 1; set_pin_control = 0; optimum = REGULATOR_MODE_FAST; mode_initialized = 1; break; case <API key>: set_hpm = 0; if (pc_vote) set_pin_control = 1; else set_pin_control = 0; optimum = <API key>; mode_initialized = 1; break; case REGULATOR_MODE_IDLE: if (pc_vote++) goto done; /* already taken care of */ if (mode_initialized && optimum == REGULATOR_MODE_FAST) { set_hpm = 1; set_pin_control = 0; } else { set_pin_control = 1; } break; case <API key>: if (pc_vote && --pc_vote) goto done; /* already taken care of */ if (optimum == <API key>) set_hpm = 0; else set_hpm = 1; set_pin_control = 0; break; default: return -EINVAL; } if (set_hpm == 1) { /* Make sure that request currents are at HPM level. */ if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } } else if (set_hpm == 0) { /* Make sure that request currents are at LPM level. */ if (peak_uA > vreg_lpm_max_uA(vreg)) { mask0 = SMPS_PEAK_CURRENT; mask1 = SMPS_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & SMPS_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & SMPS_AVG_CURRENT; } } if (set_pin_control == 1) { /* Enable pin control and pin function. */ mask0 |= SMPS_PIN_CTRL | SMPS_PIN_FN; val0 |= vreg->pdata->pin_ctrl << SMPS_PIN_CTRL_SHIFT | vreg->pdata->pin_fn << SMPS_PIN_FN_SHIFT; } else if (set_pin_control == 0) { /* Clear pin control and pin function*/ mask0 |= SMPS_PIN_CTRL | SMPS_PIN_FN; val0 |= <API key> << SMPS_PIN_CTRL_SHIFT | <API key> << SMPS_PIN_FN_SHIFT; } if (smps_is_enabled(dev)) { rc = vreg_set(vreg, mask0, val0, mask1, val1, 2); } else { /* Regulator is disabled; store but don't send new request. */ rc = vreg_store(vreg, mask0, val0, mask1, val1); } if (rc) return rc; done: vreg->mode_initialized = mode_initialized; vreg->optimum = optimum; vreg->pc_vote = pc_vote; return 0; } #endif #ifdef ES2P0_MIPI_FIX static unsigned int smps_get_mode(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); if (vreg->optimum == REGULATOR_MODE_FAST) return REGULATOR_MODE_FAST; else if (vreg->pc_vote) return REGULATOR_MODE_IDLE; else if (vreg->optimum == <API key>) return <API key>; return REGULATOR_MODE_FAST; } #else static unsigned int smps_get_mode(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); if ((vreg->optimum == REGULATOR_MODE_FAST) && vreg->mode_initialized) return REGULATOR_MODE_FAST; else if (vreg->pc_vote) return REGULATOR_MODE_IDLE; else if (vreg->optimum == <API key>) return <API key>; return REGULATOR_MODE_FAST; } #endif unsigned int <API key>(struct regulator_dev *dev, int input_uV, int output_uV, int load_uA) { struct vreg *vreg = rdev_get_drvdata(dev); if (MICRO_TO_MILLI(load_uA) > 0) { vreg->req[0].value &= ~SMPS_PEAK_CURRENT; vreg->req[0].value |= (MICRO_TO_MILLI(saturate_load(load_uA)) << <API key>) & SMPS_PEAK_CURRENT; vreg->req[1].value &= ~SMPS_AVG_CURRENT; vreg->req[1].value |= (MICRO_TO_MILLI(saturate_load(load_uA)) << <API key>) & SMPS_AVG_CURRENT; } else { /* * <API key> is being called before consumers have * specified their load currents via <API key>. * Return whatever the existing mode is. */ return smps_get_mode(dev); } if (load_uA >= vreg->hpm_min_load) return REGULATOR_MODE_FAST; return <API key>; } #ifdef ES2P0_MIPI_FIX static int ldo_set_voltage(struct regulator_dev *dev, int min_uV, int max_uV) { struct vreg *vreg = rdev_get_drvdata(dev); int rc; rc = vreg_set(vreg, LDO_VOLTAGE, MICRO_TO_MILLI(min_uV) << LDO_VOLTAGE_SHIFT, 0, 0, 2); if (rc) return rc; /* only save if nonzero (or not disabling) */ if (min_uV && !vreg->pdata->sleep_selectable) vreg->save_uV = min_uV; return rc; } #else static int ldo_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return ((vreg->req[0].value & LDO_VOLTAGE) >> LDO_VOLTAGE_SHIFT) != 0; } static int _ldo_set_voltage(struct regulator_dev *dev, int min_uV) { struct vreg *vreg = rdev_get_drvdata(dev); return vreg_set(vreg, LDO_VOLTAGE, MICRO_TO_MILLI(min_uV) << LDO_VOLTAGE_SHIFT, 0, 0, 2); } static int ldo_set_voltage(struct regulator_dev *dev, int min_uV, int max_uV) { struct vreg *vreg = rdev_get_drvdata(dev); int rc = 0; if (ldo_is_enabled(dev)) rc = _ldo_set_voltage(dev, min_uV); if (rc) return rc; /* only save if nonzero (or not disabling) */ if (min_uV && (!vreg->pdata->sleep_selectable || !ldo_is_enabled(dev))) vreg->save_uV = min_uV; return rc; } #endif #ifdef ES2P0_MIPI_FIX static int ldo_get_voltage(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return vreg->save_uV; } static int ldo_enable(struct regulator_dev *dev) { int rc = 0; struct vreg *vreg = rdev_get_drvdata(dev); /* enable by setting voltage */ if (MICRO_TO_MILLI(vreg->save_uV) > 0) rc = ldo_set_voltage(dev, vreg->save_uV, vreg->save_uV); return rc; } static int ldo_disable(struct regulator_dev *dev) { /* disable by setting voltage to zero */ return ldo_set_voltage(dev, 0, 0); } static int ldo_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return ((vreg->req[0].value & LDO_VOLTAGE) >> LDO_VOLTAGE_SHIFT) != 0; } #else static int ldo_get_voltage(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return vreg->save_uV; } static int ldo_enable(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); int rc = 0; unsigned mask, val; /* enable by setting voltage */ if (MICRO_TO_MILLI(vreg->save_uV) > 0) { /* reenable pin control if it is in use */ if (ldo_get_mode(dev) == REGULATOR_MODE_IDLE) { mask = LDO_PIN_CTRL | LDO_PIN_FN; val = vreg->pdata->pin_ctrl << LDO_PIN_CTRL_SHIFT | vreg->pdata->pin_fn << LDO_PIN_FN_SHIFT; vreg_store(vreg, mask, val, 0, 0); } rc = _ldo_set_voltage(dev, vreg->save_uV); } return rc; } static int ldo_disable(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned mask, val; /* turn off pin control */ mask = LDO_PIN_CTRL | LDO_PIN_FN; val = <API key> << LDO_PIN_CTRL_SHIFT | <API key> << LDO_PIN_FN_SHIFT; vreg_store(vreg, mask, val, 0, 0); /* disable by setting voltage to zero */ return _ldo_set_voltage(dev, 0); } #endif /* * Optimum mode programming: * REGULATOR_MODE_FAST: Go to HPM (highest priority) * <API key>: Go to pin ctrl mode if there are any pin ctrl * votes, else go to LPM * * Pin ctrl mode voting via regulator set_mode: * REGULATOR_MODE_IDLE: Go to pin ctrl mode if the optimum mode is LPM, else * go to HPM * <API key>: Go to LPM if it is the optimum mode, else go to HPM * * Pin ctrl mode takes priority on the RPM when force mode is not set; * therefore, pin ctrl bits must be cleared if LPM or HPM is being voted for. */ #ifdef ES2P0_MIPI_FIX static int ldo_set_mode(struct regulator_dev *dev, unsigned int mode) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned optimum = vreg->optimum; unsigned pc_vote = vreg->pc_vote; unsigned mode_initialized = vreg->mode_initialized; unsigned mask0 = 0, val0 = 0, mask1 = 0, val1 = 0; int set_hpm = -1, set_pin_control = -1; int peak_uA; int rc = 0; peak_uA = MILLI_TO_MICRO((vreg->req[0].value & LDO_PEAK_CURRENT) >> <API key>); switch (mode) { case REGULATOR_MODE_FAST: if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = LDO_PEAK_CURRENT; mask1 = LDO_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & LDO_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & LDO_AVG_CURRENT; } /* clear pin control */ mask0 |= LDO_PIN_CTRL; optimum = mode; mode_initialized = 1; break; case <API key>: if (peak_uA > vreg_lpm_max_uA(vreg)) { mask0 = LDO_PEAK_CURRENT; mask1 = LDO_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & LDO_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & LDO_AVG_CURRENT; } if (pc_vote) { mask0 |= LDO_PIN_CTRL; val0 |= vreg->pdata->pin_ctrl << LDO_PIN_CTRL_SHIFT; } else { /* clear pin control */ mask0 |= LDO_PIN_CTRL; } optimum = mode; mode_initialized = 1; break; case REGULATOR_MODE_IDLE: if (pc_vote++) goto done; /* already taken care of */ if (mode_initialized && optimum == REGULATOR_MODE_FAST) { set_hpm = 1; set_pin_control = 0; } else { set_pin_control = 1; } break; case <API key>: if (pc_vote && --pc_vote) goto done; /* already taken care of */ if (optimum == <API key>) { if (peak_uA > vreg_lpm_max_uA(vreg)) { mask0 = LDO_PEAK_CURRENT; mask1 = LDO_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & LDO_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & LDO_AVG_CURRENT; } } else { if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = LDO_PEAK_CURRENT; mask1 = LDO_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & LDO_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & LDO_AVG_CURRENT; } } /* clear pin control */ mask0 |= LDO_PIN_CTRL; break; default: return -EINVAL; } rc = vreg_set(rdev_get_drvdata(dev), mask0, val0, mask1, val1, 2); if (rc) return rc; done: vreg->mode_initialized = mode_initialized; vreg->optimum = optimum; vreg->pc_vote = pc_vote; return 0; } #else static int ldo_set_mode(struct regulator_dev *dev, unsigned int mode) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned optimum = vreg->optimum; unsigned pc_vote = vreg->pc_vote; unsigned mode_initialized = vreg->mode_initialized; unsigned mask0 = 0, val0 = 0, mask1 = 0, val1 = 0; int set_hpm = -1, set_pin_control = -1; int peak_uA; int rc = 0; peak_uA = MILLI_TO_MICRO((vreg->req[0].value & LDO_PEAK_CURRENT) >> <API key>); switch (mode) { case REGULATOR_MODE_FAST: set_hpm = 1; set_pin_control = 0; optimum = REGULATOR_MODE_FAST; mode_initialized = 1; break; case <API key>: set_hpm = 0; if (pc_vote) set_pin_control = 1; else set_pin_control = 0; optimum = <API key>; mode_initialized = 1; break; case REGULATOR_MODE_IDLE: if (pc_vote++) goto done; /* already taken care of */ if (mode_initialized && optimum == REGULATOR_MODE_FAST) { set_hpm = 1; set_pin_control = 0; } else { set_pin_control = 1; } break; case <API key>: if (pc_vote && --pc_vote) goto done; /* already taken care of */ if (optimum == <API key>) set_hpm = 0; else set_hpm = 1; set_pin_control = 0; break; default: return -EINVAL; } if (set_hpm == 1) { /* Make sure that request currents are at HPM level. */ if (peak_uA < vreg_hpm_min_uA(vreg)) { mask0 = LDO_PEAK_CURRENT; mask1 = LDO_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & LDO_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_hpm_min_uA(vreg)) << <API key>) & LDO_AVG_CURRENT; } } else if (set_hpm == 0) { /* Make sure that request currents are at LPM level. */ if (peak_uA > vreg_lpm_max_uA(vreg)) { mask0 = LDO_PEAK_CURRENT; mask1 = LDO_AVG_CURRENT; val0 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & LDO_PEAK_CURRENT; val1 = (MICRO_TO_MILLI(vreg_lpm_max_uA(vreg)) << <API key>) & LDO_AVG_CURRENT; } } if (set_pin_control == 1) { /* Enable pin control and pin function. */ mask0 |= LDO_PIN_CTRL | LDO_PIN_FN; val0 |= vreg->pdata->pin_ctrl << LDO_PIN_CTRL_SHIFT | vreg->pdata->pin_fn << LDO_PIN_FN_SHIFT; } else if (set_pin_control == 0) { /* Clear pin control and pin function*/ mask0 |= LDO_PIN_CTRL | LDO_PIN_FN; val0 |= <API key> << LDO_PIN_CTRL_SHIFT | <API key> << LDO_PIN_FN_SHIFT; } if (ldo_is_enabled(dev)) { rc = vreg_set(vreg, mask0, val0, mask1, val1, 2); } else { /* Regulator is disabled; store but don't send new request. */ rc = vreg_store(vreg, mask0, val0, mask1, val1); } if (rc) return rc; done: vreg->mode_initialized = mode_initialized; vreg->optimum = optimum; vreg->pc_vote = pc_vote; return 0; } #endif #ifdef ES2P0_MIPI_FIX static unsigned int ldo_get_mode(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); if (vreg->optimum == REGULATOR_MODE_FAST) return REGULATOR_MODE_FAST; else if (vreg->pc_vote) return REGULATOR_MODE_IDLE; else if (vreg->optimum == <API key>) return <API key>; return REGULATOR_MODE_FAST; } unsigned int <API key>(struct regulator_dev *dev, int input_uV, int output_uV, int load_uA) { struct vreg *vreg = rdev_get_drvdata(dev); if (MICRO_TO_MILLI(load_uA) > 0) { vreg->req[0].value &= ~LDO_PEAK_CURRENT; vreg->req[0].value |= (MICRO_TO_MILLI(saturate_load(load_uA)) << <API key>) & LDO_PEAK_CURRENT; vreg->req[1].value &= ~LDO_AVG_CURRENT; vreg->req[1].value |= (MICRO_TO_MILLI(saturate_load(load_uA)) << <API key>) & LDO_AVG_CURRENT; } else { /* * <API key> is being called before consumers have * specified their load currents via <API key>. * Return whatever the existing mode is. */ return ldo_get_mode(dev); } if (load_uA >= vreg->hpm_min_load) return REGULATOR_MODE_FAST; return <API key>; } static int switch_enable(struct regulator_dev *dev) { return vreg_set(rdev_get_drvdata(dev), SWITCH_STATE, RPM_VREG_STATE_ON << SWITCH_STATE_SHIFT, 0, 0, 1); } static int switch_disable(struct regulator_dev *dev) { return vreg_set(rdev_get_drvdata(dev), SWITCH_STATE, RPM_VREG_STATE_OFF << SWITCH_STATE_SHIFT, 0, 0, 1); } static int switch_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); enum rpm_vreg_state state; state = (vreg->req[0].value & SWITCH_STATE) >> SWITCH_STATE_SHIFT; return state == RPM_VREG_STATE_ON; } #else static unsigned int ldo_get_mode(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); if ((vreg->optimum == REGULATOR_MODE_FAST) && vreg->mode_initialized) return REGULATOR_MODE_FAST; else if (vreg->pc_vote) return REGULATOR_MODE_IDLE; else if (vreg->optimum == <API key>) return <API key>; return REGULATOR_MODE_FAST; } unsigned int <API key>(struct regulator_dev *dev, int input_uV, int output_uV, int load_uA) { struct vreg *vreg = rdev_get_drvdata(dev); if (MICRO_TO_MILLI(load_uA) > 0) { vreg->req[0].value &= ~LDO_PEAK_CURRENT; vreg->req[0].value |= (MICRO_TO_MILLI(saturate_load(load_uA)) << <API key>) & LDO_PEAK_CURRENT; vreg->req[1].value &= ~LDO_AVG_CURRENT; vreg->req[1].value |= (MICRO_TO_MILLI(saturate_load(load_uA)) << <API key>) & LDO_AVG_CURRENT; } else { /* * <API key> is being called before consumers have * specified their load currents via <API key>. * Return whatever the existing mode is. */ return ldo_get_mode(dev); } if (load_uA >= vreg->hpm_min_load) return REGULATOR_MODE_FAST; return <API key>; } static int switch_enable(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned mask = 0, val = 0; /* reenable pin control if it is in use */ if (switch_get_mode(dev) == REGULATOR_MODE_IDLE) { mask = SWITCH_PIN_CTRL | SWITCH_PIN_FN; val = vreg->pdata->pin_ctrl << <API key> | vreg->pdata->pin_fn << SWITCH_PIN_FN_SHIFT; } return vreg_set(rdev_get_drvdata(dev), SWITCH_STATE | mask, (RPM_VREG_STATE_ON << SWITCH_STATE_SHIFT) | val, 0, 0, 1); } static int switch_disable(struct regulator_dev *dev) { unsigned mask, val; /* turn off pin control */ mask = SWITCH_PIN_CTRL | SWITCH_PIN_FN; val = <API key> << <API key> | <API key> << SWITCH_PIN_FN_SHIFT; return vreg_set(rdev_get_drvdata(dev), SWITCH_STATE | mask, (RPM_VREG_STATE_OFF << SWITCH_STATE_SHIFT) | val, 0, 0, 1); } static int switch_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); enum rpm_vreg_state state; state = (vreg->req[0].value & SWITCH_STATE) >> SWITCH_STATE_SHIFT; return state == RPM_VREG_STATE_ON; } #endif /* * Pin ctrl mode voting via regulator set_mode: * REGULATOR_MODE_IDLE: Go to pin ctrl mode if the optimum mode is LPM, else * go to HPM * <API key>: Go to LPM if it is the optimum mode, else go to HPM */ #ifdef ES2P0_MIPI_FIX static int switch_set_mode(struct regulator_dev *dev, unsigned int mode) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned pc_vote = vreg->pc_vote; unsigned mask, val; int rc; switch (mode) { case REGULATOR_MODE_IDLE: if (pc_vote++) goto done; /* already taken care of */ mask = SWITCH_PIN_CTRL; val = vreg->pdata->pin_ctrl << <API key>; break; case <API key>: if (--pc_vote) goto done; /* already taken care of */ mask = SWITCH_PIN_CTRL; val = <API key> << <API key>; break; default: return -EINVAL; } rc = vreg_set(rdev_get_drvdata(dev), mask, val, 0, 0, 2); if (rc) return rc; done: vreg->pc_vote = pc_vote; return 0; } #else static int switch_set_mode(struct regulator_dev *dev, unsigned int mode) { struct vreg *vreg = rdev_get_drvdata(dev); unsigned pc_vote = vreg->pc_vote; unsigned mask, val; int rc; switch (mode) { case REGULATOR_MODE_IDLE: if (pc_vote++) goto done; /* already taken care of */ mask = SWITCH_PIN_CTRL | SWITCH_PIN_FN; val = vreg->pdata->pin_ctrl << <API key> | vreg->pdata->pin_fn << SWITCH_PIN_FN_SHIFT; break; case <API key>: if (--pc_vote) goto done; /* already taken care of */ mask = SWITCH_PIN_CTRL | SWITCH_PIN_FN; val = <API key> << <API key> | <API key> << SWITCH_PIN_FN_SHIFT; break; default: return -EINVAL; } if (switch_is_enabled(dev)) { rc = vreg_set(vreg, mask, val, 0, 0, 2); } else { /* Regulator is disabled; store but don't send new request. */ rc = vreg_store(vreg, mask, val, 0, 0); } if (rc) return rc; done: vreg->pc_vote = pc_vote; return 0; } #endif static unsigned int switch_get_mode(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); if (vreg->pc_vote) return REGULATOR_MODE_IDLE; return <API key>; } static int ncp_enable(struct regulator_dev *dev) { return vreg_set(rdev_get_drvdata(dev), NCP_STATE, RPM_VREG_STATE_ON << NCP_STATE_SHIFT, 0, 0, 2); } static int ncp_disable(struct regulator_dev *dev) { return vreg_set(rdev_get_drvdata(dev), NCP_STATE, RPM_VREG_STATE_OFF << NCP_STATE_SHIFT, 0, 0, 2); } static int ncp_is_enabled(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); enum rpm_vreg_state state; state = (vreg->req[0].value & NCP_STATE) >> NCP_STATE_SHIFT; return state == RPM_VREG_STATE_ON; } static int ncp_set_voltage(struct regulator_dev *dev, int min_uV, int max_uV) { return vreg_set(rdev_get_drvdata(dev), NCP_VOLTAGE, MICRO_TO_MILLI(min_uV) << NCP_VOLTAGE_SHIFT, 0, 0, 2); } static int ncp_get_voltage(struct regulator_dev *dev) { struct vreg *vreg = rdev_get_drvdata(dev); return MILLI_TO_MICRO((vreg->req[0].value & NCP_VOLTAGE) >> NCP_VOLTAGE_SHIFT); } static struct regulator_ops ldo_ops = { .enable = ldo_enable, .disable = ldo_disable, .is_enabled = ldo_is_enabled, .set_voltage = ldo_set_voltage, .get_voltage = ldo_get_voltage, .set_mode = ldo_set_mode, .get_optimum_mode = <API key>, .get_mode = ldo_get_mode, }; static struct regulator_ops smps_ops = { .enable = smps_enable, .disable = smps_disable, .is_enabled = smps_is_enabled, .set_voltage = smps_set_voltage, .get_voltage = smps_get_voltage, .set_mode = smps_set_mode, .get_optimum_mode = <API key>, .get_mode = smps_get_mode, }; #ifdef ES2P0_MIPI_FIX static struct regulator_ops smps_8901_ops = { .enable = smps_enable, .disable = smps_disable, .is_enabled = smps_is_enabled, .set_voltage = <API key>, .get_voltage = smps_get_voltage, .set_mode = smps_set_mode, .get_optimum_mode = <API key>, .get_mode = smps_get_mode, }; #endif static struct regulator_ops switch_ops = { .enable = switch_enable, .disable = switch_disable, .is_enabled = switch_is_enabled, .set_mode = switch_set_mode, .get_mode = switch_get_mode, }; static struct regulator_ops ncp_ops = { .enable = ncp_enable, .disable = ncp_disable, .is_enabled = ncp_is_enabled, .set_voltage = ncp_set_voltage, .get_voltage = ncp_get_voltage, }; #define DESC(_id, _name, _ops) \ [_id] = { \ .id = _id, \ .name = _name, \ .ops = _ops, \ .type = REGULATOR_VOLTAGE, \ .owner = THIS_MODULE, \ } static struct regulator_desc vreg_descrip[RPM_VREG_ID_MAX] = { DESC(<API key>, "8058_l0", &ldo_ops), DESC(<API key>, "8058_l1", &ldo_ops), DESC(<API key>, "8058_l2", &ldo_ops), DESC(<API key>, "8058_l3", &ldo_ops), DESC(<API key>, "8058_l4", &ldo_ops), DESC(<API key>, "8058_l5", &ldo_ops), DESC(<API key>, "8058_l6", &ldo_ops), DESC(<API key>, "8058_l7", &ldo_ops), DESC(<API key>, "8058_l8", &ldo_ops), DESC(<API key>, "8058_l9", &ldo_ops), DESC(<API key>, "8058_l10", &ldo_ops), DESC(<API key>, "8058_l11", &ldo_ops), DESC(<API key>, "8058_l12", &ldo_ops), DESC(<API key>, "8058_l13", &ldo_ops), DESC(<API key>, "8058_l14", &ldo_ops), DESC(<API key>, "8058_l15", &ldo_ops), DESC(<API key>, "8058_l16", &ldo_ops), DESC(<API key>, "8058_l17", &ldo_ops), DESC(<API key>, "8058_l18", &ldo_ops), DESC(<API key>, "8058_l19", &ldo_ops), DESC(<API key>, "8058_l20", &ldo_ops), DESC(<API key>, "8058_l21", &ldo_ops), DESC(<API key>, "8058_l22", &ldo_ops), DESC(<API key>, "8058_l23", &ldo_ops), DESC(<API key>, "8058_l24", &ldo_ops), DESC(<API key>, "8058_l25", &ldo_ops), DESC(<API key>, "8058_s0", &smps_ops), DESC(<API key>, "8058_s1", &smps_ops), DESC(<API key>, "8058_s2", &smps_ops), DESC(<API key>, "8058_s3", &smps_ops), DESC(<API key>, "8058_s4", &smps_ops), DESC(<API key>, "8058_lvs0", &switch_ops), DESC(<API key>, "8058_lvs1", &switch_ops), DESC(<API key>, "8058_ncp", &ncp_ops), DESC(<API key>, "8901_l0", &ldo_ops), DESC(<API key>, "8901_l1", &ldo_ops), DESC(<API key>, "8901_l2", &ldo_ops), DESC(<API key>, "8901_l3", &ldo_ops), DESC(<API key>, "8901_l4", &ldo_ops), DESC(<API key>, "8901_l5", &ldo_ops), DESC(<API key>, "8901_l6", &ldo_ops), #ifdef ES2P0_MIPI_FIX DESC(<API key>, "8901_s0", &smps_8901_ops), DESC(<API key>, "8901_s1", &smps_8901_ops), DESC(<API key>, "8901_s2", &smps_8901_ops), DESC(<API key>, "8901_s3", &smps_8901_ops), DESC(<API key>, "8901_s4", &smps_8901_ops), #else DESC(<API key>, "8901_s0", &smps_ops), DESC(<API key>, "8901_s1", &smps_ops), DESC(<API key>, "8901_s2", &smps_ops), DESC(<API key>, "8901_s3", &smps_ops), DESC(<API key>, "8901_s4", &smps_ops), #endif DESC(<API key>, "8901_lvs0", &switch_ops), DESC(<API key>, "8901_lvs1", &switch_ops), DESC(<API key>, "8901_lvs2", &switch_ops), DESC(<API key>, "8901_lvs3", &switch_ops), DESC(<API key>, "8901_mvs0", &switch_ops), }; #ifdef ES2P0_MIPI_FIX static void ldo_init(struct vreg *vreg) { vreg->req[0].value = MICRO_TO_MILLI(saturate_load(vreg->pdata->peak_uA)) << <API key> | vreg->pdata->mode << LDO_MODE_SHIFT | vreg->pdata->pin_fn << LDO_PIN_FN_SHIFT; vreg->req[1].value = vreg->pdata->pull_down_enable << <API key> | MICRO_TO_MILLI(saturate_load(vreg->pdata->avg_uA)) << <API key>; } static void smps_init(struct vreg *vreg) { vreg->req[0].value = MICRO_TO_MILLI(saturate_load(vreg->pdata->peak_uA)) << <API key> | vreg->pdata->mode << SMPS_MODE_SHIFT | vreg->pdata->pin_fn << SMPS_PIN_FN_SHIFT; vreg->req[1].value = vreg->pdata->pull_down_enable << <API key> | MICRO_TO_MILLI(saturate_load(vreg->pdata->avg_uA)) << <API key> | vreg->pdata->freq << SMPS_FREQ_SHIFT | 0 << SMPS_CLK_SRC_SHIFT; } #else static void ldo_init(struct vreg *vreg) { enum rpm_vreg_pin_fn pf = <API key>; /* Allow pf=sleep_b to be specified by platform data. */ if (vreg->pdata->pin_fn == <API key>) pf = <API key>; vreg->req[0].value = MICRO_TO_MILLI(saturate_load(vreg->pdata->peak_uA)) << <API key> | vreg->pdata->mode << LDO_MODE_SHIFT | pf << LDO_PIN_FN_SHIFT | <API key> << LDO_PIN_CTRL_SHIFT; vreg->req[1].value = vreg->pdata->pull_down_enable << <API key> | MICRO_TO_MILLI(saturate_load(vreg->pdata->avg_uA)) << <API key>; } static void smps_init(struct vreg *vreg) { enum rpm_vreg_pin_fn pf = <API key>; /* Allow pf=sleep_b to be specified by platform data. */ if (vreg->pdata->pin_fn == <API key>) pf = <API key>; vreg->req[0].value = MICRO_TO_MILLI(saturate_load(vreg->pdata->peak_uA)) << <API key> | vreg->pdata->mode << SMPS_MODE_SHIFT | pf << SMPS_PIN_FN_SHIFT | <API key> << SMPS_PIN_CTRL_SHIFT; vreg->req[1].value = vreg->pdata->pull_down_enable << <API key> | MICRO_TO_MILLI(saturate_load(vreg->pdata->avg_uA)) << <API key> | vreg->pdata->freq << SMPS_FREQ_SHIFT | 0 << SMPS_CLK_SRC_SHIFT; } #endif static void ncp_init(struct vreg *vreg) { vreg->req[0].value = vreg->pdata->state << NCP_STATE_SHIFT; } #ifdef ES2P0_MIPI_FIX static void switch_init(struct vreg *vreg) { vreg->req[0].value = vreg->pdata->state << SWITCH_STATE_SHIFT | vreg->pdata->pull_down_enable << <API key> | vreg->pdata->pin_fn << SWITCH_PIN_FN_SHIFT; } #else static void switch_init(struct vreg *vreg) { enum rpm_vreg_pin_fn pf = <API key>; /* Allow pf=sleep_b to be specified by platform data. */ if (vreg->pdata->pin_fn == <API key>) pf = <API key>; vreg->req[0].value = vreg->pdata->state << SWITCH_STATE_SHIFT | vreg->pdata->pull_down_enable << <API key> | pf << SWITCH_PIN_FN_SHIFT | <API key> << <API key>; } #endif static int vreg_init(enum rpm_vreg_id id, struct vreg *vreg) { vreg->save_uV = vreg->pdata->default_uV; if (vreg->pdata->peak_uA >= vreg->hpm_min_load) vreg->optimum = REGULATOR_MODE_FAST; else vreg->optimum = <API key>; vreg->mode_initialized = 0; if (IS_LDO(id)) ldo_init(vreg); else if (IS_SMPS(id)) smps_init(vreg); else if (IS_NCP(id)) ncp_init(vreg); else if (IS_SWITCH(id)) switch_init(vreg); else return -EINVAL; return 0; } #ifdef ES2P0_MIPI_FIX static int __devinit rpm_vreg_probe(struct platform_device *pdev) { struct regulator_desc *rdesc; struct regulator_dev *rdev; struct vreg *vreg; int rc; if (pdev == NULL) return -EINVAL; if (pdev->id < 0 || pdev->id >= RPM_VREG_ID_MAX) return -ENODEV; vreg = &vregs[pdev->id]; vreg->pdata = pdev->dev.platform_data; vreg->id = pdev->id; rdesc = &vreg_descrip[pdev->id]; rc = vreg_init(pdev->id, vreg); if (rc) { pr_err("%s: vreg_init failed, rc=%d\n", __func__, rc); return rc; } rdev = regulator_register(rdesc, &pdev->dev, &vreg->pdata->init_data, vreg); if (IS_ERR(rdev)) { rc = PTR_ERR(rdev); pr_err("%s: id=%d, rc=%d\n", __func__, pdev->id, rc); return rc; } <API key>(pdev, rdev); return rc; } #else static int __devinit rpm_vreg_probe(struct platform_device *pdev) { struct regulator_desc *rdesc; struct regulator_dev *rdev; struct vreg *vreg; int rc; if (pdev == NULL) return -EINVAL; if (pdev->id < 0 || pdev->id >= RPM_VREG_ID_MAX) return -ENODEV; vreg = &vregs[pdev->id]; vreg->pdata = pdev->dev.platform_data; vreg->id = pdev->id; rdesc = &vreg_descrip[pdev->id]; rc = vreg_init(pdev->id, vreg); if (rc) { pr_err("%s: vreg_init failed, rc=%d\n", __func__, rc); return rc; } /* Disallow idle and normal modes if pin control isn't set. */ if ((vreg->pdata->pin_ctrl == <API key>) && ((vreg->pdata->pin_fn == <API key>) || (vreg->pdata->pin_fn == <API key>))) vreg->pdata->init_data.constraints.valid_modes_mask &= ~(<API key> | REGULATOR_MODE_IDLE); rdev = regulator_register(rdesc, &pdev->dev, &vreg->pdata->init_data, vreg); if (IS_ERR(rdev)) { rc = PTR_ERR(rdev); pr_err("%s: id=%d, rc=%d\n", __func__, pdev->id, rc); return rc; } <API key>(pdev, rdev); return rc; } #endif static int __devexit rpm_vreg_remove(struct platform_device *pdev) { struct regulator_dev *rdev = <API key>(pdev); <API key>(pdev, NULL); <API key>(rdev); return 0; } static struct platform_driver rpm_vreg_driver = { .probe = rpm_vreg_probe, .remove = __devexit_p(rpm_vreg_remove), .driver = { .name = "rpm-regulator", .owner = THIS_MODULE, }, }; static int __init rpm_vreg_init(void) { return <API key>(&rpm_vreg_driver); } static void __exit rpm_vreg_exit(void) { <API key>(&rpm_vreg_driver); } postcore_initcall(rpm_vreg_init); module_exit(rpm_vreg_exit); #define <API key>(id) \ ((id == <API key>) || (id == <API key>)) static void print_rpm_request(struct vreg *vreg, int set) { int v, ip, fm, pc, pf, pd, ia, freq, clk, state; /* Suppress 8058_s0 and 8058_s1 printing. */ if ((<API key> & <API key>) && <API key>(vreg->id)) return; if (IS_LDO(vreg->id)) { v = (vreg->req[0].value & LDO_VOLTAGE) >> LDO_VOLTAGE_SHIFT; ip = (vreg->req[0].value & LDO_PEAK_CURRENT) >> <API key>; fm = (vreg->req[0].value & LDO_MODE) >> LDO_MODE_SHIFT; pc = (vreg->req[0].value & LDO_PIN_CTRL) >> LDO_PIN_CTRL_SHIFT; pf = (vreg->req[0].value & LDO_PIN_FN) >> LDO_PIN_FN_SHIFT; pd = (vreg->req[1].value & <API key>) >> <API key>; ia = (vreg->req[1].value & LDO_AVG_CURRENT) >> <API key>; pr_info("rpm-regulator: %s %-9s: s=%c, v=%4d mV, ip=%4d " "mA, fm=%s (%d), pc=%s%s%s%s%s (%d), pf=%s (%d), pd=%s " "(%d), ia=%4d mA; req[0]={%d, 0x%08X}, " "req[1]={%d, 0x%08X}\n", (set == MSM_RPM_CTX_SET_0 ? "sending " : "buffered"), vreg_descrip[vreg->id].name, (set == MSM_RPM_CTX_SET_0 ? 'A' : 'S'), v, ip, (fm == RPM_VREG_MODE_NONE ? "none" : (fm == RPM_VREG_MODE_LPM ? "LPM" : (fm == RPM_VREG_MODE_HPM ? "HPM" : ""))), fm, (pc & <API key> ? " A0" : ""), (pc & <API key> ? " A1" : ""), (pc & <API key> ? " D0" : ""), (pc & <API key> ? " D1" : ""), (pc == <API key> ? " none" : ""), pc, #ifdef ES2P0_MIPI_FIX (pf == <API key> ? "on/off" : (pf == <API key> ? "HPM/LPM" : "")), #else (pf == <API key> ? "none" : (pf == <API key> ? "on/off" : (pf == <API key> ? "HPM/LPM" : (pf == <API key> ? "sleep_b" : "")))), #endif pf, (pd == 1 ? "Y" : "N"), pd, ia, vreg->req[0].id, vreg->req[0].value, vreg->req[1].id, vreg->req[1].value); } else if (IS_SMPS(vreg->id)) { v = (vreg->req[0].value & SMPS_VOLTAGE) >> SMPS_VOLTAGE_SHIFT; ip = (vreg->req[0].value & SMPS_PEAK_CURRENT) >> <API key>; fm = (vreg->req[0].value & SMPS_MODE) >> SMPS_MODE_SHIFT; pc = (vreg->req[0].value & SMPS_PIN_CTRL) >> SMPS_PIN_CTRL_SHIFT; pf = (vreg->req[0].value & SMPS_PIN_FN) >> SMPS_PIN_FN_SHIFT; pd = (vreg->req[1].value & <API key>) >> <API key>; ia = (vreg->req[1].value & SMPS_AVG_CURRENT) >> <API key>; freq = (vreg->req[1].value & SMPS_FREQ) >> SMPS_FREQ_SHIFT; clk = (vreg->req[1].value & SMPS_CLK_SRC) >> SMPS_CLK_SRC_SHIFT; pr_info("rpm-regulator: %s %-9s: s=%c, v=%4d mV, ip=%4d " "mA, fm=%s (%d), pc=%s%s%s%s%s (%d), pf=%s (%d), pd=%s " "(%d), ia=%4d mA, freq=%2d, clk=%d; " "req[0]={%d, 0x%08X}, req[1]={%d, 0x%08X}\n", (set == MSM_RPM_CTX_SET_0 ? "sending " : "buffered"), vreg_descrip[vreg->id].name, (set == MSM_RPM_CTX_SET_0 ? 'A' : 'S'), v, ip, (fm == RPM_VREG_MODE_NONE ? "none" : (fm == RPM_VREG_MODE_LPM ? "LPM" : (fm == RPM_VREG_MODE_HPM ? "HPM" : ""))), fm, (pc & <API key> ? " A0" : ""), (pc & <API key> ? " A1" : ""), (pc & <API key> ? " D0" : ""), (pc & <API key> ? " D1" : ""), (pc == <API key> ? " none" : ""), pc, #ifdef ES2P0_MIPI_FIX (pf == <API key> ? "on/off" : (pf == <API key> ? "HPM/LPM" : "")), #else (pf == <API key> ? "none" : (pf == <API key> ? "on/off" : (pf == <API key> ? "HPM/LPM" : (pf == <API key> ? "sleep_b" : "")))), #endif pf, (pd == 1 ? "Y" : "N"), pd, ia, freq, clk, vreg->req[0].id, vreg->req[0].value, vreg->req[1].id, vreg->req[1].value); } else if (IS_SWITCH(vreg->id)) { state = (vreg->req[0].value & SWITCH_STATE) >> SWITCH_STATE_SHIFT; pd = (vreg->req[0].value & <API key>) >> <API key>; pc = (vreg->req[0].value & SWITCH_PIN_CTRL) >> <API key>; pf = (vreg->req[0].value & SWITCH_PIN_FN) >> SWITCH_PIN_FN_SHIFT; pr_info("rpm-regulator: %s %-9s: s=%c, state=%s (%d), " "pd=%s (%d), pc =%s%s%s%s%s (%d), pf=%s (%d); " "req[0]={%d, 0x%08X}\n", (set == MSM_RPM_CTX_SET_0 ? "sending " : "buffered"), vreg_descrip[vreg->id].name, (set == MSM_RPM_CTX_SET_0 ? 'A' : 'S'), (state == 1 ? "on" : "off"), state, (pd == 1 ? "Y" : "N"), pd, (pc & <API key> ? " A0" : ""), (pc & <API key> ? " A1" : ""), (pc & <API key> ? " D0" : ""), (pc & <API key> ? " D1" : ""), (pc == <API key> ? " none" : ""), pc, #ifdef ES2P0_MIPI_FIX (pf == <API key> ? "on/off" : (pf == <API key> ? "HPM/LPM" : "")), #else (pf == <API key> ? "none" : (pf == <API key> ? "on/off" : (pf == <API key> ? "HPM/LPM" : (pf == <API key> ? "sleep_b" : "")))), #endif pf, vreg->req[0].id, vreg->req[0].value); } else if (IS_NCP(vreg->id)) { v = (vreg->req[0].value & NCP_VOLTAGE) >> NCP_VOLTAGE_SHIFT; state = (vreg->req[0].value & NCP_STATE) >> NCP_STATE_SHIFT; pr_info("rpm-regulator: %s %-9s: s=%c, v=-%4d mV, " "state=%s (%d); req[0]={%d, 0x%08X}\n", (set == MSM_RPM_CTX_SET_0 ? "sending " : "buffered"), vreg_descrip[vreg->id].name, (set == MSM_RPM_CTX_SET_0 ? 'A' : 'S'), v, (state == 1 ? "on" : "off"), state, vreg->req[0].id, vreg->req[0].value); } } static void print_rpm_vote(struct vreg *vreg, enum rpm_vreg_voter voter, int set, int voter_mV, int aggregate_mV) { /* Suppress 8058_s0 and 8058_s1 printing. */ if ((<API key> & <API key>) && <API key>(vreg->id)) return; pr_info("rpm-regulator: vote received %-9s: voter=%d, set=%c, " "v_voter=%4d mV, v_aggregate=%4d mV\n", vreg_descrip[vreg->id].name, voter, (set == 0 ? 'A' : 'S'), voter_mV, aggregate_mV); } static void print_rpm_duplicate(struct vreg *vreg, int set, int cnt) { /* Suppress 8058_s0 and 8058_s1 printing. */ if ((<API key> & <API key>) && <API key>(vreg->id)) return; if (cnt == 2) pr_info("rpm-regulator: ignored duplicate request %-9s: set=%c;" " req[0]={%d, 0x%08X}, req[1]={%d, 0x%08X}\n", vreg_descrip[vreg->id].name, (set == 0 ? 'A' : 'S'), vreg->req[0].id, vreg->req[0].value, vreg->req[1].id, vreg->req[1].value); else if (cnt == 1) pr_info("rpm-regulator: ignored duplicate request %-9s: set=%c;" " req[0]={%d, 0x%08X}\n", vreg_descrip[vreg->id].name, (set == 0 ? 'A' : 'S'), vreg->req[0].id, vreg->req[0].value); } MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("rpm regulator driver"); MODULE_VERSION("1.0"); MODULE_ALIAS("platform:rpm-regulator");
#include <linux/config.h> #include <linux/module.h> #include <linux/kernel.h> #include <asm/arch/pxa-regs.h> #include <linux/init.h> #include <linux/pm.h> #include <asm/hardware.h> #include "generic.h" /* Crystal clock: 13MHz */ #define BASE_CLK 13000000 /* * Get the clock frequency as reflected by CCSR and the turbo flag. * We assume these values have been applied via a fcs. * If info is not 0 we also display the current settings. */ unsigned int <API key>( int info) { unsigned long ccsr, clkcfg; unsigned int l, L, m, M, n2, N, S; int cccr_a, t, ht, b; ccsr = CCSR; cccr_a = CCCR & (1 << 25); /* Read clkcfg register: it has turbo, b, half-turbo (and f) */ asm( "mrc\tp14, 0, %0, c6, c0, 0" : "=r" (clkcfg) ); t = clkcfg & (1 << 1); ht = clkcfg & (1 << 2); b = clkcfg & (1 << 3); l = ccsr & 0x1f; n2 = (ccsr>>7) & 0xf; m = (l <= 10) ? 1 : (l <= 20) ? 2 : 4; L = l * BASE_CLK; N = (L * n2) / 2; M = (!cccr_a) ? (L/m) : ((b) ? L : (L/2)); S = (b) ? L : (L/2); if (info) { printk( KERN_INFO "Run Mode clock: %d.%02dMHz (*%d)\n", L / 1000000, (L % 1000000) / 10000, l ); printk( KERN_INFO "Turbo Mode clock: %d.%02dMHz (*%d.%d, %sactive)\n", N / 1000000, (N % 1000000)/10000, n2 / 2, (n2 % 2)*5, (t) ? "" : "in" ); printk( KERN_INFO "Memory clock: %d.%02dMHz (/%d)\n", M / 1000000, (M % 1000000) / 10000, m ); printk( KERN_INFO "System bus clock: %d.%02dMHz \n", S / 1000000, (S % 1000000) / 10000 ); } return (t) ? (N/1000) : (L/1000); } /* * Return the current mem clock frequency in units of 10kHz as * reflected by CCCR[A], B, and L */ unsigned int <API key>(void) { unsigned long ccsr, clkcfg; unsigned int l, L, m, M; int cccr_a, b; ccsr = CCSR; cccr_a = CCCR & (1 << 25); /* Read clkcfg register: it has turbo, b, half-turbo (and f) */ asm( "mrc\tp14, 0, %0, c6, c0, 0" : "=r" (clkcfg) ); b = clkcfg & (1 << 3); l = ccsr & 0x1f; m = (l <= 10) ? 1 : (l <= 20) ? 2 : 4; L = l * BASE_CLK; M = (!cccr_a) ? (L/m) : ((b) ? L : (L/2)); return (M / 10000); } /* * Return the current LCD clock frequency in units of 10kHz as */ unsigned int <API key>(void) { unsigned long ccsr; unsigned int l, L, k, K; ccsr = CCSR; l = ccsr & 0x1f; k = (l <= 7) ? 1 : (l <= 16) ? 2 : 4; L = l * BASE_CLK; K = L / k; return (K / 10000); } EXPORT_SYMBOL(<API key>); EXPORT_SYMBOL(<API key>); EXPORT_SYMBOL(<API key>);
#ifndef GNC_CSV_MODEL_H #define GNC_CSV_MODEL_H #include "config.h" #include "Account.h" #include "Transaction.h" #include "stf/stf-parse.h" /** Enumeration for column types. These are the different types of * columns that can exist in a CSV/Fixed-Width file. There should be * no two columns with the same type except for the GNC_CSV_NONE * type. */ enum GncCsvColumnType {GNC_CSV_NONE, GNC_CSV_DATE, GNC_CSV_NUM, GNC_CSV_DESCRIPTION, GNC_CSV_NOTES, GNC_CSV_ACCOUNT, GNC_CSV_DEPOSIT, GNC_CSV_WITHDRAWAL, GNC_CSV_BALANCE, <API key> }; /** Enumeration for error types. These are the different types of * errors that various functions used for the CSV/Fixed-Width importer * can have. */ enum GncCsvErrorType {<API key>, <API key> }; /** Struct for containing a string. This struct simply contains * pointers to the beginning and end of a string. We need this because * the STF code that gnc_csv_parse calls requires these pointers. */ typedef struct { char* begin; char* end; } GncCsvStr; /* TODO We now sort transactions by date, not line number, so we * should probably get rid of this struct and uses of it. */ /** Struct pairing a transaction with a line number. This struct is * used to keep the transactions in order. When rows are separated * into "valid" and "error" lists (in case some of the rows have cells * that are unparseable), we want the user to still be able to * "correct" the error list. If we keep the line numbers of valid * transactions, we can then put transactions created from the newly * corrected rows into the right places. */ typedef struct { int line_no; Transaction* trans; gnc_numeric balance; /**< The (supposed) balance after this transaction takes place */ gboolean balance_set; /**< TRUE if balance has been set from user data, FALSE otherwise */ gchar *num; /**< Saves the 'num'for use if balance has been set from user data */ } GncCsvTransLine; /* A set of currency formats that the user sees. */ extern const int <API key>; extern const gchar* <API key>[]; /* A set of date formats that the user sees. */ extern const int num_date_formats; extern const gchar* date_format_user[]; /* This array contains all of the different strings for different column types. */ extern gchar* <API key>[]; /** Struct containing data for parsing a CSV/Fixed-Width file. */ typedef struct { gchar* encoding; GMappedFile* raw_mapping; /**< The mapping containing raw_str */ GncCsvStr raw_str; /**< Untouched data from the file as a string */ GncCsvStr file_str; /**< raw_str translated into UTF-8 */ GPtrArray* orig_lines; /**< file_str parsed into a two-dimensional array of strings */ GArray* orig_row_lengths; /**< The lengths of rows in orig_lines before error messages are appended */ int orig_max_row; /**< Holds the maximum value in orig_row_lengths */ GStringChunk* chunk; /**< A chunk of memory in which the contents of orig_lines is stored */ StfParseOptions_t* options; /**< Options controlling how file_str should be parsed */ GArray* column_types; /**< Array of values from the GncCsvColumnType enumeration */ GList* error_lines; /**< List of row numbers in orig_lines that have errors */ GList* transactions; /**< List of GncCsvTransLine*s created using orig_lines and column_types */ int date_format; /**< The format of the text in the date columns from <API key>. */ int start_row; /**< The start row to generate transactions from. */ int end_row; /**< The end row to generate transactions from. */ gboolean skip_rows; /**< Skip Alternate Rows from start row. */ int currency_format; /**< The currency format, 0 for locale, 1 for comma dec and 2 for period */ } GncCsvParseData; GncCsvParseData* <API key> (void); void <API key> (GncCsvParseData* parse_data); int gnc_csv_load_file (GncCsvParseData* parse_data, const char* filename, GError** error); int <API key> (GncCsvParseData* parse_data, const char* encoding, GError** error); int gnc_csv_parse (GncCsvParseData* parse_data, gboolean guessColTypes, GError** error); int <API key> (GncCsvParseData* parse_data, Account* account, gboolean redo_errors); time64 parse_date (const char* date_str, int format); #endif
/* * @file netsnmp_data_list.h * * @addtogroup agent * @addtogroup library * * * $Id: data_list.h 16926 2008-05-10 09:30:39Z magfr $ * * External definitions for functions and variables in netsnmp_data_list.c. * * @{ */ #ifndef DATA_LIST_H #define DATA_LIST_H #ifdef __cplusplus extern "C" { #endif #include <net-snmp/library/snmp_impl.h> #include <net-snmp/library/tools.h> typedef void (<API key>) (void *); typedef int (<API key>) (char *buf, size_t buf_len, void *); typedef void * (<API key>) (char *buf, size_t buf_len); /** @struct netsnmp_data_list_s * used to iterate through lists of data */ typedef struct netsnmp_data_list_s { struct netsnmp_data_list_s *next; char *name; /** The pointer to the data passed on. */ void *data; /** must know how to free netsnmp_data_list->data */ <API key> *free_func; } netsnmp_data_list; typedef struct <API key> { netsnmp_data_list **datalist; const char *type; const char *token; <API key> *data_list_save_ptr; <API key> *data_list_read_ptr; <API key> *data_list_free_ptr; } <API key>; netsnmp_data_list * <API key>(const char *, void *, <API key>* ); void <API key>(netsnmp_data_list **head, netsnmp_data_list *node); netsnmp_data_list * <API key>(netsnmp_data_list **head, const char *name, void *data, <API key> * beer); void *<API key>(netsnmp_data_list *head, const char *node); void <API key>(netsnmp_data_list *head); /* single */ void <API key>(netsnmp_data_list *head); /* multiple */ int <API key>(netsnmp_data_list **realhead, const char *name); netsnmp_data_list * <API key>(netsnmp_data_list *head, const char *name); /** depreciated: use <API key>() */ void <API key>(netsnmp_data_list **head, netsnmp_data_list *node); void <API key>(netsnmp_data_list **datalist, const char *type, const char *token, <API key> *data_list_save_ptr, <API key> *data_list_read_ptr, <API key> *data_list_free_ptr); int <API key>(netsnmp_data_list *head, const char *type, const char *token, <API key> * data_list_save_ptr); SNMPCallback <API key>; void <API key>(const char *token, char *line); #ifdef __cplusplus } #endif #endif
#!/bin/sh test_description='our own option parser' . ./test-lib.sh cat > expect << EOF usage: test-parse-options <options> -b, --boolean get a boolean -4, --or4 bitwise-or boolean with ...0100 --neg-or4 same as --no-or4 -i, --integer <n> get a integer -j <n> get a integer, too --set23 set integer to 23 -t <time> get timestamp of <time> -L, --length <str> get length of <str> -F, --file <file> set file to <file> String options -s, --string <string> get a string --string2 <str> get another string --st <st> get another string (pervert ordering) -o <str> get another string --default-string set string to default --list <str> add str to list Magic arguments --quux means --quux -NUM set integer to NUM + same as -b --ambiguous positive ambiguity --no-ambiguous negative ambiguity Standard options --abbrev[=<n>] use <n> digits to display SHA-1s -v, --verbose be verbose -n, --dry-run dry run -q, --quiet be quiet EOF test_expect_success 'test help' ' test_must_fail test-parse-options -h > output 2> output.err && test ! -s output.err && test_cmp expect output ' mv expect expect.err cat > expect << EOF boolean: 2 integer: 1729 timestamp: 0 string: 123 abbrev: 7 verbose: 2 quiet: no dry run: yes file: prefix/my.file EOF test_expect_success 'short options' ' test-parse-options -s123 -b -i 1729 -b -vv -n -F my.file \ > output 2> output.err && test_cmp expect output && test ! -s output.err ' cat > expect << EOF boolean: 2 integer: 1729 timestamp: 0 string: 321 abbrev: 10 verbose: 2 quiet: no dry run: no file: prefix/fi.le EOF test_expect_success 'long options' ' test-parse-options --boolean --integer 1729 --boolean --string2=321 \ --verbose --verbose --no-dry-run --abbrev=10 --file fi.le\ > output 2> output.err && test ! -s output.err && test_cmp expect output ' test_expect_success 'missing required value' ' test-parse-options -s; test $? = 129 && test-parse-options --string; test $? = 129 && test-parse-options --file; test $? = 129 ' cat > expect << EOF boolean: 1 integer: 13 timestamp: 0 string: 123 abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) arg 00: a1 arg 01: b1 arg 02: --boolean EOF test_expect_success 'intermingled arguments' ' test-parse-options a1 --string 123 b1 --boolean -j 13 -- --boolean \ > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > expect << EOF boolean: 0 integer: 2 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'unambiguously abbreviated option' ' test-parse-options --int 2 --boolean --no-bo > output 2> output.err && test ! -s output.err && test_cmp expect output ' test_expect_success 'unambiguously abbreviated option with "="' ' test-parse-options --int=2 > output 2> output.err && test ! -s output.err && test_cmp expect output ' test_expect_success 'ambiguously abbreviated option' ' test-parse-options --strin 123; test $? = 129 ' cat > expect << EOF boolean: 0 integer: 0 timestamp: 0 string: 123 abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'non ambiguous option (after two options it abbreviates)' ' test-parse-options --st 123 > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > typo.err << EOF error: did you mean \`--boolean\` (with two dashes ?) EOF test_expect_success 'detect possible typos' ' test_must_fail test-parse-options -boolean > output 2> output.err && test ! -s output && test_cmp typo.err output.err ' cat > expect <<EOF boolean: 0 integer: 0 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) arg 00: --quux EOF test_expect_success 'keep some options as arguments' ' test-parse-options --quux > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > expect <<EOF boolean: 0 integer: 0 timestamp: 1 string: default abbrev: 7 verbose: 0 quiet: yes dry run: no file: (not set) arg 00: foo EOF test_expect_success 'OPT_DATE() and OPT_SET_PTR() work' ' test-parse-options -t "1970-01-01 00:00:01 +0000" --default-string \ foo -q > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > expect <<EOF Callback: "four", 0 boolean: 5 integer: 4 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'OPT_CALLBACK() and OPT_BIT() work' ' test-parse-options --length=four -b -4 > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > expect <<EOF Callback: "not set", 1 EOF test_expect_success 'OPT_CALLBACK() and callback errors work' ' test_must_fail test-parse-options --no-length > output 2> output.err && test_cmp expect output && test_cmp expect.err output.err ' cat > expect <<EOF boolean: 1 integer: 23 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'OPT_BIT() and OPT_SET_INT() work' ' test-parse-options --set23 -bbbbb --no-or4 > output 2> output.err && test ! -s output.err && test_cmp expect output ' test_expect_success 'OPT_NEGBIT() and OPT_SET_INT() work' ' test-parse-options --set23 -bbbbb --neg-or4 > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > expect <<EOF boolean: 6 integer: 0 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'OPT_BIT() works' ' test-parse-options -bb --or4 > output 2> output.err && test ! -s output.err && test_cmp expect output ' test_expect_success 'OPT_NEGBIT() works' ' test-parse-options -bb --no-neg-or4 > output 2> output.err && test ! -s output.err && test_cmp expect output ' test_expect_success 'OPT_BOOLEAN() with PARSE_OPT_NODASH works' ' test-parse-options + + + + + + > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat > expect <<EOF boolean: 0 integer: 12345 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'OPT_NUMBER_CALLBACK() works' ' test-parse-options -12345 > output 2> output.err && test ! -s output.err && test_cmp expect output ' cat >expect <<EOF boolean: 0 integer: 0 timestamp: 0 string: (not set) abbrev: 7 verbose: 0 quiet: no dry run: no file: (not set) EOF test_expect_success 'negation of OPT_NONEG flags is not ambiguous' ' test-parse-options --no-ambig >output 2>output.err && test ! -s output.err && test_cmp expect output ' cat >>expect <<'EOF' list: foo list: bar list: baz EOF test_expect_success '--list keeps list of strings' ' test-parse-options --list foo --list=bar --list=baz >output && test_cmp expect output ' test_expect_success '--no-list resets list' ' test-parse-options --list=other --list=irrelevant --list=options \ --no-list --list=foo --list=bar --list=baz >output && test_cmp expect output ' test_done
<?php session_start(); /////////////////////////////////////////// SEGURIDAD ///////////////////////////////////////////// if(!array_key_exists("la_logusr",$_SESSION)) { print "<script language=JavaScript>"; print "location.href='../<API key>.php'"; print "</script>"; } $ls_logusr=$_SESSION["la_logusr"]; require_once("class_folder/class_funciones_cxp.php"); $io_fun_cxp=new class_funciones_cxp(); $io_fun_cxp->uf_load_seguridad("CXP","<API key>.php",$ls_permisos,$la_seguridad,$la_permisos); /////////////////////////////////////////// SEGURIDAD ///////////////////////////////////////////// function uf_limpiarvariables() { // Function: uf_limpiarvariables // Access: private // Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang global $ls_estatus,$ls_dirsujret,$ls_nomsujret,$ls_operacion,$ls_existe,$ls_codret,$ls_mes,$ls_indice; global $<API key>,$io_fun_cxp,$ls_numcom,$ls_parametros,$ls_rif,$ls_ano,$ls_codigo; $ls_estatus="EMITIDO"; $ls_numcom=""; $ls_ano=""; $ls_mes=""; $ls_codigo=""; $ls_rif=""; $ls_nomsujret=""; $ls_dirsujret=""; $ls_codret=""; $ls_indice=""; $ls_parametros=""; $ls_operacion=$io_fun_cxp->uf_obteneroperacion(); $ls_existe=$io_fun_cxp->uf_obtenerexiste(); $<API key>=0; } function uf_load_variables() { // Function: uf_load_variables // Access: private // Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang global $ls_estsol,$ls_numcom,$ls_ano,$ls_mes,$ls_codigo,$ls_rif,$ls_nomsujret,$ls_dirsujret,$ls_codret,$ls_probene; global $io_fun_cxp,$<API key>,$ls_indice; $ls_estsol=$_POST["txtestatus"]; $ls_numcom=$_POST["txtnumcom"]; $ls_mes=$_POST["cmbmes"]; $ls_ano=$_POST["txtano"]; $ls_codigo=$_POST["txtcodigo"]; $ls_rif=$_POST["txtrif"]; $ls_nomsujret=$_POST["txtnomsujret"]; $ls_dirsujret=$_POST["txtdirsujret"]; $ls_codret=$_POST["cmbtipo"]; $ls_probene=$_POST["txtprobene"]; $ls_indice=$_POST["txtindice"]; $<API key>=$_POST["totrowrecepciones"]; } function uf_load_data(&$as_parametros) { // Function: uf_load_variables // Access: private // Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang global $<API key>,$io_fun_cxp; for($li_i=1;$li_i<$<API key>;$li_i++) { $ls_codret=trim($io_fun_cxp->uf_obtenervalor("txtcodret".$li_i,"")); $ls_numope=trim($io_fun_cxp->uf_obtenervalor("txtnumope".$li_i,"")); $ls_fecfac=trim($io_fun_cxp->uf_obtenervalor("txtfecfac".$li_i,"")); $ls_numfac=trim($io_fun_cxp->uf_obtenervalor("txtnumfac".$li_i,"")); $ls_numcon=trim($io_fun_cxp->uf_obtenervalor("txtnumcon".$li_i,"")); $ls_numnd=trim($io_fun_cxp->uf_obtenervalor("txtnumnd".$li_i,"")); $ls_numnc=trim($io_fun_cxp->uf_obtenervalor("txtnumnc".$li_i,"")); $ls_tiptrans=trim($io_fun_cxp->uf_obtenervalor("txttiptrans".$li_i,"")); $ls_tot_cmp_sin_iva=trim($io_fun_cxp->uf_obtenervalor("txttotsiniva".$li_i,"")); $ls_tot_cmp_con_iva=trim($io_fun_cxp->uf_obtenervalor("txttotconiva".$li_i,"")); $ls_basimp=trim($io_fun_cxp->uf_obtenervalor("txtbasimp".$li_i,"")); $ls_porimp=trim($io_fun_cxp->uf_obtenervalor("txtporimp".$li_i,"")); $ls_totimp=trim($io_fun_cxp->uf_obtenervalor("txttotimp".$li_i,"")); $ls_ivaret=trim($io_fun_cxp->uf_obtenervalor("txtivaret".$li_i,"")); $ls_numsop=trim($io_fun_cxp->uf_obtenervalor("txtnumsop".$li_i,"")); $ls_numdoc=trim($io_fun_cxp->uf_obtenervalor("txtnumdoc".$li_i,"")); $as_parametros=$as_parametros."&txtcodret".$li_i."=".$ls_codret."&txtnumope".$li_i."=".$ls_numope."&txtfecfac".$li_i."=".$ls_fecfac. "&txtnumfac".$li_i."=".$ls_numfac."&txtnumcon".$li_i."=".$ls_numcon."&txtnumnd".$li_i."=".$ls_numnd. "&txtnumnc".$li_i."=".$ls_numnc."&txttiptrans".$li_i."=".$ls_tiptrans."&txttotsiniva".$li_i."=".$ls_tot_cmp_sin_iva. "&txttotconiva".$li_i."=".$ls_tot_cmp_con_iva."&txtbasimp".$li_i."=".$ls_basimp."&txtporimp".$li_i."=".$ls_porimp. "&txttotimp".$li_i."=".$ls_totimp."&txtivaret".$li_i."=".$ls_ivaret."&txtnumsop".$li_i."=".$ls_numsop. "&txtnumdoc".$li_i."=".$ls_numdoc; } $as_parametros=$as_parametros."&totrowrecepciones=".$<API key>.""; } ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Comprobante de Retencion</title> <meta http-equiv="" content="text/html; charset=iso-8859-1"> <meta http-equiv="" content="text/html; charset=iso-8859-1"> <script type="text/javascript" language="JavaScript1.2" src="js/stm31.js"></script> <script type="text/javascript" language="JavaScript1.2" src="js/funcion_cxp.js"></script> <script type="text/javascript" language="JavaScript1.2" src="../shared/js/valida_tecla.js"></script> <script type="text/javascript" language="javascript" src="../shared/js/number_format.js"></script> <script type="text/javascript" language="JavaScript1.2" src="../shared/js/disabled_keys.js"></script> <meta http-equiv="" content="text/html; charset=iso-8859-1"><meta http-equiv="" content="text/html; charset=iso-8859-1"> <link href="../shared/css/cabecera.css" rel="stylesheet" type="text/css"> <link href="../shared/css/general.css" rel="stylesheet" type="text/css"> <link href="../shared/css/tablas.css" rel="stylesheet" type="text/css"> <link href="../shared/css/ventanas.css" rel="stylesheet" type="text/css"> <script language="javascript"> if(document.all) { document.onkeydown = function(){ if(window.event && (window.event.keyCode == 122 || window.event.keyCode == 116 || window.event.ctrlKey)) { window.event.keyCode = 505; } if(window.event.keyCode == 505){ return false;} } } </script> <meta http-equiv="Content-Type" content="text/html; charset="><style type="text/css"> <! a:link { color: #006699; } a:visited { color: #006699; } a:hover { color: #006699; } a:active { color: #006699; } </style> <link href="../shared/js/css_intra/datepickercontrol.css" rel="stylesheet" type="text/css"> <link href="css/cxp.css" rel="stylesheet" type="text/css"> <style type="text/css"> <! .style1 {font-weight: bold} </style></head> <body> <?php require_once("../shared/class_folder/class_mensajes.php"); $io_msg=new class_mensajes(); require_once("class_folder/<API key>.php"); $io_cmpret=new <API key>("../"); require_once("class_folder/<API key>.php"); $io_modcmpret=new <API key>("../"); require_once("../shared/class_folder/sigesp_include.php"); $in= new sigesp_include(); $con= $in->uf_conectar(); require_once("../shared/class_folder/class_sql.php"); $io_sql= new class_sql($con); $ls_basdatcmp=$_SESSION["la_empresa"]["basdatcmp"]; if($ls_basdatcmp!="") { $io_modcmpret->io_sqlaux=$io_cmpret->io_sqlaux; $io_sqlaux=$io_cmpret->io_sqlaux; } uf_limpiarvariables(); $ls_basdatcmp=$_SESSION["la_empresa"]["basdatcmp"]; switch($ls_operacion) { case "NEW": uf_load_variables(); $ls_ano=date('Y'); $ls_mes=date('m'); $io_cmpret-><API key>($ls_codret,$ls_ano.$ls_mes,&$ls_numcom); uf_load_data(&$ls_parametros); break; case "GUARDAR": uf_load_variables(); $io_sql->begin_transaction(); $lb_flag=true; if($ls_existe=="FALSE") { $ls_fecha=date('Y-m-d'); if($ls_basdatcmp!="") { $lb_flag=$io_cmpret-><API key>($ls_codret,&$ls_numcom,$ls_fecha,$ls_ano.$ls_mes,$ls_codigo, $ls_nomsujret,$ls_dirsujret,$ls_rif,"","1",$ls_logusr,"", "M",$la_seguridad); } $lb_flag=$io_cmpret-><API key>($ls_codret,$ls_numcom,$ls_fecha,$ls_ano.$ls_mes,$ls_codigo,$ls_nomsujret, $ls_dirsujret,$ls_rif,"","1",$ls_logusr,"","M",$la_seguridad); } if($lb_flag) { // $lb_flag=$io_modcmpret->uf_liberar_rd($ls_codret,$ls_probene,$ls_codigo,$<API key>); $lb_flag=$io_modcmpret-><API key>($ls_codret,$ls_numcom,$ls_probene,$ls_codigo); } if($lb_flag) { $lb_flag=$io_modcmpret->uf_update_cmpret($ls_numcom,$ls_codret, $<API key>,$ls_probene,$ls_codigo, $la_seguridad); } // $lb_flag=false; if($lb_flag) { $io_msg->message("El comprobante se proceso satisfactoriamente"); $io_sql->commit(); } else { $io_msg->message("Ocurrio un error al procesar el comprobante"); $io_sql->rollback(); } uf_load_data(&$ls_parametros); break; case "ELIMINAR": uf_load_variables(); $io_sql->begin_transaction(); $ls_bdorigen=$io_modcmpret->uf_obtener_bdorigen($ls_numcom,$ls_codret); $lb_ulitmo=$io_modcmpret->uf_buscar_ultimo($ls_numcom,$ls_codret); if(($lb_ulitmo)&&($ls_bdorigen=="")) { $lb_flag=$io_modcmpret->uf_delete_cmpret($ls_numcom,$ls_codret,$la_seguridad); if($lb_flag) { $lb_flag=$io_modcmpret->uf_liberar_rd($ls_codret,$ls_probene,$ls_codigo,$<API key>); if($lb_flag) { $io_msg->message("El comprobante fue eliminado fisicamente, por ser el último registro!!"); $io_sql->commit(); uf_limpiarvariables(); } else { $io_msg->message("Se genero un problema al eliminar la retencion"); uf_limpiarvariables(); $io_sql->rollback(); } } } else { $lb_valido=$io_modcmpret->uf_anular_cmpret($ls_numcom,$la_seguridad); if(($lb_valido)&&($ls_bdorigen!="")) { $lb_valido=$io_modcmpret-><API key>($ls_codret,$ls_numcom,$ls_probene,$ls_codigo); } if($lb_valido) { $lb_valido=$io_modcmpret->uf_liberar_rd($ls_codret,$ls_probene,$ls_codigo,$<API key>); } if($lb_valido) { $io_msg->message("El comprobante fue anulado, ya que no es el ultimo registro!!"); uf_limpiarvariables(); $io_sql->commit(); } else { $io_msg->message("Se genero un problema al anular la retencion"); uf_limpiarvariables(); $io_sql->rollback(); } } uf_load_data(&$ls_parametros); break; } ?> <table width="799" border="0" align="center" cellpadding="0" cellspacing="0" class="contorno"> <tr> <td height="30" colspan="11" class="cd-logo"><img src="../shared/imagebank/header.jpg" width="808" height="40"></td> </tr> <tr> <td height="20" colspan="11" bgcolor="#E7E7E7"><table width="762" border="0" align="center" cellpadding="0" cellspacing="0"> <td width="432" height="20" bgcolor="#E7E7E7" class="descripcion_sistema">Cuentas por Pagar </td> <td width="346" bgcolor="#E7E7E7"><div align="right"><span class="letras-peque&ntilde;as"><b><?PHP print date("j/n/Y")." - ".date("h:i a");?></b></span></div></td> <tr> <td height="20" bgcolor="#E7E7E7" class="descripcion_sistema">&nbsp;</td> <td bgcolor="#E7E7E7"><div align="right" class="letras-pequenas"><b><?php print $_SESSION["la_nomusu"]." ".$_SESSION["la_apeusu"];?></b></div></td> </table></td> </tr> <tr> <td height="20" colspan="11" bgcolor="#E7E7E7" class="cd-menu"><script type="text/javascript" language="JavaScript1.2" src="js/menu.js"></script></td> </tr> <tr> <td height="13" colspan="11" class="toolbar"></td> </tr> <tr> <td height="20" width="29" class="toolbar"><div align="center"><a href="javascript: ue_nuevo();"><img src="../shared/imagebank/tools20/nuevo.gif" alt="Nuevo" width="20" height="20" border="0" title="Nuevo"></a></div></td> <td class="toolbar" width="29"><div align="center"><a href="javascript: ue_guardar();"><img src="../shared/imagebank/tools20/grabar.gif" alt="Grabar" width="20" height="20" border="0" title="Guardar"></a></div></td> <td class="toolbar" width="29"><div align="center"><a href="javascript: ue_buscar();"><img src="../shared/imagebank/tools20/buscar.gif" alt="Buscar" width="20" height="20" border="0" title="Buscar"></a></div></td> <td class="toolbar" width="29"><div align="center"><a href="javascript: ue_eliminar();"><img src="../shared/imagebank/tools20/eliminar.gif" alt="Eliminar" width="20" height="20" border="0" title="Eliminar"></a></div></td> <td class="toolbar" width="29"><a href="javascript: ue_imprimir();"><img src="../shared/imagebank/tools20/imprimir.gif" alt="Imprimir" width="20" height="20" border="0" title="Imprimir"></a></td> <td class="toolbar" width="29"><div align="center"><a href="javascript: ue_cerrar();"><img src="../shared/imagebank/tools20/salir.gif" alt="Salir" width="20" height="20" border="0" title="Salir"></a></div></td> <td class="toolbar" width="29"><div align="center"><a href="javascript: ue_ayuda();"><img src="../shared/imagebank/tools20/ayuda.gif" alt="Ayuda" width="20" height="20" border="0" title="Ayuda"></a></div></td> <td class="toolbar" width="594">&nbsp;</td> </tr> </table> <p>&nbsp;</p> <form name="formulario" method="post" action="" id="formulario"> <?php /////////////////////////////////////////// SEGURIDAD ///////////////////////////////////////////// $io_fun_cxp->uf_print_permisos($ls_permisos,$la_permisos,$ls_logusr,"location.href='sigespwindow_blank.php'"); unset($io_fun_cxp); /////////////////////////////////////////// SEGURIDAD ///////////////////////////////////////////// ?> <table width="726" border="0" align="center" cellpadding="0" cellspacing="0" class="formato-blanco"> <tr> <td width="790" height="136"><p>&nbsp;</p> <table width="721" border="0" align="center" cellpadding="0" cellspacing="0" class="formato-blanco"> <tr> <td colspan="4" class="titulo-ventana"> Comprobante de Retenci&oacute;n </td> </tr> <tr> <td height="22">&nbsp;</td> <td height="22">&nbsp;</td> <td height="22">&nbsp;</td> <td height="22">&nbsp;</td> </tr> <tr> <td width="147" height="22"><div align="right">Periodo</div></td> <td width="240" height="22"><label> <select name="cmbmes" id="cmbmes"> <option value="01" <?php if($ls_mes=="01"){ print "selected";} ?>>ENERO</option> <option value="02" <?php if($ls_mes=="02"){ print "selected";} ?>>FEBRERO</option> <option value="03" <?php if($ls_mes=="03"){ print "selected";} ?>>MARZO</option> <option value="04" <?php if($ls_mes=="04"){ print "selected";} ?>>ABRIL</option> <option value="05" <?php if($ls_mes=="05"){ print "selected";} ?>>MAYO</option> <option value="06" <?php if($ls_mes=="06"){ print "selected";} ?>>JUNIO</option> <option value="07" <?php if($ls_mes=="07"){ print "selected";} ?>>JULIO</option> <option value="08" <?php if($ls_mes=="08"){ print "selected";} ?>>AGOSTO</option> <option value="09" <?php if($ls_mes=="09"){ print "selected";} ?>>SEPTIEMBRE</option> <option value="10" <?php if($ls_mes=="10"){ print "selected";} ?>>OCTUBRE</option> <option value="11" <?php if($ls_mes=="11"){ print "selected";} ?>>NOVIEMBRE</option> <option value="12" <?php if($ls_mes=="12"){ print "selected";} ?>>DICIEMBRE</option> </select> <input name="txtano" type="text" id="txtano" size="10" maxlength="4" value="<?php print $ls_ano?>"> </label></td> <td width="142" height="22"><div align="right">Estatus</div></td> <td width="190" height="22"><input name="txtestatus" type="text" class="sin-borde2" id="txtestatus" value="<?php print $ls_estatus; ?>" size="20" readonly></td> </tr> <tr> <td height="22" align="right">Comprobante </td> <td height="22" align="left"><input name="txtnumcom" type="text" id="txtnumcom" value="<?php print $ls_numcom; ?>" readonly></td> <td height="22" align="right">Tipo</td> <td height="22" align="right"><div align="left"> <label> <select name="cmbtipo" size="1" id="cmbtipo" onChange="javascript: ue_nuevo();"> <?php if($ls_modageret=$_SESSION["la_empresa"]["estretiva"]!="B"){?> <option value="0000000001" <?php if($ls_codret=="0000000001"){ print "selected";} ?>>IVA</option> <?php }if($ls_modageret=$_SESSION["la_empresa"]["modageret"]!="B"){?> <option value="0000000003" <?php if($ls_codret=="0000000003"){ print "selected";} ?>>Municipal</option> <?php }?> <option value="0000000004" <?php if($ls_codret=="0000000004"){ print "selected";} ?>>Aporte Social</option> </select> </label> </div></td> </tr> <tr> <td height="13">&nbsp;</td> <td colspan="3">&nbsp;</td> </tr> <tr> <td height="13" colspan="4"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="formato-blanco"> <tr> <td colspan="4" class="titulo-ventana">Sujeto Retenci&oacute;n</td> </tr> <tr> <td height="22" colspan="4"><?php if($ls_operacion=="NEW") { print"<div align=center>Proveedor <input name=estprov type=radio value=P> Beneficiario <input name=estprov type=radio value=B> </div>"; } ?></td> </tr> <tr> <td width="19%" height="25"><div align="right">Codigo</div></td> <td width="24%"><div align="left"> <label> <input name="txtcodigo" type="text" id="txtcodigo" value="<?php print $ls_codigo?>" readonly> <?php if($ls_operacion=="NEW") { print"<a href=javascript:uf_catalogo_proben('D');><img src=../shared/imagebank/tools15/buscar.gif name=buscar1 width=15 height=15 border=0 id=buscar1 onClick=document.form1.hidrangocodigos.value=1></a>"; } ?> </label> </div></td> <td width="25%"><div align="right">Rif</div></td> <td width="32%"><label> <input name="txtrif" type="text" id="txtrif" value="<?php print $ls_rif?>" readonly> </label></td> </tr> <tr> <td height="23"><div align="right">Nombre</div></td> <td colspan="3"><label> <input name="txtnomsujret" type="text" id="txtnomsujret" size="100" maxlength="100" value="<?php print $ls_nomsujret?>" readonly> </label></td> </tr> <tr> <td height="22"><div align="right">Direccion</div></td> <td colspan="3"><label> <input name="txtdirsujret" type="text" id="txtdirsujret" size="100" value="<?php print $ls_dirsujret?>" readonly> </label></td> </tr> <tr> <td height="13" colspan="4" align="center">&nbsp;</td> </tr> <tr> <td height="13" colspan="4" align="center"></td> </tr> </table></td> </tr> </table> <p align="center"> <input name="operacion" type="hidden" id="operacion" value="<?php print $ls_operacion;?>"> <input name="existe" type="hidden" id="existe" value="<?php print $ls_existe;?>"> <input name="estapr" type="hidden" id="estapr" value="<?php print $li_estaprord;?>"> <input name="parametros" type="hidden" id="parametros" value="<?php print $ls_parametros;?>"> <input name="txttipdes" type="hidden" id="txttipdes" value="<?php print $ls_tipodestino; ?>"> <input name="txtfecha" type="hidden" id="txtfecha" value="<?php print $ld_fecemisol; ?>"> <input name="txtmes" type="hidden" id="txtmes" value="<?php print $ls_mes; ?>"> <input name="totrowrecepciones" type="hidden" id="totrowrecepciones" value="<?php print $<API key>;?>"> <input name="formato" type="hidden" id="formato" value="<?php print $ls_reporte; ?>"> <input name="txtprobene" type="hidden" id="txtprobene" value="<?php print $ls_probene; ?>"> <input name="txtindice" type="hidden" id="txtindice" value="<?php print $ls_indice; ?>"> <input name="hidfilsel" type="hidden" id="hidfilsel"> <input name="modageret" type="hidden" id="modageret" value="<?php print $_SESSION["la_empresa"]["modageret"]; ?>"> <input name="conivaret" type="hidden" id="conivaret" value="<?php print $_SESSION["la_empresa"]["estretiva"]; ?>"> <input name="txtbasdatcmp" type="hidden" id="txtbasdatcmp" value="<?php print $ls_basdatcmp; ?>"> </p></td> </tr> </table> <br> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td><div id="detalles" align="center"></div></td> </tr> </table> </form> </body> <script language="javascript"> var patron = new Array(2,2,4); var patron2 = new Array(1,3,3,3,3); function ue_nuevo() { f=document.formulario; li_modageret=f.modageret.value; li_conivaret=f.conivaret.value; if((li_modageret!="B")||(li_conivaret!="B")) { li_incluir=f.incluir.value; if(li_incluir==1) { f.operacion.value="NEW"; f.existe.value="FALSE"; f.action="<API key>.php"; f.submit(); } else { alert("No tiene permiso para realizar esta operacion"); } } else { alert("Los dos comprobantes se manejan por el Módulo de Caja y Banco"); } } function ue_guardar() { f=document.formulario; li_incluir=f.incluir.value; li_cambiar=f.cambiar.value; lb_existe=f.existe.value; ls_basdatcmp=f.txtbasdatcmp.value; if(((lb_existe=="TRUE")&&(li_cambiar==1))||(lb_existe=="FALSE")&&(li_incluir==1)) { valido=true; if((ls_basdatcmp!="")&&(li_cambiar==1)) { alert("Los comprobantes solo pueden ser modificados desde la Base de Datos integradora"); } else { // Obtenemos el total de filas de los Conceptos total=<API key>("txtnumope"); f.totrowrecepciones.value=total; numcom=ue_validarvacio(f.txtnumcom.value); if(valido) { valido=ue_validarcampo(f.txtnumcom.value,"Debe seleccionar un Comprobante.",f.txtnumsol); } if(valido) { valido=ue_validarcampo(f.txtcodigo.value,"Debe seleccionar un Proveedor / Beneficiario.",f.txtnumsol); } if(valido) { rowrecepciones=f.totrowrecepciones.value; for(row=1;row<rowrecepciones;row++) { numfac= eval("f.txtnumfac"+row+".value"); if(numfac=="") { alert("No se permite numeros de factura en Blanco."); valido=false; break; } } if(rowrecepciones<=1) { alert("El comprobante debe tener al menos un detalle."); valido=false; } } if(valido) { f.operacion.value="GUARDAR"; f.action="<API key>.php"; f.submit(); } } } else { alert("No tiene permiso para realizar esta operación."); } } function ue_eliminar() { f=document.formulario; li_eliminar=f.eliminar.value; lb_existe=f.existe.value; ls_basdatcmp=f.txtbasdatcmp.value; if(li_eliminar==1) { valido=true; if(ls_basdatcmp!="") { alert("Los comprobantes solo pueden ser modificados desde la Base de Datos integradora"); } else { // Obtenemos el total de filas de los Conceptos total=<API key>("txtnumope"); f.totrowrecepciones.value=total; numcom=ue_validarvacio(f.txtnumcom.value); if(valido) { valido=ue_validarcampo(numcom,"Debe seleccionar un Comprobante.",f.txtnumsol); } if(valido) { rowrecepciones=f.totrowrecepciones.value; if(rowrecepciones<=1) { alert("El comprobante debe tener al menos un detalle."); valido=false; } } if(valido) { if(confirm("¿Realmente desea inutilizar este registro?")) { f.operacion.value="ELIMINAR"; f.action="<API key>.php"; f.submit(); } else { alert("Operación Cancelada!!!"); } } } } else { alert("No tiene permiso para realizar esta operación."); } } function ue_buscar() { f=document.formulario; li_leer=f.leer.value; li_modageret=f.modageret.value; li_conivaret=f.conivaret.value; if((li_modageret!="B")||(li_conivaret!="B")) { if (li_leer==1) { window.open("<API key>.php","catalogo","menubar=no,toolbar=no,scrollbars=yes,width=630,height=400,left=50,top=50,location=no,resizable=yes"); } else { alert("No tiene permiso para realizar esta operacion"); } } else { alert("Los dos comprobantes se manejan por el Módulo de Caja y Banco"); } } function ue_cerrar() { location.href = "sigespwindow_blank.php"; } function ue_delete_detalle(fila) { f=document.formulario; if(confirm("¿Desea eliminar el Registro actual?")) { valido=true; parametros=""; total=<API key>("txtnumope"); f.totrowrecepciones.value=total; rowrecepciones=f.totrowrecepciones.value; li_i=1; for(j=1;(j<rowrecepciones)&&(valido);j++) { if(j!=fila) { ls_codret=eval("document.formulario.txtcodret"+j+".value"); ls_numope=eval("document.formulario.txtnumope"+j+".value"); ls_fecfac=eval("document.formulario.txtfecfac"+j+".value"); ls_numfac=eval("document.formulario.txtnumfac"+j+".value"); ls_numcon=eval("document.formulario.txtnumcon"+j+".value"); ls_numnd=eval("document.formulario.txtnumnd"+j+".value"); ls_numnc=eval("document.formulario.txtnumnc"+j+".value"); ls_tiptrans=eval("document.formulario.txttiptrans"+j+".value"); ls_tot_cmp_sin_iva=eval("document.formulario.txttotsiniva"+j+".value"); ls_tot_cmp_con_iva=eval("document.formulario.txttotconiva"+j+".value"); ls_basimp=eval("document.formulario.txtbasimp"+j+".value"); ls_porimp=eval("document.formulario.txtporimp"+j+".value"); ls_porret=eval("document.formulario.txtporret"+j+".value"); ls_totimp=eval("document.formulario.txttotimp"+j+".value"); ls_ivaret=eval("document.formulario.txtivaret"+j+".value"); ls_numsop=eval("document.formulario.txtnumsop"+j+".value"); ls_numdoc=eval("document.formulario.txtnumdoc"+j+".value"); parametros=parametros+"&txtcodret"+li_i+"="+ls_codret+"&txtnumope"+li_i+"="+ls_numope+"&txtfecfac"+li_i+"="+ls_fecfac+ "&txtnumfac"+li_i+"="+ls_numfac+"&txtnumcon"+li_i+"="+ls_numcon+"&txtnumnd"+li_i+"="+ls_numnd+ "&txtnumnc"+li_i+"="+ls_numnc+"&txttiptrans"+li_i+"="+ls_tiptrans+"&txttotsiniva"+li_i+"="+ls_tot_cmp_sin_iva+ "&txttotconiva"+li_i+"="+ls_tot_cmp_con_iva+"&txtbasimp"+li_i+"="+ls_basimp+"&txtporimp"+li_i+"="+ls_porimp+ "&txttotimp"+li_i+"="+ls_totimp+"&txtivaret"+li_i+"="+ls_ivaret+"&txtnumsop"+li_i+"="+ls_numsop+ "&txtnumdoc"+li_i+"="+ls_numdoc+"&txtporret"+li_i+"="+ls_porret; li_i=li_i+1; } } totalrecepciones=eval(li_i); f.totrowrecepciones.value=totalrecepciones; parametros=parametros+"&totrowrecepciones="+totalrecepciones; if((parametros!="")&&(valido)) { divgrid = document.getElementById("detalles"); ajax=objetoAjax(); ajax.open("POST","class_folder/<API key>.php",true); ajax.onreadystatechange=function() { if (ajax.readyState==4) { divgrid.innerHTML = ajax.responseText } } ajax.setRequestHeader("Content-Type","application/<API key>"); ajax.send("proceso=AGREGARCMPRET"+parametros); } } } function ue_insert_row() { f=document.formulario; parametros=""; total=<API key>("txtnumope"); f.totrowrecepciones.value=total; rowrecepciones=f.totrowrecepciones.value; for (j=1;(j<rowrecepciones);j++) { ls_codret = eval("document.formulario.txtcodret"+j+".value"); ls_numope = eval("document.formulario.txtnumope"+j+".value"); ls_fecfac = eval("document.formulario.txtfecfac"+j+".value"); ls_numfac = eval("document.formulario.txtnumfac"+j+".value"); ls_numcon = eval("document.formulario.txtnumcon"+j+".value"); ls_numnd = eval("document.formulario.txtnumnd"+j+".value"); ls_numnc = eval("document.formulario.txtnumnc"+j+".value"); ls_tiptrans = eval("document.formulario.txttiptrans"+j+".value"); ls_tot_cmp_sin_iva = eval("document.formulario.txttotsiniva"+j+".value"); ls_tot_cmp_con_iva = eval("document.formulario.txttotconiva"+j+".value"); ls_basimp = eval("document.formulario.txtbasimp"+j+".value"); ls_porimp = eval("document.formulario.txtporimp"+j+".value"); ls_porret = eval("document.formulario.txtporret"+j+".value"); ls_totimp = eval("document.formulario.txttotimp"+j+".value"); ls_ivaret = eval("document.formulario.txtivaret"+j+".value"); ls_numsop = eval("document.formulario.txtnumsop"+j+".value"); ls_numdoc = eval("document.formulario.txtnumdoc"+j+".value"); parametros= parametros+"&txtcodret"+j+"="+ls_codret+"&txtnumope"+j+"="+ls_numope+"&txtfecfac"+j+"="+ls_fecfac+ "&txtnumfac"+j+"="+ls_numfac+"&txtnumcon"+j+"="+ls_numcon+"&txtnumnd"+j+"="+ls_numnd+ "&txtnumnc"+j+"="+ls_numnc+"&txttiptrans"+j+"="+ls_tiptrans+"&txttotsiniva"+j+"="+ls_tot_cmp_sin_iva+ "&txttotconiva"+j+"="+ls_tot_cmp_con_iva+"&txtbasimp"+j+"="+ls_basimp+"&txtporimp"+j+"="+ls_porimp+ "&txttotimp"+j+"="+ls_totimp+"&txtivaret"+j+"="+ls_ivaret+"&txtnumsop"+j+"="+ls_numsop+ "&txtnumdoc"+j+"="+ls_numdoc+"&txtporret"+j+"="+ls_porret; } j++; totalrecepciones=eval(j); f.totrowrecepciones.value=totalrecepciones; parametros=parametros+"&totrowrecepciones="+totalrecepciones; if (parametros!="") { divgrid = document.getElementById("detalles"); ajax = objetoAjax(); ajax.open("POST","class_folder/<API key>.php",true); ajax.onreadystatechange=function() { if (ajax.readyState==4) { divgrid.innerHTML = ajax.responseText } } ajax.setRequestHeader("Content-Type","application/<API key>"); ajax.send("proceso=AGREGARCMPRETINS"+parametros); } } function ue_reload() { f=document.formulario; parametros=f.parametros.value; proceso="AGREGARCMPRET"; if(parametros!="") { divgrid = document.getElementById("detalles"); ajax=objetoAjax(); ajax.open("POST","class_folder/<API key>.php",true); ajax.onreadystatechange=function() { if (ajax.readyState==4) { divgrid.innerHTML = ajax.responseText } } ajax.setRequestHeader("Content-Type","application/<API key>"); ajax.send("proceso="+proceso+""+parametros); } } function ue_cargardatos(ls_numcom,ls_anofiscal,ls_mesfiscal,ls_codsujret,ls_nomsujret,ls_dirsujret,ls_rifsujret,ls_codret, ls_probene,ls_estcmpret) { f=document.formulario; f.txtnumcom.value=ls_numcom; f.txtano.value=ls_anofiscal; f.cmbmes.value=ls_mesfiscal; f.cmbtipo.value=ls_codret; f.txtcodigo.value=ls_codsujret; f.txtnomsujret.value=ls_nomsujret; f.txtdirsujret.value=ls_dirsujret; f.txtrif.value=ls_rifsujret; f.txtprobene.value=ls_probene; if(ls_estcmpret==1) { f.txtestatus.value="EMITIDO"; } else { f.txtestatus.value="ANULADO"; } f.existe.value="TRUE"; } function uf_catalogo_proben() { fop=document.formulario; if (fop.estprov[0].checked==true) { ls_tipo="MODCMPRET"; f.txtprobene.value="P"; pagina="<API key>.php?tipo="+ls_tipo; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=560,height=400,resizable=yes,location=no"); } else { if (fop.estprov[1].checked==true) { ls_tipo="MODCMPRET"; f.txtprobene.value="B"; pagina="<API key>.php?tipo="+ls_tipo; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=560,height=400,resizable=yes,location=no"); } } } function cargarcodpro(codpro,nompro,rifpro,dirprov) { f=document.formulario; f.txtcodigo.value=codpro; f.txtnomsujret.value=nompro; f.txtdirsujret.value=dirprov; f.txtrif.value=rifpro; } function ue_cat_solicitud(li_fila) { f=document.formulario; f.txtindice.value=li_fila; ls_catalogo="<API key>.php?tipo=MODCMPRET"; window.open(ls_catalogo,"_blank","menubar=no,toolbar=no,scrollbars=yes,width=550,height=400,left=50,top=50,location=no,resizable=yes"); } function uf_iva(li_row) { f=document.formulario; ld_basimp = eval("f.txtbasimp"+li_row+".value"); if ((ld_basimp!="0,00") && (ld_basimp!="")) { f.hidfilsel.value = li_row; pagina="<API key>.php?tipo=CMPRET"; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=700,height=600,resizable=yes,location=no"); } else { alert("Para que pueda seleccionar un cargo la Base Imponible debe ser distinta de cero !!!"); } } function uf_retenciones(li_row) { f = document.formulario; f.hidfilsel.value = li_row; ls_tipret = f.cmbtipo.value; switch (ls_tipret) { case "0000000001": ld_porcar = eval("f.txtporimp"+li_row+".value"); if ((ld_porcar!="0,00") && (ld_porcar!="")) { pagina="<API key>.php?tipo=CMPRETIVA"; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=600,height=600,resizable=yes,location=no"); } else { alert("Para que pueda seleccionar un deducción el porcentaje debe ser distinto a cero !!!"); } break; case "0000000003": ld_basimp = eval("f.txtbasimp"+li_row+".value"); if ((ld_basimp!="0,00") && (ld_basimp!="")) { pagina="<API key>.php?tipo=CMPRETMUN"; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=700,height=600,resizable=yes,location=no"); } else { alert("Para que pueda seleccionar un deducción el Monto de la Base Imponible debe ser Mayor a Cero !!!"); } break; case "0000000004": ld_basimp = eval("f.txtbasimp"+li_row+".value"); if ((ld_basimp!="0,00") && (ld_basimp!="")) { pagina="<API key>.php?tipo=CMPRETAPO"; window.open(pagina,"catalogo","menubar=no,toolbar=no,scrollbars=yes,width=700,height=600,resizable=yes,location=no"); } else { alert("Para que pueda seleccionar un deducción el Monto de la Base Imponible debe ser Mayor a Cero !!!"); } break; } function ue_numeronegativo(valor,li_row) { f= document.formulario; if(eval("document.formulario.txtnumnc"+li_row+".value")) { auxiliar=valor.value; if((auxiliar.indexOf("-")==-1)&&(auxilar!="")) { auxiliar="-"+auxiliar; valor.value = auxiliar; } } } function ue_validarnota(valor,li_row) { f= document.formulario; if(valor=="NC") { eval("document.formulario.txtnumnd"+li_row+".value=''"); } else { eval("document.formulario.txtnumnc"+li_row+".value=''"); } eval("document.formulario.txtbasimp"+li_row+".value='0,00'"); eval("document.formulario.txttotconiva"+li_row+".value='0,00'"); eval("document.formulario.txtporimp"+li_row+".value='0,00'"); eval("document.formulario.txttotimp"+li_row+".value='0,00'"); } function currency_Format(fld, milSep, decSep, e) { var sep = 0; var key = ''; var i = j = 0; var len = len2 = 0; var strCheck = '0123456789-'; var aux = aux2 = ''; var whichCode = (window.Event) ? e.which : e.keyCode; if (whichCode == 13) return true; // Enter if (whichCode == 8) return true; // Enter if (whichCode == 127) return true; // Enter if (whichCode == 9) return true; // Enter key = String.fromCharCode(whichCode); // Get key value from key code if (strCheck.indexOf(key) == -1) return false; // Not a valid key len = fld.value.length; for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); aux += key; len = aux.length; if (len == 0) fld.value = ''; if (len == 1) fld.value = '0'+ decSep + '0' + aux; if (len == 2) fld.value = '0'+ decSep + aux; if (len > 2) { aux2 = ''; for (j = 0, i = len - 3; i >= 0; i if(aux.charAt(i)=='-') { if (j == 4) { aux2 += milSep; j = 0; } } else { if (j == 3) { aux2 += milSep; j = 0; } } aux2 += aux.charAt(i); j++; } fld.value = ''; len2 = aux2.length; for (i = len2 - 1; i >= 0; i fld.value += aux2.charAt(i); fld.value += decSep + aux.substr(len - 2, len); } return false; } </script> <script language="javascript" src="../shared/js/js_intra/datepickercontrol.js"></script> <?php if(($ls_operacion=="GUARDAR")) { print "<script language=JavaScript>"; print " ue_reload();"; print "</script>"; } if($ls_operacion=="NEW") { print "<script language=JavaScript>"; print " ue_insert_row();"; print "</script>"; } ?> </html>
#!/usr/bin/env python # This program is free software: you can redistribute it and/or modify # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from flask import render_template from white.controller import admin_bp as bp, ADMIN, EDITOR from white.security import security @bp.route('/extend') @security(ADMIN) def extend_index(): return render_template('admin/extend/index.html') @bp.route('/extend/variable') @security(ADMIN) def variable_index(): return render_template('admin/extend/variable/index.html') @bp.route('/extend/variable/add') @security(ADMIN) def variable_add_page(): return render_template('admin/extend/variable/add.html') @bp.route('/extend/plugin') @security(ADMIN) def extend_plugin(): return render_template('admin/extend/plugin/index.html')
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "modes.h" #include <math.h> #include "os_support.h" #ifdef ARMV7NEON_ASM EXPORT int <API key>=<API key>; #else EXPORT int <API key>=0; #endif EXPORT int speex_lib_ctl(int request, void *ptr) { switch (request) { case <API key>: *((int*)ptr) = SPEEX_MAJOR_VERSION; break; case <API key>: *((int*)ptr) = SPEEX_MINOR_VERSION; break; case <API key>: *((int*)ptr) = SPEEX_MICRO_VERSION; break; case <API key>: *((const char**)ptr) = SPEEX_EXTRA_VERSION; break; case <API key>: *((const char**)ptr) = SPEEX_VERSION; break; case <API key>: <API key>=*(int*)ptr; break; /*case <API key>: break; case <API key>: break; case <API key>: break; case <API key>: break;*/ default: speex_warning_int("Unknown wb_mode_query request: ", request); return -1; } return 0; }
<?php namespace Laminas\Diactoros; use <API key>; use function get_class; use function gettype; use function in_array; use function is_numeric; use function is_object; use function is_string; use function ord; use function preg_match; use function sprintf; use function strlen; final class HeaderSecurity { /** * Private constructor; non-instantiable. * @codeCoverageIgnore */ private function __construct() { } public static function filter($value) { $value = (string) $value; $length = strlen($value); $string = ''; for ($i = 0; $i < $length; $i += 1) { $ascii = ord($value[$i]); // Detect continuation sequences if ($ascii === 13) { $lf = ord($value[$i + 1]); $ws = ord($value[$i + 2]); if ($lf === 10 && in_array($ws, [9, 32], true)) { $string .= $value[$i] . $value[$i + 1]; $i += 1; } continue; } // Non-visible, non-whitespace characters if (($ascii < 32 && $ascii !== 9) || $ascii === 127 || $ascii > 254 ) { continue; } $string .= $value[$i]; } return $string; } public static function isValid($value) { $value = (string) $value; // Look for: // \n not preceded by \r, OR // \r not followed by \n, OR // \r\n not followed by space or horizontal tab; these are all CRLF attacks if (preg_match("#(?:(?:(?<!\r)\n)|(?:\r(?!\n))|(?:\r\n(?![ \t])))#", $value)) { return false; } // Non-visible, non-whitespace characters if (preg_match('/[^\x09\x0a\x0d\x20-\x7E\x80-\xFE]/', $value)) { return false; } return true; } /** * Assert a header value is valid. * * @param string $value * @throws <API key> for invalid values */ public static function assertValid($value) { if (! is_string($value) && ! is_numeric($value)) { throw new <API key>(sprintf( 'Invalid header value type; must be a string or numeric; received %s', (is_object($value) ? get_class($value) : gettype($value)) )); } if (! self::isValid($value)) { throw new <API key>(sprintf( '"%s" is not valid header value', $value )); } } public static function assertValidName($name) { if (! is_string($name)) { throw new <API key>(sprintf( 'Invalid header name type; expected string; received %s', (is_object($name) ? get_class($name) : gettype($name)) )); } if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $name)) { throw new <API key>(sprintf( '"%s" is not valid header name', $name )); } } }
include("shared.lua")
# Makefile for the touchscreen drivers. # Each configuration option enables a list of files. wm97xx-ts-y := wm97xx-core.o obj-$(<API key>) += 88pm860x-ts.o obj-$(<API key>) += ad7877.o obj-$(<API key>) += ad7879.o obj-$(<API key>) += ad7879-i2c.o obj-$(<API key>) += ad7879-spi.o obj-$(<API key>) += ads7846.o obj-$(<API key>) += atmel_maxtouch.o obj-$(<API key>) += atmel_mxt_ts.o obj-$(<API key>) += atmel_tsadcc.o obj-$(<API key>) += h3600_ts_input.o obj-$(<API key>) += bu21013_ts.o obj-$(<API key>) += cy8c_tmg_ts.o obj-$(<API key>) += cy8ctmg110_ts.o obj-$(<API key>) += da9034-ts.o obj-$(<API key>) += dynapro.o obj-$(<API key>) += hampshire.o obj-$(<API key>) += gunze.o obj-$(<API key>) += eeti_ts.o obj-$(<API key>) += elan8232_i2c.o obj-$(<API key>) += elo.o obj-$(<API key>) += fujitsu_ts.o obj-$(<API key>) += inexio.o obj-$(<API key>) += intel-mid-touch.o obj-$(<API key>) += lpc32xx_ts.o obj-$(<API key>) += max11801_ts.o obj-$(<API key>) += mc13783_ts.o obj-$(<API key>) += mcs5000_ts.o obj-$(<API key>) += migor_ts.o obj-$(<API key>) += mtouch.o obj-$(<API key>) += mk712.o obj-$(<API key>) += msm_ts.o obj-$(<API key>) += hp680_ts_input.o obj-$(<API key>) += jornada720_ts.o obj-$(<API key>) += htcpen.o obj-$(<API key>) += usbtouchscreen.o obj-$(<API key>) += pcap_ts.o obj-$(<API key>) += penmount.o obj-$(<API key>) += s3c2410_ts.o obj-$(<API key>) += st1232.o obj-$(<API key>) += stmpe-ts.o obj-$(<API key>) += tnetv107x-ts.o obj-$(<API key>) += synaptics_i2c_rmi.o obj-$(<API key>) +=synaptics/ obj-$(<API key>) += touchit213.o obj-$(<API key>) += touchright.o obj-$(<API key>) += touchwin.o obj-$(<API key>) += tsc2005.o obj-$(<API key>) += tsc2007.o obj-$(<API key>) += ucb1400_ts.o obj-$(<API key>) += wacom_w8001.o obj-$(<API key>) += wm831x-ts.o obj-$(<API key>) += wm97xx-ts.o wm97xx-ts-$(<API key>) += wm9705.o wm97xx-ts-$(<API key>) += wm9712.o wm97xx-ts-$(<API key>) += wm9713.o obj-$(<API key>) += atmel-wm97xx.o obj-$(<API key>) += mainstone-wm97xx.o obj-$(<API key>) += zylonite-wm97xx.o obj-$(<API key>) += w90p910_ts.o obj-$(<API key>) += tps6507x-ts.o obj-$(<API key>) += msm_touch.o obj-$(<API key>) += cy8c_ts.o obj-$(<API key>) += cyttsp-i2c.o obj-$(<API key>) += mcs6000_ts_sub.o obj-$(<API key>) += qt602240.o obj-$(<API key>) += qt602140.o obj-$(<API key>) += qt602240_ts.o obj-$(<API key>) += so340010.o
-- Table `#<API key>` sample data INSERT INTO `#<API key>` (`manufacturer_id`, `manufacturer_name`, `manufacturer_image`, `<API key>`, `created_date`, `modified_date`) VALUES (1, 'HTC', '', 1, NOW(), NOW()), (2, 'Acer', '', 1, NOW(), NOW()), (3, 'AMD', '', 1, NOW(), NOW()), (4, 'Apple', '', 1, NOW(), NOW()), (5, 'AT&T', '', 1, NOW(), NOW()), (6, 'Canon', '', 1, NOW(), NOW()), (7, 'Dell', '', 1, NOW(), NOW()), (8, 'Gateway', '', 1, NOW(), NOW());
#ifndef _STP_STRING_H_ #define _STP_STRING_H_ #define to_oct_digit(c) ((c) + '0') static int _stp_text_str(char *out, char *in, int inlen, int outlen, int quoted, int user); #if defined(__KERNEL__) /* * Powerpc uses a paranoid user address check in __get_user() which * spews warnings "BUG: Sleeping function...." when <API key> * is enabled. With 2.6.21 and above, a newer variant __get_user_inatomic * is provided without the paranoid check. Use it if available, fall back * to __get_user() if not. Other archs can use __get_user() as is */ #if defined(__powerpc__) && defined(__get_user_inatomic) #define __stp_get_user(x, ptr) __get_user_inatomic (x, ptr) #else #define __stp_get_user(x, ptr) __get_user (x, ptr) #endif #elif defined(__DYNINST__) #define __stp_get_user(x, ptr) __get_user(x, ptr) #endif /** Safely read from userspace or kernelspace. * On success, returns 0. Returns -EFAULT on error. * * This uses __get_user() to read from userspace or * kernelspace. Will not sleep or cause pagefaults when * called from within a kprobe context. * * @param segment . KERNEL_DS for kernel access * USER_DS for userspace. */ /* XXX: duplicates _stp_deref() in loc2c-runtime.h */ /* NB: lookup_bad_addr cannot easily be called from here due to header * file ordering. */ /* XXX: no error signalling */ #define _stp_read_address(x, ptr, segment) \ ({ \ long ret; \ mm_segment_t ofs = get_fs(); \ set_fs(segment); \ pagefault_disable(); \ if (!access_ok(VERIFY_READ, (char __user *)ptr, sizeof(x))) \ ret = -EFAULT; \ else \ ret = __stp_get_user(x, ptr); \ pagefault_enable(); \ set_fs(ofs); \ ret; \ }) #endif /* _STP_STRING_H_ */
#include <errno.h> #include <unistd.h> #include <sys/types.h> /* Set the real group ID of the calling process to RGID, and the effective group ID of the calling process to EGID. */ int __setregid (effective_gid, real_gid) gid_t effective_gid; gid_t real_gid; { __set_errno (ENOSYS); return -1; } stub_warning (setregid) weak_alias (__setregid, setregid) #include <stub-tag.h>
function c63193879.initial_effect(c) --lv change local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(63193879,0)) e1:SetProperty(<API key>) e1:SetType(<API key>) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(2) e1:SetCost(c63193879.cost) e1:SetTarget(c63193879.target) e1:SetOperation(c63193879.operation) c:RegisterEffect(e1) --unsynchroable local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(<API key>) e2:SetProperty(<API key>+<API key>) e2:SetValue(1) c:RegisterEffect(e2) Duel.<API key>(63193879,ACTIVITY_SPSUMMON,c63193879.counterfilter) end function c63193879.counterfilter(c) return c:IsAttribute(ATTRIBUTE_WATER) end function c63193879.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.<API key>(63193879,tp,ACTIVITY_SPSUMMON)==0 end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(<API key>+EFFECT_FLAG_OATH) e1:SetCode(<API key>) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetTargetRange(1,0) e1:SetTarget(c63193879.splimit) Duel.RegisterEffect(e1,tp) end function c63193879.splimit(e,c) return c:GetAttribute()~=ATTRIBUTE_WATER end function c63193879.filter(c) return c:IsFaceup() and c:IsRace(RACE_FISH) and c:GetLevel()>0 end function c63193879.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c63193879.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c63193879.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c63193879.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) local op=0 if g:GetFirst():IsLevel(1) then op=Duel.SelectOption(tp,aux.Stringid(63193879,1)) else op=Duel.SelectOption(tp,aux.Stringid(63193879,1),aux.Stringid(63193879,2)) end e:SetLabel(op) end function c63193879.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(<API key>) e1:SetCode(EFFECT_UPDATE_LEVEL) e1:SetReset(RESET_EVENT+RESETS_STANDARD) if e:GetLabel()==0 then e1:SetValue(1) else e1:SetValue(-1) end tc:RegisterEffect(e1) end end
<?php class <API key> extends <API key> { public $id = 'day'; function schedule($newsletter) { $this->newsletter = $newsletter; $y = $this->year; $m = $this->month; $d = $this->day; $h = $this->get_hour(); $i = $this->get_minute(); return $this-><API key>( $this->mktime( $h, $i, 0, $m, $d, $y ) ); } } new <API key>(__('Every day', MP_TXTDOM));
/* $OpenBSD: dhclient.c,v 1.62 2004/12/05 18:35:51 deraadt Exp $ */ #include <rosdhcp.h> #define PERIOD 0x2e #define hyphenchar(c) ((c) == 0x2d) #define bslashchar(c) ((c) == 0x5c) #define periodchar(c) ((c) == PERIOD) #define asterchar(c) ((c) == 0x2a) #define alphachar(c) (((c) >= 0x41 && (c) <= 0x5a) || \ ((c) >= 0x61 && (c) <= 0x7a)) #define digitchar(c) ((c) >= 0x30 && (c) <= 0x39) #define borderchar(c) (alphachar(c) || digitchar(c)) #define middlechar(c) (borderchar(c) || hyphenchar(c)) #define domainchar(c) ((c) > 0x20 && (c) < 0x7f) unsigned long debug_trace_level = 0; /* DEBUG_ULTRA */ char *path_dhclient_conf = _PATH_DHCLIENT_CONF; char *path_dhclient_db = NULL; int log_perror = 1; int privfd; //int nullfd = -1; struct iaddr iaddr_broadcast = { 4, { 255, 255, 255, 255 } }; struct in_addr inaddr_any; struct sockaddr_in sockaddr_broadcast; /* * ASSERT_STATE() does nothing now; it used to be * assert (state_is == state_shouldbe). */ #define ASSERT_STATE(state_is, state_shouldbe) {} #define TIME_MAX 2147483647 int log_priority; int no_daemon; int unknown_ok = 1; int routefd; void usage(void); int check_option(struct client_lease *l, int option); int ipv4addrs(char * buf); int res_hnok(const char *dn); char *option_as_string(unsigned int code, unsigned char *data, int len); int fork_privchld(int, int); int check_arp( struct interface_info *ip, struct client_lease *lp ); #define ADVANCE(x, n) (x += ROUNDUP((n)->sa_len)) time_t scripttime; int init_client(void) { ApiInit(); AdapterInit(); tzset(); memset(&sockaddr_broadcast, 0, sizeof(sockaddr_broadcast)); sockaddr_broadcast.sin_family = AF_INET; sockaddr_broadcast.sin_port = htons(REMOTE_PORT); sockaddr_broadcast.sin_addr.s_addr = INADDR_BROADCAST; inaddr_any.s_addr = INADDR_ANY; <API key> = do_packet; if (PipeInit() == <API key>) { DbgPrint("DHCPCSVC: PipeInit() failed!\n"); AdapterStop(); ApiFree(); return 0; // FALSE } return 1; // TRUE } void stop_client(void) { // AdapterStop(); // ApiFree(); /* FIXME: Close pipe and kill pipe thread */ } /* XXX Implement me */ int check_arp( struct interface_info *ip, struct client_lease *lp ) { return 1; } /* * Individual States: * * Each routine is called from the <API key>() in one of * these conditions: * -> entering INIT state * -> recvpacket_flag == 0: timeout in this state * -> otherwise: received a packet in this state * * Return conditions as handled by <API key>(): * Returns 1, sendpacket_flag = 1: send packet, reset timer. * Returns 1, sendpacket_flag = 0: just reset the timer (wait for a milestone). * Returns 0: finish the nap which was interrupted for no good reason. * * Several per-interface variables are used to keep track of the process: * active_lease: the lease that is being used on the interface * (null pointer if not configured yet). * offered_leases: leases corresponding to DHCPOFFER messages that have * been sent to us by DHCP servers. * acked_leases: leases corresponding to DHCPACK messages that have been * sent to us by DHCP servers. * sendpacket: DHCP packet we're trying to send. * destination: IP address to send sendpacket to * In addition, there are several relevant per-lease variables. * T1_expiry, T2_expiry, lease_expiry: lease milestones * In the active lease, these control the process of renewing the lease; * In leases on the acked_leases list, this simply determines when we * can no longer legitimately use the lease. */ void state_reboot(void *ipp) { struct interface_info *ip = ipp; ULONG foo = (ULONG) GetTickCount(); /* If we don't remember an active lease, go straight to INIT. */ if (!ip->client->active || ip->client->active->is_bootp) { state_init(ip); return; } /* We are in the rebooting state. */ ip->client->state = S_REBOOTING; /* make_request doesn't initialize xid because it normally comes from the DHCPDISCOVER, but we haven't sent a DHCPDISCOVER, so pick an xid now. */ ip->client->xid = RtlRandom(&foo); /* Make a DHCPREQUEST packet, and set appropriate per-interface flags. */ make_request(ip, ip->client->active); ip->client->destination = iaddr_broadcast; time(&ip->client->first_sending); ip->client->interval = ip->client->config->initial_interval; /* Zap the medium list... */ ip->client->medium = NULL; /* Send out the first DHCPREQUEST packet. */ send_request(ip); } /* * Called when a lease has completely expired and we've * been unable to renew it. */ void state_init(void *ipp) { struct interface_info *ip = ipp; ASSERT_STATE(state, S_INIT); /* Make a DHCPDISCOVER packet, and set appropriate per-interface flags. */ make_discover(ip, ip->client->active); ip->client->xid = ip->client->packet.xid; ip->client->destination = iaddr_broadcast; ip->client->state = S_SELECTING; time(&ip->client->first_sending); ip->client->interval = ip->client->config->initial_interval; /* Add an immediate timeout to cause the first DHCPDISCOVER packet to go out. */ send_discover(ip); } /* * state_selecting is called when one or more DHCPOFFER packets * have been received and a configurable period of time has passed. */ void state_selecting(void *ipp) { struct interface_info *ip = ipp; struct client_lease *lp, *next, *picked; time_t cur_time; ASSERT_STATE(state, S_SELECTING); time(&cur_time); /* Cancel state_selecting and send_discover timeouts, since either one could have got us here. */ cancel_timeout(state_selecting, ip); cancel_timeout(send_discover, ip); /* We have received one or more DHCPOFFER packets. Currently, the only criterion by which we judge leases is whether or not we get a response when we arp for them. */ picked = NULL; for (lp = ip->client->offered_leases; lp; lp = next) { next = lp->next; /* Check to see if we got an ARPREPLY for the address in this particular lease. */ if (!picked) { if( !check_arp(ip,lp) ) goto freeit; picked = lp; picked->next = NULL; } else { freeit: free_client_lease(lp); } } ip->client->offered_leases = NULL; /* If we just tossed all the leases we were offered, go back to square one. */ if (!picked) { ip->client->state = S_INIT; state_init(ip); return; } /* If it was a BOOTREPLY, we can just take the address right now. */ if (!picked->options[<API key>].len) { ip->client->new = picked; /* Make up some lease expiry times XXX these should be configurable. */ ip->client->new->expiry = cur_time + 12000; ip->client->new->renewal += cur_time + 8000; ip->client->new->rebind += cur_time + 10000; ip->client->state = S_REQUESTING; /* Bind to the address we received. */ bind_lease(ip); return; } /* Go to the REQUESTING state. */ ip->client->destination = iaddr_broadcast; ip->client->state = S_REQUESTING; ip->client->first_sending = cur_time; ip->client->interval = ip->client->config->initial_interval; /* Make a DHCPREQUEST packet from the lease we picked. */ make_request(ip, picked); ip->client->xid = ip->client->packet.xid; /* Toss the lease we picked - we'll get it back in a DHCPACK. */ free_client_lease(picked); /* Add an immediate timeout to send the first DHCPREQUEST packet. */ send_request(ip); } /* state_requesting is called when we receive a DHCPACK message after having sent out one or more DHCPREQUEST packets. */ void dhcpack(struct packet *packet) { struct interface_info *ip = packet->interface; struct client_lease *lease; time_t cur_time; time(&cur_time); /* If we're not receptive to an offer right now, or if the offer has an unrecognizable transaction id, then just drop it. */ if (packet->interface->client->xid != packet->raw->xid || (packet->interface->hw_address.hlen != packet->raw->hlen) || (memcmp(packet->interface->hw_address.haddr, packet->raw->chaddr, packet->raw->hlen))) return; if (ip->client->state != S_REBOOTING && ip->client->state != S_REQUESTING && ip->client->state != S_RENEWING && ip->client->state != S_REBINDING) return; note("DHCPACK from %s", piaddr(packet->client_addr)); lease = packet_to_lease(packet); if (!lease) { note("packet_to_lease failed."); return; } ip->client->new = lease; /* Stop resending DHCPREQUEST. */ cancel_timeout(send_request, ip); /* Figure out the lease time. */ if (ip->client->new->options[DHO_DHCP_LEASE_TIME].data) ip->client->new->expiry = getULong( ip->client->new->options[DHO_DHCP_LEASE_TIME].data); else ip->client->new->expiry = <API key>; /* A number that looks negative here is really just very large, because the lease expiry offset is unsigned. */ if (ip->client->new->expiry < 0) ip->client->new->expiry = TIME_MAX; /* XXX should be fixed by resetting the client state */ if (ip->client->new->expiry < 60) ip->client->new->expiry = 60; /* Take the server-provided renewal time if there is one; otherwise figure it out according to the spec. */ if (ip->client->new->options[<API key>].len) ip->client->new->renewal = getULong( ip->client->new->options[<API key>].data); else ip->client->new->renewal = ip->client->new->expiry / 2; /* Same deal with the rebind time. */ if (ip->client->new->options[<API key>].len) ip->client->new->rebind = getULong( ip->client->new->options[<API key>].data); else ip->client->new->rebind = ip->client->new->renewal + ip->client->new->renewal / 2 + ip->client->new->renewal / 4; #ifdef __REACTOS__ ip->client->new->obtained = cur_time; #endif ip->client->new->expiry += cur_time; /* Lease lengths can never be negative. */ if (ip->client->new->expiry < cur_time) ip->client->new->expiry = TIME_MAX; ip->client->new->renewal += cur_time; if (ip->client->new->renewal < cur_time) ip->client->new->renewal = TIME_MAX; ip->client->new->rebind += cur_time; if (ip->client->new->rebind < cur_time) ip->client->new->rebind = TIME_MAX; bind_lease(ip); } void set_name_servers( PDHCP_ADAPTER Adapter, struct client_lease *new_lease ) { CHAR Buffer[200] = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\"; HKEY RegKey; strcat(Buffer, Adapter->DhclientInfo.name); if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, Buffer, 0, KEY_WRITE, &RegKey ) != ERROR_SUCCESS) return; if( new_lease->options[<API key>].len ) { struct iaddr nameserver; char *nsbuf; int i, addrs = new_lease->options[<API key>].len / sizeof(ULONG); nsbuf = malloc( addrs * sizeof(IP_ADDRESS_STRING) ); if( nsbuf) { nsbuf[0] = 0; for( i = 0; i < addrs; i++ ) { nameserver.len = sizeof(ULONG); memcpy( nameserver.iabuf, new_lease->options[<API key>].data + (i * sizeof(ULONG)), sizeof(ULONG) ); strcat( nsbuf, piaddr(nameserver) ); if( i != addrs-1 ) strcat( nsbuf, "," ); } DH_DbgPrint(MID_TRACE,("Setting DhcpNameserver: %s\n", nsbuf)); RegSetValueExA( RegKey, "DhcpNameServer", 0, REG_SZ, (LPBYTE)nsbuf, strlen(nsbuf) + 1 ); free( nsbuf ); } } else { RegDeleteValueW( RegKey, L"DhcpNameServer" ); } RegCloseKey( RegKey ); } void setup_adapter( PDHCP_ADAPTER Adapter, struct client_lease *new_lease ) { CHAR Buffer[200] = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\"; struct iaddr netmask; HKEY hkey; int i; DWORD dwEnableDHCP; strcat(Buffer, Adapter->DhclientInfo.name); if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, Buffer, 0, KEY_WRITE, &hkey) != ERROR_SUCCESS) hkey = NULL; if( Adapter->NteContext ) { DeleteIPAddress( Adapter->NteContext ); Adapter->NteContext = 0; } /* Set up our default router if we got one from the DHCP server */ if( new_lease->options[DHO_SUBNET_MASK].len ) { NTSTATUS Status; memcpy( netmask.iabuf, new_lease->options[DHO_SUBNET_MASK].data, new_lease->options[DHO_SUBNET_MASK].len ); Status = AddIPAddress ( *((ULONG*)new_lease->address.iabuf), *((ULONG*)netmask.iabuf), Adapter->IfMib.dwIndex, &Adapter->NteContext, &Adapter->NteInstance ); if (hkey) { RegSetValueExA(hkey, "DhcpIPAddress", 0, REG_SZ, (LPBYTE)piaddr(new_lease->address), strlen(piaddr(new_lease->address))+1); Buffer[0] = '\0'; for(i = 0; i < new_lease->options[DHO_SUBNET_MASK].len; i++) { sprintf(&Buffer[strlen(Buffer)], "%u", new_lease->options[DHO_SUBNET_MASK].data[i]); if (i + 1 < new_lease->options[DHO_SUBNET_MASK].len) strcat(Buffer, "."); } RegSetValueExA(hkey, "DhcpSubnetMask", 0, REG_SZ, (LPBYTE)Buffer, strlen(Buffer)+1); dwEnableDHCP = 1; RegSetValueExA(hkey, "EnableDHCP", 0, REG_DWORD, (LPBYTE)&dwEnableDHCP, sizeof(DWORD)); } if( !NT_SUCCESS(Status) ) warning("AddIPAddress: %lx\n", Status); } if( new_lease->options[DHO_ROUTERS].len ) { NTSTATUS Status; Adapter->RouterMib.dwForwardDest = 0; /* Default route */ Adapter->RouterMib.dwForwardMask = 0; Adapter->RouterMib.dwForwardMetric1 = 1; Adapter->RouterMib.dwForwardIfIndex = Adapter->IfMib.dwIndex; if( Adapter->RouterMib.dwForwardNextHop ) { /* If we set a default route before, delete it before continuing */ <API key>( &Adapter->RouterMib ); } Adapter->RouterMib.dwForwardNextHop = *((ULONG*)new_lease->options[DHO_ROUTERS].data); Status = <API key>( &Adapter->RouterMib ); if( !NT_SUCCESS(Status) ) warning("<API key>: %lx\n", Status); if (hkey) { Buffer[0] = '\0'; for(i = 0; i < new_lease->options[DHO_ROUTERS].len; i++) { sprintf(&Buffer[strlen(Buffer)], "%u", new_lease->options[DHO_ROUTERS].data[i]); if (i + 1 < new_lease->options[DHO_ROUTERS].len) strcat(Buffer, "."); } RegSetValueExA(hkey, "DhcpDefaultGateway", 0, REG_SZ, (LPBYTE)Buffer, strlen(Buffer)+1); } } if (hkey) RegCloseKey(hkey); } void bind_lease(struct interface_info *ip) { PDHCP_ADAPTER Adapter; struct client_lease *new_lease = ip->client->new; time_t cur_time; time(&cur_time); /* Remember the medium. */ ip->client->new->medium = ip->client->medium; ip->client->active = ip->client->new; ip->client->new = NULL; /* Set up a timeout to start the renewal process. */ /* Timeout of zero means no timeout (some implementations seem to use * one day). */ if( ip->client->active->renewal - cur_time ) add_timeout(ip->client->active->renewal, state_bound, ip); note("bound to %s -- renewal in %ld seconds.", piaddr(ip->client->active->address), (long int)(ip->client->active->renewal - cur_time)); ip->client->state = S_BOUND; Adapter = AdapterFindInfo( ip ); if( Adapter ) setup_adapter( Adapter, new_lease ); else { warning("Could not find adapter for info %p\n", ip); return; } set_name_servers( Adapter, new_lease ); } /* * state_bound is called when we've successfully bound to a particular * lease, but the renewal time on that lease has expired. We are * expected to unicast a DHCPREQUEST to the server that gave us our * original lease. */ void state_bound(void *ipp) { struct interface_info *ip = ipp; ASSERT_STATE(state, S_BOUND); /* T1 has expired. */ make_request(ip, ip->client->active); ip->client->xid = ip->client->packet.xid; if (ip->client->active->options[<API key>].len == 4) { memcpy(ip->client->destination.iabuf, ip->client->active-> options[<API key>].data, 4); ip->client->destination.len = 4; } else ip->client->destination = iaddr_broadcast; time(&ip->client->first_sending); ip->client->interval = ip->client->config->initial_interval; ip->client->state = S_RENEWING; /* Send the first packet immediately. */ send_request(ip); } void bootp(struct packet *packet) { struct iaddrlist *ap; if (packet->raw->op != BOOTREPLY) return; /* If there's a reject list, make sure this packet's sender isn't on it. */ for (ap = packet->interface->client->config->reject_list; ap; ap = ap->next) { if (addr_eq(packet->client_addr, ap->addr)) { note("BOOTREPLY from %s rejected.", piaddr(ap->addr)); return; } } dhcpoffer(packet); } void dhcp(struct packet *packet) { struct iaddrlist *ap; void (*handler)(struct packet *); char *type; switch (packet->packet_type) { case DHCPOFFER: handler = dhcpoffer; type = "DHCPOFFER"; break; case DHCPNAK: handler = dhcpnak; type = "DHCPNACK"; break; case DHCPACK: handler = dhcpack; type = "DHCPACK"; break; default: return; } /* If there's a reject list, make sure this packet's sender isn't on it. */ for (ap = packet->interface->client->config->reject_list; ap; ap = ap->next) { if (addr_eq(packet->client_addr, ap->addr)) { note("%s from %s rejected.", type, piaddr(ap->addr)); return; } } (*handler)(packet); } void dhcpoffer(struct packet *packet) { struct interface_info *ip = packet->interface; struct client_lease *lease, *lp; int i; int arp_timeout_needed = 0, stop_selecting; char *name = packet->options[<API key>].len ? "DHCPOFFER" : "BOOTREPLY"; time_t cur_time; time(&cur_time); /* If we're not receptive to an offer right now, or if the offer has an unrecognizable transaction id, then just drop it. */ if (ip->client->state != S_SELECTING || packet->interface->client->xid != packet->raw->xid || (packet->interface->hw_address.hlen != packet->raw->hlen) || (memcmp(packet->interface->hw_address.haddr, packet->raw->chaddr, packet->raw->hlen))) return; note("%s from %s", name, piaddr(packet->client_addr)); /* If this lease doesn't supply the minimum required parameters, blow it off. */ for (i = 0; ip->client->config->required_options[i]; i++) { if (!packet->options[ip->client->config-> required_options[i]].len) { note("%s isn't satisfactory.", name); return; } } /* If we've already seen this lease, don't record it again. */ for (lease = ip->client->offered_leases; lease; lease = lease->next) { if (lease->address.len == sizeof(packet->raw->yiaddr) && !memcmp(lease->address.iabuf, &packet->raw->yiaddr, lease->address.len)) { debug("%s already seen.", name); return; } } lease = packet_to_lease(packet); if (!lease) { note("packet_to_lease failed."); return; } /* If this lease was acquired through a BOOTREPLY, record that fact. */ if (!packet->options[<API key>].len) lease->is_bootp = 1; /* Record the medium under which this lease was offered. */ lease->medium = ip->client->medium; /* Send out an ARP Request for the offered IP address. */ if( !check_arp( ip, lease ) ) { note("Arp check failed\n"); return; } /* Figure out when we're supposed to stop selecting. */ stop_selecting = ip->client->first_sending + ip->client->config->select_interval; /* If this is the lease we asked for, put it at the head of the list, and don't mess with the arp request timeout. */ if (lease->address.len == ip->client->requested_address.len && !memcmp(lease->address.iabuf, ip->client->requested_address.iabuf, ip->client->requested_address.len)) { lease->next = ip->client->offered_leases; ip->client->offered_leases = lease; } else { /* If we already have an offer, and arping for this offer would take us past the selection timeout, then don't extend the timeout - just hope for the best. */ if (ip->client->offered_leases && (cur_time + arp_timeout_needed) > stop_selecting) arp_timeout_needed = 0; /* Put the lease at the end of the list. */ lease->next = NULL; if (!ip->client->offered_leases) ip->client->offered_leases = lease; else { for (lp = ip->client->offered_leases; lp->next; lp = lp->next) ; /* nothing */ lp->next = lease; } } /* If we're supposed to stop selecting before we've had time to wait for the ARPREPLY, add some delay to wait for the ARPREPLY. */ if (stop_selecting - cur_time < arp_timeout_needed) stop_selecting = cur_time + arp_timeout_needed; /* If the selecting interval has expired, go immediately to state_selecting(). Otherwise, time out into state_selecting at the select interval. */ if (stop_selecting <= 0) state_selecting(ip); else { add_timeout(stop_selecting, state_selecting, ip); cancel_timeout(send_discover, ip); } } /* Allocate a client_lease structure and initialize it from the parameters in the specified packet. */ struct client_lease * packet_to_lease(struct packet *packet) { struct client_lease *lease; int i; lease = malloc(sizeof(struct client_lease)); if (!lease) { warning("dhcpoffer: no memory to record lease."); return (NULL); } memset(lease, 0, sizeof(*lease)); /* Copy the lease options. */ for (i = 0; i < 256; i++) { if (packet->options[i].len) { lease->options[i].data = malloc(packet->options[i].len + 1); if (!lease->options[i].data) { warning("dhcpoffer: no memory for option %d", i); free_client_lease(lease); return (NULL); } else { memcpy(lease->options[i].data, packet->options[i].data, packet->options[i].len); lease->options[i].len = packet->options[i].len; lease->options[i].data[lease->options[i].len] = 0; } if (!check_option(lease,i)) { /* ignore a bogus lease offer */ warning("Invalid lease option - ignoring offer"); free_client_lease(lease); return (NULL); } } } lease->address.len = sizeof(packet->raw->yiaddr); memcpy(lease->address.iabuf, &packet->raw->yiaddr, lease->address.len); #ifdef __REACTOS__ lease->serveraddress.len = sizeof(packet->raw->siaddr); memcpy(lease->serveraddress.iabuf, &packet->raw->siaddr, lease->address.len); #endif /* If the server name was filled out, copy it. */ if ((!packet->options[<API key>].len || !(packet->options[<API key>].data[0] & 2)) && packet->raw->sname[0]) { lease->server_name = malloc(DHCP_SNAME_LEN + 1); if (!lease->server_name) { warning("dhcpoffer: no memory for server name."); free_client_lease(lease); return (NULL); } memcpy(lease->server_name, packet->raw->sname, DHCP_SNAME_LEN); lease->server_name[DHCP_SNAME_LEN]='\0'; if (!res_hnok(lease->server_name) ) { warning("Bogus server name %s", lease->server_name ); free_client_lease(lease); return (NULL); } } /* Ditto for the filename. */ if ((!packet->options[<API key>].len || !(packet->options[<API key>].data[0] & 1)) && packet->raw->file[0]) { /* Don't count on the NUL terminator. */ lease->filename = malloc(DHCP_FILE_LEN + 1); if (!lease->filename) { warning("dhcpoffer: no memory for filename."); free_client_lease(lease); return (NULL); } memcpy(lease->filename, packet->raw->file, DHCP_FILE_LEN); lease->filename[DHCP_FILE_LEN]='\0'; } return lease; } void dhcpnak(struct packet *packet) { struct interface_info *ip = packet->interface; /* If we're not receptive to an offer right now, or if the offer has an unrecognizable transaction id, then just drop it. */ if (packet->interface->client->xid != packet->raw->xid || (packet->interface->hw_address.hlen != packet->raw->hlen) || (memcmp(packet->interface->hw_address.haddr, packet->raw->chaddr, packet->raw->hlen))) return; if (ip->client->state != S_REBOOTING && ip->client->state != S_REQUESTING && ip->client->state != S_RENEWING && ip->client->state != S_REBINDING) return; note("DHCPNAK from %s", piaddr(packet->client_addr)); if (!ip->client->active) { note("DHCPNAK with no active lease.\n"); return; } free_client_lease(ip->client->active); ip->client->active = NULL; /* Stop sending DHCPREQUEST packets... */ cancel_timeout(send_request, ip); ip->client->state = S_INIT; state_init(ip); } /* Send out a DHCPDISCOVER packet, and set a timeout to send out another one after the right interval has expired. If we don't get an offer by the time we reach the panic interval, call the panic function. */ void send_discover(void *ipp) { struct interface_info *ip = ipp; int interval, increase = 1; time_t cur_time; DH_DbgPrint(MID_TRACE,("Doing discover on interface %p\n",ip)); time(&cur_time); /* Figure out how long it's been since we started transmitting. */ interval = cur_time - ip->client->first_sending; /* If we're past the panic timeout, call the script and tell it we haven't found anything for this interface yet. */ if (interval > ip->client->config->timeout) { state_panic(ip); ip->client->first_sending = cur_time; } /* If we're selecting media, try the whole list before doing the exponential backoff, but if we've already received an offer, stop looping, because we obviously have it right. */ if (!ip->client->offered_leases && ip->client->config->media) { int fail = 0; if (ip->client->medium) { ip->client->medium = ip->client->medium->next; increase = 0; } if (!ip->client->medium) { if (fail) error("No valid media types for %s!", ip->name); ip->client->medium = ip->client->config->media; increase = 1; } note("Trying medium \"%s\" %d", ip->client->medium->string, increase); /* XXX Support other media types eventually */ } /* * If we're supposed to increase the interval, do so. If it's * currently zero (i.e., we haven't sent any packets yet), set * it to one; otherwise, add to it a random number between zero * and two times itself. On average, this means that it will * double with every transmission. */ if (increase) { if (!ip->client->interval) ip->client->interval = ip->client->config->initial_interval; else { ip->client->interval += (rand() >> 2) % (2 * ip->client->interval); } /* Don't backoff past cutoff. */ if (ip->client->interval > ip->client->config->backoff_cutoff) ip->client->interval = ((ip->client->config->backoff_cutoff / 2) + ((rand() >> 2) % ip->client->config->backoff_cutoff)); } else if (!ip->client->interval) ip->client->interval = ip->client->config->initial_interval; /* If the backoff would take us to the panic timeout, just use that as the interval. */ if (cur_time + ip->client->interval > ip->client->first_sending + ip->client->config->timeout) ip->client->interval = (ip->client->first_sending + ip->client->config->timeout) - cur_time + 1; /* Record the number of seconds since we started sending. */ if (interval < 65536) ip->client->packet.secs = htons(interval); else ip->client->packet.secs = htons(65535); ip->client->secs = ip->client->packet.secs; note("DHCPDISCOVER on %s to %s port %d interval %ld", ip->name, inet_ntoa(sockaddr_broadcast.sin_addr), ntohs(sockaddr_broadcast.sin_port), (long int)ip->client->interval); /* Send out a packet. */ (void)send_packet(ip, &ip->client->packet, ip->client->packet_length, inaddr_any, &sockaddr_broadcast, NULL); DH_DbgPrint(MID_TRACE,("discover timeout: now %x -> then %x\n", cur_time, cur_time + ip->client->interval)); add_timeout(cur_time + ip->client->interval, send_discover, ip); } /* * state_panic gets called if we haven't received any offers in a preset * amount of time. When this happens, we try to use existing leases * that haven't yet expired, and failing that, we call the client script * and hope it can do something. */ void state_panic(void *ipp) { struct interface_info *ip = ipp; PDHCP_ADAPTER Adapter = AdapterFindInfo(ip); note("No DHCPOFFERS received."); if (!Adapter->NteContext) { /* Generate an automatic private address */ DbgPrint("DHCPCSVC: Failed to receive a response from a DHCP server. An automatic private address will be assigned.\n"); /* FIXME: The address generation code sucks */ AddIPAddress(htonl(0xA9FE0000 | (rand() % 0xFFFF)), //169.254.X.X htonl(0xFFFF0000), //255.255.0.0 Adapter->IfMib.dwIndex, &Adapter->NteContext, &Adapter->NteInstance); } } void send_request(void *ipp) { struct interface_info *ip = ipp; struct sockaddr_in destination; struct in_addr from; int interval; time_t cur_time; time(&cur_time); /* Figure out how long it's been since we started transmitting. */ interval = cur_time - ip->client->first_sending; /* If we're in the INIT-REBOOT or REQUESTING state and we're past the reboot timeout, go to INIT and see if we can DISCOVER an address... */ /* XXX In the INIT-REBOOT state, if we don't get an ACK, it means either that we're on a network with no DHCP server, or that our server is down. In the latter case, assuming that there is a backup DHCP server, DHCPDISCOVER will get us a new address, but we could also have successfully reused our old address. In the former case, we're hosed anyway. This is not a win-prone situation. */ if ((ip->client->state == S_REBOOTING || ip->client->state == S_REQUESTING) && interval > ip->client->config->reboot_timeout) { ip->client->state = S_INIT; cancel_timeout(send_request, ip); state_init(ip); return; } /* If we're in the reboot state, make sure the media is set up correctly. */ if (ip->client->state == S_REBOOTING && !ip->client->medium && ip->client->active->medium ) { /* If the medium we chose won't fly, go to INIT state. */ /* XXX Nothing for now */ /* Record the medium. */ ip->client->medium = ip->client->active->medium; } /* If the lease has expired, relinquish the address and go back to the INIT state. */ if (ip->client->state != S_REQUESTING && cur_time > ip->client->active->expiry) { PDHCP_ADAPTER Adapter = AdapterFindInfo( ip ); /* Run the client script with the new parameters. */ /* No script actions necessary in the expiry case */ /* Now do a preinit on the interface so that we can discover a new address. */ if( Adapter ) { DeleteIPAddress( Adapter->NteContext ); Adapter->NteContext = 0; } ip->client->state = S_INIT; state_init(ip); return; } /* Do the exponential backoff... */ if (!ip->client->interval) ip->client->interval = ip->client->config->initial_interval; else ip->client->interval += ((rand() >> 2) % (2 * ip->client->interval)); /* Don't backoff past cutoff. */ if (ip->client->interval > ip->client->config->backoff_cutoff) ip->client->interval = ((ip->client->config->backoff_cutoff / 2) + ((rand() >> 2) % ip->client->interval)); /* If the backoff would take us to the expiry time, just set the timeout to the expiry time. */ if (ip->client->state != S_REQUESTING && cur_time + ip->client->interval > ip->client->active->expiry) ip->client->interval = ip->client->active->expiry - cur_time + 1; /* If the lease T2 time has elapsed, or if we're not yet bound, broadcast the DHCPREQUEST rather than unicasting. */ memset(&destination, 0, sizeof(destination)); if (ip->client->state == S_REQUESTING || ip->client->state == S_REBOOTING || cur_time > ip->client->active->rebind) destination.sin_addr.s_addr = INADDR_BROADCAST; else memcpy(&destination.sin_addr.s_addr, ip->client->destination.iabuf, sizeof(destination.sin_addr.s_addr)); destination.sin_port = htons(REMOTE_PORT); destination.sin_family = AF_INET; // destination.sin_len = sizeof(destination); if (ip->client->state != S_REQUESTING) memcpy(&from, ip->client->active->address.iabuf, sizeof(from)); else from.s_addr = INADDR_ANY; /* Record the number of seconds since we started sending. */ if (ip->client->state == S_REQUESTING) ip->client->packet.secs = ip->client->secs; else { if (interval < 65536) ip->client->packet.secs = htons(interval); else ip->client->packet.secs = htons(65535); } note("DHCPREQUEST on %s to %s port %d", ip->name, inet_ntoa(destination.sin_addr), ntohs(destination.sin_port)); /* Send out a packet. */ (void) send_packet(ip, &ip->client->packet, ip->client->packet_length, from, &destination, NULL); add_timeout(cur_time + ip->client->interval, send_request, ip); } void send_decline(void *ipp) { struct interface_info *ip = ipp; note("DHCPDECLINE on %s to %s port %d", ip->name, inet_ntoa(sockaddr_broadcast.sin_addr), ntohs(sockaddr_broadcast.sin_port)); /* Send out a packet. */ (void) send_packet(ip, &ip->client->packet, ip->client->packet_length, inaddr_any, &sockaddr_broadcast, NULL); } void make_discover(struct interface_info *ip, struct client_lease *lease) { unsigned char discover = DHCPDISCOVER; struct tree_cache *options[256]; struct tree_cache option_elements[256]; int i; ULONG foo = (ULONG) GetTickCount(); memset(option_elements, 0, sizeof(option_elements)); memset(options, 0, sizeof(options)); memset(&ip->client->packet, 0, sizeof(ip->client->packet)); /* Set DHCP_MESSAGE_TYPE to DHCPDISCOVER */ i = <API key>; options[i] = &option_elements[i]; options[i]->value = &discover; options[i]->len = sizeof(discover); options[i]->buf_size = sizeof(discover); options[i]->timeout = 0xFFFFFFFF; /* Request the options we want */ i = <API key>; options[i] = &option_elements[i]; options[i]->value = ip->client->config->requested_options; options[i]->len = ip->client->config-><API key>; options[i]->buf_size = ip->client->config-><API key>; options[i]->timeout = 0xFFFFFFFF; /* If we had an address, try to get it again. */ if (lease) { ip->client->requested_address = lease->address; i = <API key>; options[i] = &option_elements[i]; options[i]->value = lease->address.iabuf; options[i]->len = lease->address.len; options[i]->buf_size = lease->address.len; options[i]->timeout = 0xFFFFFFFF; } else ip->client->requested_address.len = 0; /* Send any options requested in the config file. */ for (i = 0; i < 256; i++) if (!options[i] && ip->client->config->send_options[i].data) { options[i] = &option_elements[i]; options[i]->value = ip->client->config->send_options[i].data; options[i]->len = ip->client->config->send_options[i].len; options[i]->buf_size = ip->client->config->send_options[i].len; options[i]->timeout = 0xFFFFFFFF; } /* Set up the option buffer... */ ip->client->packet_length = cons_options(NULL, &ip->client->packet, 0, options, 0, 0, 0, NULL, 0); if (ip->client->packet_length < BOOTP_MIN_LEN) ip->client->packet_length = BOOTP_MIN_LEN; ip->client->packet.op = BOOTREQUEST; ip->client->packet.htype = ip->hw_address.htype; ip->client->packet.hlen = ip->hw_address.hlen; ip->client->packet.hops = 0; ip->client->packet.xid = RtlRandom(&foo); ip->client->packet.secs = 0; /* filled in by send_discover. */ ip->client->packet.flags = 0; memset(&(ip->client->packet.ciaddr), 0, sizeof(ip->client->packet.ciaddr)); memset(&(ip->client->packet.yiaddr), 0, sizeof(ip->client->packet.yiaddr)); memset(&(ip->client->packet.siaddr), 0, sizeof(ip->client->packet.siaddr)); memset(&(ip->client->packet.giaddr), 0, sizeof(ip->client->packet.giaddr)); memcpy(ip->client->packet.chaddr, ip->hw_address.haddr, ip->hw_address.hlen); } void make_request(struct interface_info *ip, struct client_lease * lease) { unsigned char request = DHCPREQUEST; struct tree_cache *options[256]; struct tree_cache option_elements[256]; int i; memset(options, 0, sizeof(options)); memset(&ip->client->packet, 0, sizeof(ip->client->packet)); /* Set DHCP_MESSAGE_TYPE to DHCPREQUEST */ i = <API key>; options[i] = &option_elements[i]; options[i]->value = &request; options[i]->len = sizeof(request); options[i]->buf_size = sizeof(request); options[i]->timeout = 0xFFFFFFFF; /* Request the options we want */ i = <API key>; options[i] = &option_elements[i]; options[i]->value = ip->client->config->requested_options; options[i]->len = ip->client->config-><API key>; options[i]->buf_size = ip->client->config-><API key>; options[i]->timeout = 0xFFFFFFFF; /* If we are requesting an address that hasn't yet been assigned to us, use the DHCP Requested Address option. */ if (ip->client->state == S_REQUESTING) { /* Send back the server identifier... */ i = <API key>; options[i] = &option_elements[i]; options[i]->value = lease->options[i].data; options[i]->len = lease->options[i].len; options[i]->buf_size = lease->options[i].len; options[i]->timeout = 0xFFFFFFFF; } if (ip->client->state == S_REQUESTING || ip->client->state == S_REBOOTING) { ip->client->requested_address = lease->address; i = <API key>; options[i] = &option_elements[i]; options[i]->value = lease->address.iabuf; options[i]->len = lease->address.len; options[i]->buf_size = lease->address.len; options[i]->timeout = 0xFFFFFFFF; } else ip->client->requested_address.len = 0; /* Send any options requested in the config file. */ for (i = 0; i < 256; i++) if (!options[i] && ip->client->config->send_options[i].data) { options[i] = &option_elements[i]; options[i]->value = ip->client->config->send_options[i].data; options[i]->len = ip->client->config->send_options[i].len; options[i]->buf_size = ip->client->config->send_options[i].len; options[i]->timeout = 0xFFFFFFFF; } /* Set up the option buffer... */ ip->client->packet_length = cons_options(NULL, &ip->client->packet, 0, options, 0, 0, 0, NULL, 0); if (ip->client->packet_length < BOOTP_MIN_LEN) ip->client->packet_length = BOOTP_MIN_LEN; ip->client->packet.op = BOOTREQUEST; ip->client->packet.htype = ip->hw_address.htype; ip->client->packet.hlen = ip->hw_address.hlen; ip->client->packet.hops = 0; ip->client->packet.xid = ip->client->xid; ip->client->packet.secs = 0; /* Filled in by send_request. */ /* If we own the address we're requesting, put it in ciaddr; otherwise set ciaddr to zero. */ if (ip->client->state == S_BOUND || ip->client->state == S_RENEWING || ip->client->state == S_REBINDING) { memcpy(&ip->client->packet.ciaddr, lease->address.iabuf, lease->address.len); ip->client->packet.flags = 0; } else { memset(&ip->client->packet.ciaddr, 0, sizeof(ip->client->packet.ciaddr)); ip->client->packet.flags = 0; } memset(&ip->client->packet.yiaddr, 0, sizeof(ip->client->packet.yiaddr)); memset(&ip->client->packet.siaddr, 0, sizeof(ip->client->packet.siaddr)); memset(&ip->client->packet.giaddr, 0, sizeof(ip->client->packet.giaddr)); memcpy(ip->client->packet.chaddr, ip->hw_address.haddr, ip->hw_address.hlen); } void make_decline(struct interface_info *ip, struct client_lease *lease) { struct tree_cache *options[256], message_type_tree; struct tree_cache <API key>; struct tree_cache server_id_tree, client_id_tree; unsigned char decline = DHCPDECLINE; int i; memset(options, 0, sizeof(options)); memset(&ip->client->packet, 0, sizeof(ip->client->packet)); /* Set DHCP_MESSAGE_TYPE to DHCPDECLINE */ i = <API key>; options[i] = &message_type_tree; options[i]->value = &decline; options[i]->len = sizeof(decline); options[i]->buf_size = sizeof(decline); options[i]->timeout = 0xFFFFFFFF; /* Send back the server identifier... */ i = <API key>; options[i] = &server_id_tree; options[i]->value = lease->options[i].data; options[i]->len = lease->options[i].len; options[i]->buf_size = lease->options[i].len; options[i]->timeout = 0xFFFFFFFF; /* Send back the address we're declining. */ i = <API key>; options[i] = &<API key>; options[i]->value = lease->address.iabuf; options[i]->len = lease->address.len; options[i]->buf_size = lease->address.len; options[i]->timeout = 0xFFFFFFFF; /* Send the uid if the user supplied one. */ i = <API key>; if (ip->client->config->send_options[i].len) { options[i] = &client_id_tree; options[i]->value = ip->client->config->send_options[i].data; options[i]->len = ip->client->config->send_options[i].len; options[i]->buf_size = ip->client->config->send_options[i].len; options[i]->timeout = 0xFFFFFFFF; } /* Set up the option buffer... */ ip->client->packet_length = cons_options(NULL, &ip->client->packet, 0, options, 0, 0, 0, NULL, 0); if (ip->client->packet_length < BOOTP_MIN_LEN) ip->client->packet_length = BOOTP_MIN_LEN; ip->client->packet.op = BOOTREQUEST; ip->client->packet.htype = ip->hw_address.htype; ip->client->packet.hlen = ip->hw_address.hlen; ip->client->packet.hops = 0; ip->client->packet.xid = ip->client->xid; ip->client->packet.secs = 0; /* Filled in by send_request. */ ip->client->packet.flags = 0; /* ciaddr must always be zero. */ memset(&ip->client->packet.ciaddr, 0, sizeof(ip->client->packet.ciaddr)); memset(&ip->client->packet.yiaddr, 0, sizeof(ip->client->packet.yiaddr)); memset(&ip->client->packet.siaddr, 0, sizeof(ip->client->packet.siaddr)); memset(&ip->client->packet.giaddr, 0, sizeof(ip->client->packet.giaddr)); memcpy(ip->client->packet.chaddr, ip->hw_address.haddr, ip->hw_address.hlen); } void free_client_lease(struct client_lease *lease) { int i; if (lease->server_name) free(lease->server_name); if (lease->filename) free(lease->filename); for (i = 0; i < 256; i++) { if (lease->options[i].len) free(lease->options[i].data); } free(lease); } FILE *leaseFile; void <API key>(struct interface_info *ifi) { struct client_lease *lp; if (!leaseFile) { leaseFile = fopen(path_dhclient_db, "w"); if (!leaseFile) error("can't create %s", path_dhclient_db); } else { fflush(leaseFile); rewind(leaseFile); } for (lp = ifi->client->leases; lp; lp = lp->next) write_client_lease(ifi, lp, 1); if (ifi->client->active) write_client_lease(ifi, ifi->client->active, 1); fflush(leaseFile); } void write_client_lease(struct interface_info *ip, struct client_lease *lease, int rewrite) { static int leases_written; struct tm *t; int i; if (!rewrite) { if (leases_written++ > 20) { <API key>(ip); leases_written = 0; } } /* If the lease came from the config file, we don't need to stash a copy in the lease database. */ if (lease->is_static) return; if (!leaseFile) { /* XXX */ leaseFile = fopen(path_dhclient_db, "w"); if (!leaseFile) { error("can't create %s", path_dhclient_db); return; } } fprintf(leaseFile, "lease {\n"); if (lease->is_bootp) fprintf(leaseFile, " bootp;\n"); fprintf(leaseFile, " interface \"%s\";\n", ip->name); fprintf(leaseFile, " fixed-address %s;\n", piaddr(lease->address)); if (lease->filename) fprintf(leaseFile, " filename \"%s\";\n", lease->filename); if (lease->server_name) fprintf(leaseFile, " server-name \"%s\";\n", lease->server_name); if (lease->medium) fprintf(leaseFile, " medium \"%s\";\n", lease->medium->string); for (i = 0; i < 256; i++) if (lease->options[i].len) fprintf(leaseFile, " option %s %s;\n", dhcp_options[i].name, pretty_print_option(i, lease->options[i].data, lease->options[i].len, 1, 1)); t = gmtime(&lease->renewal); if (t) fprintf(leaseFile, " renew %d %d/%d/%d %02d:%02d:%02d;\n", t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); t = gmtime(&lease->rebind); if (t) fprintf(leaseFile, " rebind %d %d/%d/%d %02d:%02d:%02d;\n", t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); t = gmtime(&lease->expiry); if (t) fprintf(leaseFile, " expire %d %d/%d/%d %02d:%02d:%02d;\n", t->tm_wday, t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); fprintf(leaseFile, "}\n"); fflush(leaseFile); } void priv_script_init(struct interface_info *ip, char *reason, char *medium) { if (ip) { // XXX Do we need to do anything? } } void <API key>(struct interface_info *ip, char *prefix, struct client_lease *lease) { u_int8_t dbuf[1500]; int i, len = 0; #if 0 script_set_env(ip->client, prefix, "ip_address", piaddr(lease->address)); #endif if (lease->options[DHO_SUBNET_MASK].len && (lease->options[DHO_SUBNET_MASK].len < sizeof(lease->address.iabuf))) { struct iaddr netmask, subnet, broadcast; memcpy(netmask.iabuf, lease->options[DHO_SUBNET_MASK].data, lease->options[DHO_SUBNET_MASK].len); netmask.len = lease->options[DHO_SUBNET_MASK].len; subnet = subnet_number(lease->address, netmask); if (subnet.len) { #if 0 script_set_env(ip->client, prefix, "network_number", piaddr(subnet)); #endif if (!lease->options[<API key>].len) { broadcast = broadcast_addr(subnet, netmask); if (broadcast.len) #if 0 script_set_env(ip->client, prefix, "broadcast_address", piaddr(broadcast)); #else ; #endif } } } #if 0 if (lease->filename) script_set_env(ip->client, prefix, "filename", lease->filename); if (lease->server_name) script_set_env(ip->client, prefix, "server_name", lease->server_name); #endif for (i = 0; i < 256; i++) { u_int8_t *dp = NULL; if (ip->client->config->defaults[i].len) { if (lease->options[i].len) { switch ( ip->client->config->default_actions[i]) { case ACTION_DEFAULT: dp = lease->options[i].data; len = lease->options[i].len; break; case ACTION_SUPERSEDE: supersede: dp = ip->client-> config->defaults[i].data; len = ip->client-> config->defaults[i].len; break; case ACTION_PREPEND: len = ip->client-> config->defaults[i].len + lease->options[i].len; if (len >= sizeof(dbuf)) { warning("no space to %s %s", "prepend option", dhcp_options[i].name); goto supersede; } dp = dbuf; memcpy(dp, ip->client-> config->defaults[i].data, ip->client-> config->defaults[i].len); memcpy(dp + ip->client-> config->defaults[i].len, lease->options[i].data, lease->options[i].len); dp[len] = '\0'; break; case ACTION_APPEND: len = ip->client-> config->defaults[i].len + lease->options[i].len + 1; if (len > sizeof(dbuf)) { warning("no space to %s %s", "append option", dhcp_options[i].name); goto supersede; } dp = dbuf; memcpy(dp, lease->options[i].data, lease->options[i].len); memcpy(dp + lease->options[i].len, ip->client-> config->defaults[i].data, ip->client-> config->defaults[i].len); dp[len-1] = '\0'; } } else { dp = ip->client-> config->defaults[i].data; len = ip->client-> config->defaults[i].len; } } else if (lease->options[i].len) { len = lease->options[i].len; dp = lease->options[i].data; } else { len = 0; } #if 0 if (len) { char name[256]; if (dhcp_option_ev_name(name, sizeof(name), &dhcp_options[i])) script_set_env(ip->client, prefix, name, pretty_print_option(i, dp, len, 0, 0)); } #endif } #if 0 snprintf(tbuf, sizeof(tbuf), "%d", (int)lease->expiry); script_set_env(ip->client, prefix, "expiry", tbuf); #endif } int dhcp_option_ev_name(char *buf, size_t buflen, struct dhcp_option *option) { int i; for (i = 0; option->name[i]; i++) { if (i + 1 == buflen) return 0; if (option->name[i] == '-') buf[i] = '_'; else buf[i] = option->name[i]; } buf[i] = 0; return 1; } #if 0 void go_daemon(void) { static int state = 0; if (no_daemon || state) return; state = 1; /* Stop logging to stderr... */ log_perror = 0; if (daemon(1, 0) == -1) error("daemon"); /* we are chrooted, daemon(3) fails to open /dev/null */ if (nullfd != -1) { dup2(nullfd, STDIN_FILENO); dup2(nullfd, STDOUT_FILENO); dup2(nullfd, STDERR_FILENO); close(nullfd); nullfd = -1; } } #endif int check_option(struct client_lease *l, int option) { char *opbuf; char *sbuf; /* we use this, since this is what gets passed to dhclient-script */ opbuf = pretty_print_option(option, l->options[option].data, l->options[option].len, 0, 0); sbuf = option_as_string(option, l->options[option].data, l->options[option].len); switch (option) { case DHO_SUBNET_MASK: case DHO_TIME_SERVERS: case DHO_NAME_SERVERS: case DHO_ROUTERS: case <API key>: case DHO_LOG_SERVERS: case DHO_COOKIE_SERVERS: case DHO_LPR_SERVERS: case DHO_IMPRESS_SERVERS: case <API key>: case DHO_SWAP_SERVER: case <API key>: case DHO_NIS_SERVERS: case DHO_NTP_SERVERS: case <API key>: case <API key>: case DHO_FONT_SERVERS: case <API key>: if (!ipv4addrs(opbuf)) { warning("Invalid IP address in option(%d): %s", option, opbuf); return (0); } return (1) ; case DHO_HOST_NAME: case DHO_DOMAIN_NAME: case DHO_NIS_DOMAIN: if (!res_hnok(sbuf)) warning("Bogus Host Name option %d: %s (%s)", option, sbuf, opbuf); return (1); case DHO_PAD: case DHO_TIME_OFFSET: case DHO_BOOT_SIZE: case DHO_MERIT_DUMP: case DHO_ROOT_PATH: case DHO_EXTENSIONS_PATH: case DHO_IP_FORWARDING: case <API key>: case DHO_POLICY_FILTER: case <API key>: case DHO_DEFAULT_IP_TTL: case <API key>: case <API key>: case DHO_INTERFACE_MTU: case <API key>: case <API key>: case DHO_MASK_SUPPLIER: case <API key>: case <API key>: case DHO_STATIC_ROUTES: case <API key>: case <API key>: case <API key>: case DHO_DEFAULT_TCP_TTL: case <API key>: case <API key>: case <API key>: case <API key>: case DHO_NETBIOS_SCOPE: case <API key>: case <API key>: case DHO_DHCP_LEASE_TIME: case <API key>: case <API key>: case <API key>: case DHO_DHCP_MESSAGE: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case DHO_END: return (1); default: warning("unknown dhcp option value 0x%x", option); return (unknown_ok); } } int res_hnok(const char *dn) { int pch = PERIOD, ch = *dn++; while (ch != '\0') { int nch = *dn++; if (periodchar(ch)) { ; } else if (periodchar(pch)) { if (!borderchar(ch)) return (0); } else if (periodchar(nch) || nch == '\0') { if (!borderchar(ch)) return (0); } else { if (!middlechar(ch)) return (0); } pch = ch, ch = nch; } return (1); } /* Does buf consist only of dotted decimal ipv4 addrs? * return how many if so, * otherwise, return 0 */ int ipv4addrs(char * buf) { char *tmp; struct in_addr jnk; int i = 0; note("Input: %s", buf); do { tmp = strtok(buf, " "); note("got %s", tmp); if( tmp && inet_aton(tmp, &jnk) ) i++; buf = NULL; } while( tmp ); return (i); } char * option_as_string(unsigned int code, unsigned char *data, int len) { static char optbuf[32768]; /* XXX */ char *op = optbuf; int opleft = sizeof(optbuf); unsigned char *dp = data; if (code > 255) error("option_as_string: bad code %d", code); for (; dp < data + len; dp++) { if (!isascii(*dp) || !isprint(*dp)) { if (dp + 1 != data + len || *dp != 0) { _snprintf(op, opleft, "\\%03o", *dp); op += 4; opleft -= 4; } } else if (*dp == '"' || *dp == '\'' || *dp == '$' || *dp == '`' || *dp == '\\') { *op++ = '\\'; *op++ = *dp; opleft -= 2; } else { *op++ = *dp; opleft } } if (opleft < 1) goto toobig; *op = 0; return optbuf; toobig: warning("dhcp option too large"); return "<error>"; }
#include "Mp_Precomp.h" #include "../phydm_precomp.h" // 2010/04/25 MH Define the max tx power tracking tx agc power. #define <API key> 6 //3 Tx Power Tracking VOID <API key>( PDM_ODM_T pDM_Odm, PWRTRACK_METHOD Method, u1Byte RFPath, u1Byte ChannelMappedIndex ) { PADAPTER Adapter = pDM_Odm->Adapter; PHAL_DATA_TYPE pHalData = GET_HAL_DATA(Adapter); u1Byte PwrTrackingLimit = 26; //+1.0dB u1Byte TxRate = 0xFF; u1Byte <API key> = 0; u1Byte <API key> = 0; //u1Byte i = 0; u4Byte finalBbSwingIdx[1]; if (pDM_Odm->mp_mode == TRUE) { #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN|ODM_CE )) #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN)) PMPT_CONTEXT pMptCtx = &(Adapter->MptCtx); #elif (DM_ODM_SUPPORT_TYPE & (ODM_CE)) PMPT_CONTEXT pMptCtx = &(Adapter->mppriv.MptCtx); #endif TxRate = MptToMgntRate(pMptCtx->MptRateIndex); #endif } else { u2Byte rate = *(pDM_Odm->pForcedDataRate); if(!rate) { //auto rate if(pDM_Odm->TxRate != 0xFF) #if (DM_ODM_SUPPORT_TYPE & (ODM_WIN)) TxRate = Adapter->HalFunc.<API key>(pDM_Odm->TxRate); #elif (DM_ODM_SUPPORT_TYPE & (ODM_CE)) TxRate = HwRateToMRate(pDM_Odm->TxRate); #endif } else { //force rate TxRate = (u1Byte)rate; } } ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("===><API key>\n")); if(TxRate != 0xFF) { //2 CCK if((TxRate >= MGN_1M)&&(TxRate <= MGN_11M)) PwrTrackingLimit = 32; //+4dB //2 OFDM else if((TxRate >= MGN_6M)&&(TxRate <= MGN_48M)) PwrTrackingLimit = 30; //+3dB else if(TxRate == MGN_54M) PwrTrackingLimit = 28; //+2dB //2 HT else if((TxRate >= MGN_MCS0)&&(TxRate <= MGN_MCS2)) //QPSK/BPSK PwrTrackingLimit = 34; //+5dB else if((TxRate >= MGN_MCS3)&&(TxRate <= MGN_MCS4)) //16QAM PwrTrackingLimit = 30; //+3dB else if((TxRate >= MGN_MCS5)&&(TxRate <= MGN_MCS7)) //64QAM PwrTrackingLimit = 28; //+2dB //2 VHT else if((TxRate >= MGN_VHT1SS_MCS0)&&(TxRate <= MGN_VHT1SS_MCS2)) //QPSK/BPSK PwrTrackingLimit = 34; //+5dB else if((TxRate >= MGN_VHT1SS_MCS3)&&(TxRate <= MGN_VHT1SS_MCS4)) //16QAM PwrTrackingLimit = 30; //+3dB else if((TxRate >= MGN_VHT1SS_MCS5)&&(TxRate <= MGN_VHT1SS_MCS6)) //64QAM PwrTrackingLimit = 28; //+2dB else if(TxRate == MGN_VHT1SS_MCS7) //64QAM PwrTrackingLimit = 26; //+1dB else if(TxRate == MGN_VHT1SS_MCS8) //256QAM PwrTrackingLimit = 24; //+0dB else if(TxRate == MGN_VHT1SS_MCS9) //256QAM PwrTrackingLimit = 22; //-1dB else PwrTrackingLimit = 24; } ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("TxRate=0x%x, PwrTrackingLimit=%d\n", TxRate, PwrTrackingLimit)); if (Method == BBSWING) { if (RFPath == ODM_RF_PATH_A) { finalBbSwingIdx[ODM_RF_PATH_A] = (pDM_Odm->RFCalibrateInfo.OFDM_index[ODM_RF_PATH_A] > PwrTrackingLimit) ? PwrTrackingLimit : pDM_Odm->RFCalibrateInfo.OFDM_index[ODM_RF_PATH_A]; ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("pDM_Odm->RFCalibrateInfo.OFDM_index[ODM_RF_PATH_A]=%d, pDM_Odm->RealBbSwingIdx[ODM_RF_PATH_A]=%d\n", pDM_Odm->RFCalibrateInfo.OFDM_index[ODM_RF_PATH_A], finalBbSwingIdx[ODM_RF_PATH_A])); ODM_SetBBReg(pDM_Odm, rA_TxScale_Jaguar, 0xFFE00000, <API key>[finalBbSwingIdx[ODM_RF_PATH_A]]); } } else if (Method == MIX_MODE) { ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("pDM_Odm->DefaultOfdmIndex=%d, pDM_Odm-><API key>[RFPath]=%d, RF_Path = %d\n", pDM_Odm->DefaultOfdmIndex, pDM_Odm-><API key>[RFPath],RFPath )); <API key> = pDM_Odm->DefaultCckIndex + pDM_Odm-><API key>[RFPath]; <API key> = pDM_Odm->DefaultOfdmIndex + pDM_Odm-><API key>[RFPath]; if (RFPath == ODM_RF_PATH_A) { if(<API key> > PwrTrackingLimit) { //BBSwing higher then Limit pDM_Odm->Remnant_CCKSwingIdx= <API key> - PwrTrackingLimit; pDM_Odm-><API key>[RFPath] = <API key> - PwrTrackingLimit; ODM_SetBBReg(pDM_Odm, rA_TxScale_Jaguar, 0xFFE00000, <API key>[PwrTrackingLimit]); pDM_Odm-><API key>= TRUE; <API key>(Adapter, pHalData->CurrentChannel, ODM_RF_PATH_A); ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("******Path_A Over BBSwing Limit , PwrTrackingLimit = %d , Remnant TxAGC Value = %d \n", PwrTrackingLimit, pDM_Odm-><API key>[RFPath])); } else if (<API key> <= 0) { pDM_Odm->Remnant_CCKSwingIdx= <API key>; pDM_Odm-><API key>[RFPath] = <API key>; ODM_SetBBReg(pDM_Odm, rA_TxScale_Jaguar, 0xFFE00000, <API key>[0]); pDM_Odm-><API key>= TRUE; <API key>(Adapter, pHalData->CurrentChannel, ODM_RF_PATH_A); ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("******Path_A Lower then BBSwing lower bound 0 , Remnant TxAGC Value = %d \n", pDM_Odm-><API key>[RFPath])); } else { ODM_SetBBReg(pDM_Odm, rA_TxScale_Jaguar, 0xFFE00000, <API key>[<API key>]); ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("******Path_A Compensate with BBSwing , <API key> = %d \n", <API key>)); if(pDM_Odm-><API key>) { //If TxAGC has changed, reset TxAGC again pDM_Odm->Remnant_CCKSwingIdx= 0; pDM_Odm-><API key>[RFPath] = 0; <API key>(Adapter, pHalData->CurrentChannel, ODM_RF_PATH_A); pDM_Odm-><API key>= FALSE; ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD,("******Path_A pDM_Odm->Modify_TxAGC_Flag = FALSE \n")); } } } } else { return; } } // <API key> VOID <API key>( IN PDM_ODM_T pDM_Odm, OUT pu1Byte *TemperatureUP_A, OUT pu1Byte *TemperatureDOWN_A, OUT pu1Byte *TemperatureUP_B, OUT pu1Byte *TemperatureDOWN_B ) { PADAPTER Adapter = pDM_Odm->Adapter; PODM_RF_CAL_T pRFCalibrateInfo = &(pDM_Odm->RFCalibrateInfo); HAL_DATA_TYPE *pHalData = GET_HAL_DATA(Adapter); u2Byte rate = *(pDM_Odm->pForcedDataRate); u1Byte channel = pHalData->CurrentChannel; if ( 1 <= channel && channel <= 14) { if (IS_CCK_RATE(rate)) { *TemperatureUP_A = pRFCalibrateInfo-><API key>; *TemperatureDOWN_A = pRFCalibrateInfo-><API key>; *TemperatureUP_B = pRFCalibrateInfo-><API key>; *TemperatureDOWN_B = pRFCalibrateInfo-><API key>; } else { *TemperatureUP_A = pRFCalibrateInfo-><API key>; *TemperatureDOWN_A = pRFCalibrateInfo-><API key>; *TemperatureUP_B = pRFCalibrateInfo-><API key>; *TemperatureDOWN_B = pRFCalibrateInfo-><API key>; } } else if ( 36 <= channel && channel <= 64) { *TemperatureUP_A = pRFCalibrateInfo-><API key>[0]; *TemperatureDOWN_A = pRFCalibrateInfo-><API key>[0]; *TemperatureUP_B = pRFCalibrateInfo-><API key>[0]; *TemperatureDOWN_B = pRFCalibrateInfo-><API key>[0]; } else if ( 100 <= channel && channel <= 140) { *TemperatureUP_A = pRFCalibrateInfo-><API key>[1]; *TemperatureDOWN_A = pRFCalibrateInfo-><API key>[1]; *TemperatureUP_B = pRFCalibrateInfo-><API key>[1]; *TemperatureDOWN_B = pRFCalibrateInfo-><API key>[1]; } else if ( 149 <= channel && channel <= 173) { *TemperatureUP_A = pRFCalibrateInfo-><API key>[2]; *TemperatureDOWN_A = pRFCalibrateInfo-><API key>[2]; *TemperatureUP_B = pRFCalibrateInfo-><API key>[2]; *TemperatureDOWN_B = pRFCalibrateInfo-><API key>[2]; } else { *TemperatureUP_A = (pu1Byte)<API key>; *TemperatureDOWN_A = (pu1Byte)<API key>; *TemperatureUP_B = (pu1Byte)<API key>; *TemperatureDOWN_B = (pu1Byte)<API key>; } return; } void <API key>( PTXPWRTRACK_CFG pConfig ) { pConfig->SwingTableSize_CCK = TXSCALE_TABLE_SIZE; pConfig->SwingTableSize_OFDM = TXSCALE_TABLE_SIZE; pConfig->Threshold_IQK = IQK_THRESHOLD; pConfig->AverageThermalNum = <API key>; pConfig->RfPathCount = MAX_PATH_NUM_8821A; pConfig->ThermalRegAddr = RF_T_METER_8812A; pConfig-><API key> = <API key>; pConfig->DoIQK = DoIQK_8821A; pConfig->PHY_LCCalibrate = <API key>; pConfig->GetDeltaSwingTable = <API key>; } #define DP_BB_REG_NUM 7 #define DP_RF_REG_NUM 1 #define DP_RETRY_LIMIT 10 #define DP_PATH_NUM 2 #define DP_DPK_NUM 3 #define DP_DPK_VALUE_NUM 2 VOID <API key>( IN PDM_ODM_T pDM_Odm ) { u8Byte StartTime; u8Byte ProgressingTime; StartTime = ODM_GetCurrentTime( pDM_Odm); <API key>(pDM_Odm); ProgressingTime = <API key>( pDM_Odm, StartTime); ODM_RT_TRACE(pDM_Odm,<API key>, ODM_DBG_LOUD, ("LCK ProgressingTime = %lld\n", ProgressingTime)); }
<html lang="en"> <head> <title>GENERIC - GNU Compiler Collection (GCC) Internals</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="GNU Compiler Collection (GCC) Internals"> <meta name="generator" content="makeinfo 4.7"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Tree-SSA.html#Tree-SSA" title="Tree SSA"> <link rel="next" href="GIMPLE.html#GIMPLE" title="GIMPLE"> <link href="http: <! Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with the Invariant Sections being ``GNU General Public License'' and ``Funding Free Software'', the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled ``GNU Free Documentation License''. (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development. <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><! pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family: serif; font-weight: normal; } --></style> </head> <body> <div class="node"> <p> <a name="GENERIC"></a>Next:&nbsp;<a rel="next" accesskey="n" href="GIMPLE.html#GIMPLE">GIMPLE</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Tree-SSA.html#Tree-SSA">Tree SSA</a> <hr><br> </div> <h3 class="section">10.1 GENERIC</h3> <p><a name="index-GENERIC-2068"></a> The purpose of GENERIC is simply to provide a <API key> way of representing an entire function in trees. To this end, it was necessary to add a few new tree codes to the back end, but most everything was already there. If you can express it with the codes in <code>gcc/tree.def</code>, it's GENERIC. <p>Early on, there was a great deal of debate about how to think about statements in a tree IL. In GENERIC, a statement is defined as any expression whose value, if any, is ignored. A statement will always have <code>TREE_SIDE_EFFECTS</code> set (or it will be discarded), but a non-statement expression may also have side effects. A <code>CALL_EXPR</code>, for instance. <p>It would be possible for some local optimizations to work on the GENERIC form of a function; indeed, the adapted tree inliner works fine on GENERIC, but the current compiler performs inlining after lowering to GIMPLE (a restricted form described in the next section). Indeed, currently the frontends perform this lowering before handing off to <code><API key></code>, but this seems inelegant. <p>If necessary, a front end can use some language-dependent tree codes in its GENERIC representation, so long as it provides a hook for converting them to GIMPLE and doesn't expect them to work with any (hypothetical) optimizers that run before the conversion to GIMPLE. The intermediate representation used while parsing C and C++ looks very little like GENERIC, but the C and C++ gimplifier hooks are perfectly happy to take it as input and spit out GIMPLE. </body></html>
# This is required for 1.1.6 support class Module def alias_method_chain(target, feature) # Strip out punctuation on predicates or bang methods since # e.g. target?_without_feature is not a valid method name. aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 yield(aliased_target, punctuation) if block_given? alias_method "#{aliased_target}_without_#{feature}#{punctuation}", target alias_method target, "#{aliased_target}_with_#{feature}#{punctuation}" end end
<?php /** * oAuth My Applications controller * * Tab "My Applications" in the Customer Account * * @category Mage * @package Mage_Oauth * @author Magento Core Team <core@magentocommerce.com> */ class Mage_O<API key> extends <API key> { /** * Customer session model * * @var <API key> */ protected $_session; /** * Customer session model * * @var <API key> */ protected $_sessionName = 'customer/session'; /** * Check authentication * * Check customer authentication for some actions */ public function preDispatch() { parent::preDispatch(); $this->_session = Mage::getSingleton($this->_sessionName); if (!$this->_session->authenticate($this)) { $this->setFlag('', self::FLAG_NO_DISPATCH, true); } } /** * Render grid page */ public function indexAction() { $this->loadLayout(); $this->_initLayoutMessages($this->_sessionName); $this->renderLayout(); } /** * Redirect to referrer URL or otherwise to index page without params * * @return Mage_O<API key> */ protected function _redirectBack() { $url = $this->_getRefererUrl(); if (Mage::app()->getStore()->getBaseUrl() == $url) { $url = Mage::getUrl('*/*/index'); } $this->_redirectUrl($url); return $this; } /** * Update revoke status action */ public function revokeAction() { $id = $this->getRequest()->getParam('id'); $status = $this->getRequest()->getParam('status'); if (0 === (int) $id) { // No ID $this->_session->addError($this->__('Invalid entry ID.')); $this->_redirectBack(); return; } if (null === $status) { // No status selected $this->_session->addError($this->__('Invalid revoke status.')); $this->_redirectBack(); return; } try { /** @var $collection Mage_O<API key> */ $collection = Mage::getModel('oauth/token')->getCollection(); $collection-><API key>() -><API key>($this->_session->getCustomerId()) ->addFilterById($id) ->addFilterByType(<API key>::TYPE_ACCESS) ->addFilterByRevoked(!$status); //here is can be load from model, but used from collection for get consumer name /** @var $model <API key> */ $model = $collection->getFirstItem(); if ($model->getId()) { $name = $model->getName(); $model->load($model->getId()); $model->setRevoked($status)->save(); if ($status) { $message = $this->__('Application "%s" has been revoked.', $name); } else { $message = $this->__('Application "%s" has been enabled.', $name); } $this->_session->addSuccess($message); } else { $this->_session->addError($this->__('Application not found.')); } } catch (Mage_Core_Exception $e) { $this->_session->addError($e->getMessage()); } catch (Exception $e) { $this->_session->addError($this->__('An error occurred on update revoke status.')); Mage::logException($e); } $this->_redirectBack(); } /** * Delete action */ public function deleteAction() { $id = $this->getRequest()->getParam('id'); if (0 === (int) $id) { // No ID $this->_session->addError($this->__('Invalid entry ID.')); $this->_redirectBack(); return; } try { /** @var $collection Mage_O<API key> */ $collection = Mage::getModel('oauth/token')->getCollection(); $collection-><API key>() -><API key>($this->_session->getCustomerId()) ->addFilterByType(<API key>::TYPE_ACCESS) ->addFilterById($id); /** @var $model <API key> */ $model = $collection->getFirstItem(); if ($model->getId()) { $name = $model->getName(); $model->delete(); $this->_session->addSuccess( $this->__('Application "%s" has been deleted.', $name)); } else { $this->_session->addError($this->__('Application not found.')); } } catch (Mage_Core_Exception $e) { $this->_session->addError($e->getMessage()); } catch (Exception $e) { $this->_session->addError($this->__('An error occurred on delete application.')); Mage::logException($e); } $this->_redirectBack(); } }
// List.cpp #include "StdAfx.h" #include "../../../Common/IntToString.h" #include "../../../Common/MyCom.h" #include "../../../Common/StdOutStream.h" #include "../../../Common/StringConvert.h" #include "../../../Common/UTFConvert.h" #include "../../../Windows/ErrorMsg.h" #include "../../../Windows/FileDir.h" #include "../../../Windows/PropVariant.h" #include "../../../Windows/PropVariantConv.h" #include "../Common/OpenArchive.h" #include "../Common/PropIDUtils.h" #include "ConsoleClose.h" #include "List.h" #include "OpenCallbackConsole.h" using namespace NWindows; using namespace NCOM; extern CStdOutStream *g_StdStream; extern CStdOutStream *g_ErrStream; static const char * const kPropIdToName[] = { "0" , "1" , "2" , "Path" , "Name" , "Extension" , "Folder" , "Size" , "Packed Size" , "Attributes" , "Created" , "Accessed" , "Modified" , "Solid" , "Commented" , "Encrypted" , "Split Before" , "Split After" , "Dictionary Size" , "CRC" , "Type" , "Anti" , "Method" , "Host OS" , "File System" , "User" , "Group" , "Block" , "Comment" , "Position" , "Path Prefix" , "Folders" , "Files" , "Version" , "Volume" , "Multivolume" , "Offset" , "Links" , "Blocks" , "Volumes" , "Time Type" , "64-bit" , "Big-endian" , "CPU" , "Physical Size" , "Headers Size" , "Checksum" , "Characteristics" , "Virtual Address" , "ID" , "Short Name" , "Creator Application" , "Sector Size" , "Mode" , "Symbolic Link" , "Error" , "Total Size" , "Free Space" , "Cluster Size" , "Label" , "Local Name" , "Provider" , "NT Security" , "Alternate Stream" , "Aux" , "Deleted" , "Tree" , "SHA-1" , "SHA-256" , "Error Type" , "Errors" , "Errors" , "Warnings" , "Warning" , "Streams" , "Alternate Streams" , "Alternate Streams Size" , "Virtual Size" , "Unpack Size" , "Total Physical Size" , "Volume Index" , "SubType" , "Short Comment" , "Code Page" , "Is not archive type" , "Physical Size can't be detected" , "Zeros Tail Is Allowed" , "Tail Size" , "Embedded Stub Size" , "Link" , "Hard Link" , "iNode" , "Stream ID" , "Read-only" , "Out Name" , "Copy Link" }; static const char kEmptyAttribChar = '.'; static const char * const kListing = "Listing archive: "; static const char * const kString_Files = "files"; static const char * const kString_Dirs = "folders"; static const char * const kString_AltStreams = "alternate streams"; static const char * const kString_Streams = "streams"; static const char * const kError = "ERROR: "; static void GetAttribString(UInt32 wa, bool isDir, bool allAttribs, char *s) { if (isDir) wa |= <API key>; if (allAttribs) { <API key>(s, wa); return; } s[0] = ((wa & <API key>) != 0) ? 'D': kEmptyAttribChar; s[1] = ((wa & <API key>) != 0) ? 'R': kEmptyAttribChar; s[2] = ((wa & <API key>) != 0) ? 'H': kEmptyAttribChar; s[3] = ((wa & <API key>) != 0) ? 'S': kEmptyAttribChar; s[4] = ((wa & <API key>) != 0) ? 'A': kEmptyAttribChar; s[5] = 0; } enum EAdjustment { kLeft, kCenter, kRight }; struct CFieldInfo { PROPID PropID; bool IsRawProp; UString NameU; AString NameA; EAdjustment TitleAdjustment; EAdjustment TextAdjustment; unsigned PrefixSpacesWidth; unsigned Width; }; struct CFieldInfoInit { PROPID PropID; const char *Name; EAdjustment TitleAdjustment; EAdjustment TextAdjustment; unsigned PrefixSpacesWidth; unsigned Width; }; static const CFieldInfoInit kStandardFieldTable[] = { { kpidMTime, " Date Time", kLeft, kLeft, 0, 19 }, { kpidAttrib, "Attr", kRight, kCenter, 1, 5 }, { kpidSize, "Size", kRight, kRight, 1, 12 }, { kpidPackSize, "Compressed", kRight, kRight, 1, 12 }, { kpidPath, "Name", kLeft, kLeft, 2, 24 } }; const unsigned kNumSpacesMax = 32; // it must be larger than max CFieldInfoInit.Width static const char *g_Spaces = " " ; static void PrintSpaces(unsigned numSpaces) { if (numSpaces > 0 && numSpaces <= kNumSpacesMax) g_StdOut << g_Spaces + (kNumSpacesMax - numSpaces); } static void PrintSpacesToString(char *dest, unsigned numSpaces) { unsigned i; for (i = 0; i < numSpaces; i++) dest[i] = ' '; dest[i] = 0; } // extern int g_CodePage; static void PrintUString(EAdjustment adj, unsigned width, const UString &s, AString &temp) { /* // we don't need multibyte align. int codePage = g_CodePage; if (codePage == -1) codePage = CP_OEMCP; if (codePage == CP_UTF8) <API key>(s, temp); else <API key>(temp, s, (UINT)codePage); */ unsigned numSpaces = 0; if (width > s.Len()) { numSpaces = width - s.Len(); unsigned numLeftSpaces = 0; switch (adj) { case kLeft: numLeftSpaces = 0; break; case kCenter: numLeftSpaces = numSpaces / 2; break; case kRight: numLeftSpaces = numSpaces; break; } PrintSpaces(numLeftSpaces); numSpaces -= numLeftSpaces; } g_StdOut.PrintUString(s, temp); PrintSpaces(numSpaces); } static void PrintString(EAdjustment adj, unsigned width, const char *s) { unsigned numSpaces = 0; unsigned len = (unsigned)strlen(s); if (width > len) { numSpaces = width - len; unsigned numLeftSpaces = 0; switch (adj) { case kLeft: numLeftSpaces = 0; break; case kCenter: numLeftSpaces = numSpaces / 2; break; case kRight: numLeftSpaces = numSpaces; break; } PrintSpaces(numLeftSpaces); numSpaces -= numLeftSpaces; } g_StdOut << s; PrintSpaces(numSpaces); } static void PrintStringToString(char *dest, EAdjustment adj, unsigned width, const char *textString) { unsigned numSpaces = 0; unsigned len = (unsigned)strlen(textString); if (width > len) { numSpaces = width - len; unsigned numLeftSpaces = 0; switch (adj) { case kLeft: numLeftSpaces = 0; break; case kCenter: numLeftSpaces = numSpaces / 2; break; case kRight: numLeftSpaces = numSpaces; break; } PrintSpacesToString(dest, numLeftSpaces); dest += numLeftSpaces; numSpaces -= numLeftSpaces; } memcpy(dest, textString, len); dest += len; PrintSpacesToString(dest, numSpaces); } struct CListUInt64Def { UInt64 Val; bool Def; CListUInt64Def(): Val(0), Def(false) {} void Add(UInt64 v) { Val += v; Def = true; } void Add(const CListUInt64Def &v) { if (v.Def) Add(v.Val); } }; struct CListFileTimeDef { FILETIME Val; bool Def; CListFileTimeDef(): Def(false) { Val.dwLowDateTime = 0; Val.dwHighDateTime = 0; } void Update(const CListFileTimeDef &t) { if (t.Def && (!Def || CompareFileTime(&Val, &t.Val) < 0)) { Val = t.Val; Def = true; } } }; struct CListStat { CListUInt64Def Size; CListUInt64Def PackSize; CListFileTimeDef MTime; UInt64 NumFiles; CListStat(): NumFiles(0) {} void Update(const CListStat &st) { Size.Add(st.Size); PackSize.Add(st.PackSize); MTime.Update(st.MTime); NumFiles += st.NumFiles; } void SetSizeDefIfNoFiles() { if (NumFiles == 0) Size.Def = true; } }; struct CListStat2 { CListStat MainFiles; CListStat AltStreams; UInt64 NumDirs; CListStat2(): NumDirs(0) {} void Update(const CListStat2 &st) { MainFiles.Update(st.MainFiles); AltStreams.Update(st.AltStreams); NumDirs += st.NumDirs; } const UInt64 GetNumStreams() const { return MainFiles.NumFiles + AltStreams.NumFiles; } CListStat &GetStat(bool altStreamsMode) { return altStreamsMode ? AltStreams : MainFiles; } }; class CFieldPrinter { CObjectVector<CFieldInfo> _fields; void AddProp(const wchar_t *name, PROPID propID, bool isRawProp); public: const CArc *Arc; bool TechMode; UString FilePath; AString TempAString; UString TempWString; bool IsDir; AString LinesString; void Clear() { _fields.Clear(); LinesString.Empty(); } void Init(const CFieldInfoInit *standardFieldTable, unsigned numItems); HRESULT AddMainProps(IInArchive *archive); HRESULT AddRawProps(IArchiveGetRawProps *getRawProps); void PrintTitle(); void PrintTitleLines(); HRESULT PrintItemInfo(UInt32 index, const CListStat &st); void PrintSum(const CListStat &st, UInt64 numDirs, const char *str); void PrintSum(const CListStat2 &stat2); }; void CFieldPrinter::Init(const CFieldInfoInit *standardFieldTable, unsigned numItems) { Clear(); for (unsigned i = 0; i < numItems; i++) { CFieldInfo &f = _fields.AddNew(); const CFieldInfoInit &fii = standardFieldTable[i]; f.PropID = fii.PropID; f.IsRawProp = false; f.NameA = fii.Name; f.TitleAdjustment = fii.TitleAdjustment; f.TextAdjustment = fii.TextAdjustment; f.PrefixSpacesWidth = fii.PrefixSpacesWidth; f.Width = fii.Width; unsigned k; for (k = 0; k < fii.PrefixSpacesWidth; k++) LinesString.Add_Space(); for (k = 0; k < fii.Width; k++) LinesString += '-'; } } static void GetPropName(PROPID propID, const wchar_t *name, AString &nameA, UString &nameU) { if (propID < ARRAY_SIZE(kPropIdToName)) { nameA = kPropIdToName[propID]; return; } if (name) nameU = name; else { nameA.Empty(); nameA.Add_UInt32(propID); } } void CFieldPrinter::AddProp(const wchar_t *name, PROPID propID, bool isRawProp) { CFieldInfo f; f.PropID = propID; f.IsRawProp = isRawProp; GetPropName(propID, name, f.NameA, f.NameU); f.NameU += " = "; if (!f.NameA.IsEmpty()) f.NameA += " = "; else { const UString &s = f.NameU; AString sA; unsigned i; for (i = 0; i < s.Len(); i++) { wchar_t c = s[i]; if (c >= 0x80) break; sA += (char)c; } if (i == s.Len()) f.NameA = sA; } _fields.Add(f); } HRESULT CFieldPrinter::AddMainProps(IInArchive *archive) { UInt32 numProps; RINOK(archive-><API key>(&numProps)); for (UInt32 i = 0; i < numProps; i++) { CMyComBSTR name; PROPID propID; VARTYPE vt; RINOK(archive->GetPropertyInfo(i, &name, &propID, &vt)); AddProp(name, propID, false); } return S_OK; } HRESULT CFieldPrinter::AddRawProps(IArchiveGetRawProps *getRawProps) { UInt32 numProps; RINOK(getRawProps->GetNumRawProps(&numProps)); for (UInt32 i = 0; i < numProps; i++) { CMyComBSTR name; PROPID propID; RINOK(getRawProps->GetRawPropInfo(i, &name, &propID)); AddProp(name, propID, true); } return S_OK; } void CFieldPrinter::PrintTitle() { FOR_VECTOR (i, _fields) { const CFieldInfo &f = _fields[i]; PrintSpaces(f.PrefixSpacesWidth); PrintString(f.TitleAdjustment, ((f.PropID == kpidPath) ? 0: f.Width), f.NameA); } } void CFieldPrinter::PrintTitleLines() { g_StdOut << LinesString; } static void PrintTime(char *dest, const FILETIME *ft) { *dest = 0; if (ft->dwLowDateTime == 0 && ft->dwHighDateTime == 0) return; <API key>(*ft, dest, <API key>); } #ifndef _SFX static inline char GetHex(Byte value) { return (char)((value < 10) ? ('0' + value) : ('A' + (value - 10))); } static void HexToString(char *dest, const Byte *data, UInt32 size) { for (UInt32 i = 0; i < size; i++) { Byte b = data[i]; dest[0] = GetHex((Byte)((b >> 4) & 0xF)); dest[1] = GetHex((Byte)(b & 0xF)); dest += 2; } *dest = 0; } #endif #define MY_ENDL endl HRESULT CFieldPrinter::PrintItemInfo(UInt32 index, const CListStat &st) { char temp[128]; size_t tempPos = 0; bool techMode = this->TechMode; /* if (techMode) { g_StdOut << "Index = "; g_StdOut << (UInt64)index; g_StdOut << endl; } */ FOR_VECTOR (i, _fields) { const CFieldInfo &f = _fields[i]; if (!techMode) { PrintSpacesToString(temp + tempPos, f.PrefixSpacesWidth); tempPos += f.PrefixSpacesWidth; } if (techMode) { if (!f.NameA.IsEmpty()) g_StdOut << f.NameA; else g_StdOut << f.NameU; } if (f.PropID == kpidPath) { if (!techMode) g_StdOut << temp; g_StdOut.<API key>(FilePath, TempWString, TempAString); if (techMode) g_StdOut << MY_ENDL; continue; } const unsigned width = f.Width; if (f.IsRawProp) { #ifndef _SFX const void *data; UInt32 dataSize; UInt32 propType; RINOK(Arc->GetRawProps->GetRawProp(index, f.PropID, &data, &dataSize, &propType)); if (dataSize != 0) { bool needPrint = true; if (f.PropID == kpidNtSecure) { if (propType != NPropDataType::kRaw) return E_FAIL; #ifndef _SFX <API key>((const Byte *)data, dataSize, TempAString); g_StdOut << TempAString; needPrint = false; #endif } else if (f.PropID == kpidNtReparse) { UString s; if (<API key>((const Byte *)data, dataSize, s)) { needPrint = false; g_StdOut.PrintUString(s, TempAString); } } if (needPrint) { if (propType != NPropDataType::kRaw) return E_FAIL; const UInt32 kMaxDataSize = 64; if (dataSize > kMaxDataSize) { g_StdOut << "data:"; g_StdOut << dataSize; } else { char hexStr[kMaxDataSize * 2 + 4]; HexToString(hexStr, (const Byte *)data, dataSize); g_StdOut << hexStr; } } } #endif } else { CPropVariant prop; switch (f.PropID) { case kpidSize: if (st.Size.Def) prop = st.Size.Val; break; case kpidPackSize: if (st.PackSize.Def) prop = st.PackSize.Val; break; case kpidMTime: if (st.MTime.Def) prop = st.MTime.Val; break; default: RINOK(Arc->Archive->GetProperty(index, f.PropID, &prop)); } if (f.PropID == kpidAttrib && (prop.vt == VT_EMPTY || prop.vt == VT_UI4)) { GetAttribString((prop.vt == VT_EMPTY) ? 0 : prop.ulVal, IsDir, techMode, temp + tempPos); if (techMode) g_StdOut << temp + tempPos; else tempPos += strlen(temp + tempPos); } else if (prop.vt == VT_EMPTY) { if (!techMode) { PrintSpacesToString(temp + tempPos, width); tempPos += width; } } else if (prop.vt == VT_FILETIME) { PrintTime(temp + tempPos, &prop.filetime); if (techMode) g_StdOut << temp + tempPos; else { size_t len = strlen(temp + tempPos); tempPos += len; if (len < (unsigned)f.Width) { len = f.Width - len; PrintSpacesToString(temp + tempPos, (unsigned)len); tempPos += len; } } } else if (prop.vt == VT_BSTR) { TempWString.SetFromBstr(prop.bstrVal); // do we need multi-line support here ? g_StdOut.Normalize_UString(TempWString); if (techMode) { g_StdOut.PrintUString(TempWString, TempAString); } else PrintUString(f.TextAdjustment, width, TempWString, TempAString); } else { char s[64]; <API key>(s, prop, f.PropID); if (techMode) g_StdOut << s; else { PrintStringToString(temp + tempPos, f.TextAdjustment, width, s); tempPos += strlen(temp + tempPos); } } } if (techMode) g_StdOut << MY_ENDL; } g_StdOut << MY_ENDL; return S_OK; } static void PrintNumber(EAdjustment adj, unsigned width, const CListUInt64Def &value) { char s[32]; s[0] = 0; if (value.Def) <API key>(value.Val, s); PrintString(adj, width, s); } void <API key>(AString &s, UInt64 val, const char *name); void CFieldPrinter::PrintSum(const CListStat &st, UInt64 numDirs, const char *str) { FOR_VECTOR (i, _fields) { const CFieldInfo &f = _fields[i]; PrintSpaces(f.PrefixSpacesWidth); if (f.PropID == kpidSize) PrintNumber(f.TextAdjustment, f.Width, st.Size); else if (f.PropID == kpidPackSize) PrintNumber(f.TextAdjustment, f.Width, st.PackSize); else if (f.PropID == kpidMTime) { char s[64]; s[0] = 0; if (st.MTime.Def) PrintTime(s, &st.MTime.Val); PrintString(f.TextAdjustment, f.Width, s); } else if (f.PropID == kpidPath) { AString s; <API key>(s, st.NumFiles, str); if (numDirs != 0) { s += ", "; <API key>(s, numDirs, kString_Dirs); } PrintString(f.TextAdjustment, 0, s); } else PrintString(f.TextAdjustment, f.Width, ""); } g_StdOut << endl; } void CFieldPrinter::PrintSum(const CListStat2 &stat2) { PrintSum(stat2.MainFiles, stat2.NumDirs, kString_Files); if (stat2.AltStreams.NumFiles != 0) { PrintSum(stat2.AltStreams, 0, kString_AltStreams);; CListStat st = stat2.MainFiles; st.Update(stat2.AltStreams); PrintSum(st, 0, kString_Streams); } } static HRESULT GetUInt64Value(IInArchive *archive, UInt32 index, PROPID propID, CListUInt64Def &value) { value.Val = 0; value.Def = false; CPropVariant prop; RINOK(archive->GetProperty(index, propID, &prop)); value.Def = <API key>(prop, value.Val); return S_OK; } static HRESULT GetItemMTime(IInArchive *archive, UInt32 index, CListFileTimeDef &t) { t.Val.dwLowDateTime = 0; t.Val.dwHighDateTime = 0; t.Def = false; CPropVariant prop; RINOK(archive->GetProperty(index, kpidMTime, &prop)); if (prop.vt == VT_FILETIME) { t.Val = prop.filetime; t.Def = true; } else if (prop.vt != VT_EMPTY) return E_FAIL; return S_OK; } static void <API key>(CStdOutStream &so, const char *name, UInt64 val) { so << name << ": " << val << endl; } static void <API key>(CStdOutStream &so, PROPID propID) { const char *s; char temp[16]; if (propID < ARRAY_SIZE(kPropIdToName)) s = kPropIdToName[propID]; else { <API key>(propID, temp); s = temp; } so << s << " = "; } static void <API key>(CStdOutStream &so, PROPID propID, UInt64 val) { <API key>(so, propID); so << val << endl; } static void <API key>(CStdOutStream &so, PROPID propID, Int64 val) { <API key>(so, propID); so << val << endl; } static void <API key>(UString &s) { // s.Replace(L"\r\n", L"\n"); wchar_t *src = s.GetBuf(); wchar_t *dest = src; for (;;) { wchar_t c = *src++; if (c == 0) break; if (c == '\r' && *src == '\n') { src++; c = '\n'; } *dest++ = c; } s.ReleaseBuf_SetEnd((unsigned)(dest - s.GetBuf())); } static void <API key>(CStdOutStream &so, const wchar_t *val) { UString s = val; if (s.Find(L'\n') >= 0) { so << endl; so << "{"; so << endl; <API key>(s); so.<API key>(s); so << s; so << endl; so << "}"; } else { so.Normalize_UString(s); so << s; } so << endl; } static void PrintPropPair(CStdOutStream &so, const char *name, const wchar_t *val, bool multiLine) { so << name << " = "; if (multiLine) { <API key>(so, val); return; } UString s = val; so.Normalize_UString(s); so << s; so << endl; } static void PrintPropertyPair2(CStdOutStream &so, PROPID propID, const wchar_t *name, const CPropVariant &prop) { UString s; <API key>(s, prop, propID); if (!s.IsEmpty()) { AString nameA; UString nameU; GetPropName(propID, name, nameA, nameU); if (!nameA.IsEmpty()) so << nameA; else so << nameU; so << " = "; <API key>(so, s); } } static HRESULT PrintArcProp(CStdOutStream &so, IInArchive *archive, PROPID propID, const wchar_t *name) { CPropVariant prop; RINOK(archive->GetArchiveProperty(propID, &prop)); PrintPropertyPair2(so, propID, name, prop); return S_OK; } static void PrintArcTypeError(CStdOutStream &so, const UString &type, bool isWarning) { so << "Open " << (isWarning ? "WARNING" : "ERROR") << ": Can not open the file as [" << type << "] archive" << endl; } int <API key>(const UStringVector &fileName, const UString& name); void PrintErrorFlags(CStdOutStream &so, const char *s, UInt32 errorFlags); static void ErrorInfo_Print(CStdOutStream &so, const CArcErrorInfo &er) { PrintErrorFlags(so, "ERRORS:", er.GetErrorFlags()); if (!er.ErrorMessage.IsEmpty()) PrintPropPair(so, "ERROR", er.ErrorMessage, true); PrintErrorFlags(so, "WARNINGS:", er.GetWarningFlags()); if (!er.WarningMessage.IsEmpty()) PrintPropPair(so, "WARNING", er.WarningMessage, true); } HRESULT <API key>(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink) { FOR_VECTOR (r, arcLink.Arcs) { const CArc &arc = arcLink.Arcs[r]; const CArcErrorInfo &er = arc.ErrorInfo; so << " PrintPropPair(so, "Path", arc.Path, false); if (er.ErrorFormatIndex >= 0) { if (er.ErrorFormatIndex == arc.FormatIndex) so << "Warning: The archive is open with offset" << endl; else PrintArcTypeError(so, codecs->GetFormatNamePtr(er.ErrorFormatIndex), true); } PrintPropPair(so, "Type", codecs->GetFormatNamePtr(arc.FormatIndex), false); ErrorInfo_Print(so, er); Int64 offset = arc.GetGlobalOffset(); if (offset != 0) <API key>(so, kpidOffset, offset); IInArchive *archive = arc.Archive; RINOK(PrintArcProp(so, archive, kpidPhySize, NULL)); if (er.TailSize != 0) <API key>(so, kpidTailSize, er.TailSize); { UInt32 numProps; RINOK(archive-><API key>(&numProps)); for (UInt32 j = 0; j < numProps; j++) { CMyComBSTR name; PROPID propID; VARTYPE vt; RINOK(archive-><API key>(j, &name, &propID, &vt)); RINOK(PrintArcProp(so, archive, propID, name)); } } if (r != arcLink.Arcs.Size() - 1) { UInt32 numProps; so << " if (archive-><API key>(&numProps) == S_OK) { UInt32 mainIndex = arcLink.Arcs[r + 1].SubfileIndex; for (UInt32 j = 0; j < numProps; j++) { CMyComBSTR name; PROPID propID; VARTYPE vt; RINOK(archive->GetPropertyInfo(j, &name, &propID, &vt)); CPropVariant prop; RINOK(archive->GetProperty(mainIndex, propID, &prop)); PrintPropertyPair2(so, propID, name, prop); } } } } return S_OK; } HRESULT <API key>(CStdOutStream &so, const CCodecs *codecs, const CArchiveLink &arcLink) { #ifndef _NO_CRYPTO if (arcLink.PasswordWasAsked) so << "Can not open encrypted archive. Wrong password?"; else #endif { if (arcLink.NonOpen_ErrorInfo.ErrorFormatIndex >= 0) { so.<API key>(arcLink.NonOpen_ArcPath); so << endl; PrintArcTypeError(so, codecs->Formats[arcLink.NonOpen_ErrorInfo.ErrorFormatIndex].Name, false); } else so << "Can not open the file as archive"; } so << endl; so << endl; ErrorInfo_Print(so, arcLink.NonOpen_ErrorInfo); return S_OK; } bool <API key>(const NWildcard::CCensorNode &node, const CReadArcItem &item); HRESULT ListArchives(CCodecs *codecs, const CObjectVector<COpenType> &types, const CIntVector &excludedFormats, bool stdInMode, UStringVector &arcPaths, UStringVector &arcPathsFull, bool processAltStreams, bool showAltStreams, const NWildcard::CCensorNode &wildcardCensor, bool enableHeaders, bool techMode, #ifndef _NO_CRYPTO bool &passwordEnabled, UString &password, #endif #ifndef _SFX const CObjectVector<CProperty> *props, #endif UInt64 &numErrors, UInt64 &numWarnings) { bool allFilesAreAllowed = wildcardCensor.AreAllAllowed(); numErrors = 0; numWarnings = 0; CFieldPrinter fp; if (!techMode) fp.Init(kStandardFieldTable, ARRAY_SIZE(kStandardFieldTable)); CListStat2 stat2total; CBoolArr skipArcs(arcPaths.Size()); unsigned arcIndex; for (arcIndex = 0; arcIndex < arcPaths.Size(); arcIndex++) skipArcs[arcIndex] = false; UInt64 numVolumes = 0; UInt64 numArcs = 0; UInt64 totalArcSizes = 0; HRESULT lastError = 0; for (arcIndex = 0; arcIndex < arcPaths.Size(); arcIndex++) { if (skipArcs[arcIndex]) continue; const UString &arcPath = arcPaths[arcIndex]; UInt64 arcPackSize = 0; if (!stdInMode) { NFile::NFind::CFileInfo fi; if (!fi.Find(us2fs(arcPath))) { DWORD errorCode = GetLastError(); if (errorCode == 0) errorCode = <API key>; lastError = HRESULT_FROM_WIN32(lastError);; g_StdOut.Flush(); if (g_ErrStream) { *g_ErrStream << endl << kError << NError::MyFormatMessage(errorCode) << endl; g_ErrStream-><API key>(arcPath); *g_ErrStream << endl << endl; } numErrors++; continue; } if (fi.IsDir()) { g_StdOut.Flush(); if (g_ErrStream) { *g_ErrStream << endl << kError; g_ErrStream-><API key>(arcPath); *g_ErrStream << " is not a file" << endl << endl; } numErrors++; continue; } arcPackSize = fi.Size; totalArcSizes += arcPackSize; } CArchiveLink arcLink; <API key> openCallback; openCallback.Init(&g_StdOut, g_ErrStream, NULL); #ifndef _NO_CRYPTO openCallback.PasswordIsDefined = passwordEnabled; openCallback.Password = password; #endif /* CObjectVector<<API key>> optPropsVector; <API key> &optProps = optPropsVector.AddNew(); optProps.Props = *props; */ COpenOptions options; #ifndef _SFX options.props = props; #endif options.codecs = codecs; options.types = &types; options.excludedFormats = &excludedFormats; options.stdInMode = stdInMode; options.stream = NULL; options.filePath = arcPath; if (enableHeaders) { g_StdOut << endl << kListing; g_StdOut.<API key>(arcPath); g_StdOut << endl << endl; } HRESULT result = arcLink.Open_Strict(options, &openCallback); if (result != S_OK) { if (result == E_ABORT) return result; if (result != S_FALSE) lastError = result; g_StdOut.Flush(); if (g_ErrStream) { *g_ErrStream << endl << kError; g_ErrStream-><API key>(arcPath); *g_ErrStream << " : "; if (result == S_FALSE) { <API key>(*g_ErrStream, codecs, arcLink); } else { *g_ErrStream << "opening : "; if (result == E_OUTOFMEMORY) *g_ErrStream << "Can't allocate required memory"; else *g_ErrStream << NError::MyFormatMessage(result); } *g_ErrStream << endl; } numErrors++; continue; } { FOR_VECTOR (r, arcLink.Arcs) { const CArcErrorInfo &arc = arcLink.Arcs[r].ErrorInfo; if (!arc.WarningMessage.IsEmpty()) numWarnings++; if (arc.AreThereWarnings()) numWarnings++; if (arc.ErrorFormatIndex >= 0) numWarnings++; if (arc.AreThereErrors()) { numErrors++; // break; } if (!arc.ErrorMessage.IsEmpty()) numErrors++; } } numArcs++; numVolumes++; if (!stdInMode) { numVolumes += arcLink.VolumePaths.Size(); totalArcSizes += arcLink.VolumesSize; FOR_VECTOR (v, arcLink.VolumePaths) { int index = <API key>(arcPathsFull, arcLink.VolumePaths[v]); if (index >= 0 && (unsigned)index > arcIndex) skipArcs[(unsigned)index] = true; } } if (enableHeaders) { RINOK(<API key>(g_StdOut, codecs, arcLink)); g_StdOut << endl; if (techMode) g_StdOut << " } if (enableHeaders && !techMode) { fp.PrintTitle(); g_StdOut << endl; fp.PrintTitleLines(); g_StdOut << endl; } const CArc &arc = arcLink.Arcs.Back(); fp.Arc = &arc; fp.TechMode = techMode; IInArchive *archive = arc.Archive; if (techMode) { fp.Clear(); RINOK(fp.AddMainProps(archive)); if (arc.GetRawProps) { RINOK(fp.AddRawProps(arc.GetRawProps)); } } CListStat2 stat2; UInt32 numItems; RINOK(archive->GetNumberOfItems(&numItems)); CReadArcItem item; UStringVector pathParts; for (UInt32 i = 0; i < numItems; i++) { if (NConsoleClose::TestBreakSignal()) return E_ABORT; HRESULT res = arc.GetItemPath2(i, fp.FilePath); if (stdInMode && res == E_INVALIDARG) break; RINOK(res); if (arc.Ask_Aux) { bool isAux; RINOK(Archive_IsItem_Aux(archive, i, isAux)); if (isAux) continue; } bool isAltStream = false; if (arc.Ask_AltStream) { RINOK(<API key>(archive, i, isAltStream)); if (isAltStream && !processAltStreams) continue; } RINOK(Archive_IsItem_Dir(archive, i, fp.IsDir)); if (!allFilesAreAllowed) { if (isAltStream) { RINOK(arc.GetItem(i, item)); if (!<API key>(wildcardCensor, item)) continue; } else { SplitPathToParts(fp.FilePath, pathParts);; bool include; if (!wildcardCensor.CheckPathVect(pathParts, !fp.IsDir, include)) continue; if (!include) continue; } } CListStat st; RINOK(GetUInt64Value(archive, i, kpidSize, st.Size)); RINOK(GetUInt64Value(archive, i, kpidPackSize, st.PackSize)); RINOK(GetItemMTime(archive, i, st.MTime)); if (fp.IsDir) stat2.NumDirs++; else st.NumFiles = 1; stat2.GetStat(isAltStream).Update(st); if (isAltStream && !showAltStreams) continue; RINOK(fp.PrintItemInfo(i, st)); } UInt64 numStreams = stat2.GetNumStreams(); if (!stdInMode && !stat2.MainFiles.PackSize.Def && !stat2.AltStreams.PackSize.Def) { if (arcLink.VolumePaths.Size() != 0) arcPackSize += arcLink.VolumesSize; stat2.MainFiles.PackSize.Add((numStreams == 0) ? 0 : arcPackSize); } stat2.MainFiles.SetSizeDefIfNoFiles(); stat2.AltStreams.SetSizeDefIfNoFiles(); if (enableHeaders && !techMode) { fp.PrintTitleLines(); g_StdOut << endl; fp.PrintSum(stat2); } if (enableHeaders) { if (arcLink.NonOpen_ErrorInfo.ErrorFormatIndex >= 0) { g_StdOut << " PrintPropPair(g_StdOut, "Path", arcLink.NonOpen_ArcPath, false); PrintArcTypeError(g_StdOut, codecs->Formats[arcLink.NonOpen_ErrorInfo.ErrorFormatIndex].Name, false); } } stat2total.Update(stat2); g_StdOut.Flush(); } if (enableHeaders && !techMode && (arcPaths.Size() > 1 || numVolumes > 1)) { g_StdOut << endl; fp.PrintTitleLines(); g_StdOut << endl; fp.PrintSum(stat2total); g_StdOut << endl; <API key>(g_StdOut, "Archives", numArcs); <API key>(g_StdOut, "Volumes", numVolumes); <API key>(g_StdOut, "Total archives size", totalArcSizes); } if (numErrors == 1 && lastError != 0) return lastError; return S_OK; }
#include "GUIMediaWindow.h" #include "Application.h" #include "messaging/<API key>.h" #include "ContextMenuManager.h" #include "<API key>.h" #include "GUIPassword.h" #include "GUIUserMessages.h" #include "PartyModeManager.h" #include "PlayListPlayer.h" #include "URL.h" #include "Util.h" #include "addons/AddonManager.h" #include "addons/<API key>.h" #include "addons/PluginSource.h" #if defined(TARGET_ANDROID) #include "platform/android/activity/XBMCApp.h" #endif #include "dialogs/GUIDialogKaiToast.h" #include "dialogs/<API key>.h" #include "dialogs/<API key>.h" #include "dialogs/GUIDialogOK.h" #include "dialogs/GUIDialogProgress.h" #include "dialogs/<API key>.h" #include "filesystem/FavouritesDirectory.h" #include "filesystem/File.h" #include "filesystem/<API key>.h" #include "filesystem/MultiPathDirectory.h" #include "filesystem/PluginDirectory.h" #include "filesystem/<API key>.h" #include "guilib/GUIEditControl.h" #include "guilib/GUIKeyboardFactory.h" #include "guilib/GUIWindowManager.h" #include "guilib/LocalizeStrings.h" #include "interfaces/builtins/Builtins.h" #include "interfaces/generic/<API key>.h" #include "input/Key.h" #include "network/Network.h" #include "playlists/PlayList.h" #include "profiles/ProfilesManager.h" #include "settings/AdvancedSettings.h" #include "settings/Settings.h" #include "storage/MediaManager.h" #include "threads/SystemClock.h" #include "utils/FileUtils.h" #include "utils/LabelFormatter.h" #include "utils/log.h" #include "utils/SortUtils.h" #include "utils/StringUtils.h" #include "utils/URIUtils.h" #include "utils/Variant.h" #include "video/VideoLibraryQueue.h" #include "view/GUIViewState.h" #define <API key> 2 #define CONTROL_BTNSORTBY 3 #define CONTROL_BTNSORTASC 4 #define CONTROL_BTN_FILTER 19 #define CONTROL_LABELFILES 12 #define CONTROL_VIEW_START 50 #define CONTROL_VIEW_END 59 #define PROPERTY_PATH_DB "path.db" #define PROPERTY_SORT_ORDER "sort.order" #define <API key> "sort.ascending" #define <API key> 200 using namespace ADDON; using namespace KODI::MESSAGING; CGUIMediaWindow::CGUIMediaWindow(int id, const char *xmlFile) : CGUIWindow(id, xmlFile) { m_loadType = KEEP_IN_MEMORY; m_vecItems = new CFileItemList; m_unfilteredItems = new CFileItemList; m_vecItems->SetPath("?"); m_iLastControl = -1; m_canFilterAdvanced = false; m_guiState.reset(CGUIViewState::GetViewState(GetID(), *m_vecItems)); } CGUIMediaWindow::~CGUIMediaWindow() { delete m_vecItems; delete m_unfilteredItems; } void CGUIMediaWindow::LoadAdditionalTags(TiXmlElement *root) { CGUIWindow::LoadAdditionalTags(root); // configure our view control m_viewControl.Reset(); m_viewControl.SetParentWindow(GetID()); TiXmlElement *element = root->FirstChildElement("views"); if (element && element->FirstChild()) { // format is <views>50,29,51,95</views> const std::string &allViews = element->FirstChild()->ValueStr(); std::vector<std::string> views = StringUtils::Split(allViews, ","); for (std::vector<std::string>::const_iterator i = views.begin(); i != views.end(); ++i) { int controlID = atol(i->c_str()); CGUIControl *control = GetControl(controlID); if (control && control->IsContainer()) m_viewControl.AddView(control); } } else { // backward compatibility std::vector<CGUIControl *> controls; GetContainers(controls); for (ciControls it = controls.begin(); it != controls.end(); it++) { CGUIControl *control = *it; if (control->GetID() >= CONTROL_VIEW_START && control->GetID() <= CONTROL_VIEW_END) m_viewControl.AddView(control); } } m_viewControl.SetViewControlID(<API key>); } void CGUIMediaWindow::OnWindowLoaded() { SendMessage(GUI_MSG_SET_TYPE, CONTROL_BTN_FILTER, CGUIEditControl::INPUT_TYPE_FILTER); CGUIWindow::OnWindowLoaded(); SetupShares(); } void CGUIMediaWindow::OnWindowUnload() { CGUIWindow::OnWindowUnload(); m_viewControl.Reset(); } CFileItemPtr CGUIMediaWindow::GetCurrentListItem(int offset) { int item = m_viewControl.GetSelectedItem(); if (!m_vecItems->Size() || item < 0) return CFileItemPtr(); item = (item + offset) % m_vecItems->Size(); if (item < 0) item += m_vecItems->Size(); return m_vecItems->Get(item); } bool CGUIMediaWindow::OnAction(const CAction &action) { if (action.GetID() == ACTION_PARENT_DIR) { GoParentFolder(); return true; } // the non-contextual menu can be called at any time if (action.GetID() == ACTION_CONTEXT_MENU && !m_viewControl.HasControl(GetFocusedControlID())) { OnPopupMenu(-1); return true; } if (CGUIWindow::OnAction(action)) return true; if (action.GetID() == ACTION_FILTER) return Filter(); // live filtering if (action.GetID() == ACTION_FILTER_CLEAR) { CGUIMessage message(GUI_MSG_NOTIFY_ALL, GetID(), 0, <API key>); message.SetStringParam(""); OnMessage(message); return true; } if (action.GetID() == ACTION_BACKSPACE) { CGUIMessage message(GUI_MSG_NOTIFY_ALL, GetID(), 0, <API key>, 2); // 2 for delete OnMessage(message); return true; } if (action.GetID() >= ACTION_FILTER_SMS2 && action.GetID() <= ACTION_FILTER_SMS9) { std::string filter = StringUtils::Format("%i", (int)(action.GetID() - ACTION_FILTER_SMS2 + 2)); CGUIMessage message(GUI_MSG_NOTIFY_ALL, GetID(), 0, <API key>, 1); // 1 for append message.SetStringParam(filter); OnMessage(message); return true; } return false; } bool CGUIMediaWindow::OnBack(int actionID) { CURL filterUrl(m_strFilterPath); if (actionID == ACTION_NAV_BACK && !m_vecItems-><API key>() && !URIUtils::PathEquals(m_vecItems->GetPath(), GetRootPath(), true) && (!URIUtils::PathEquals(m_vecItems->GetPath(), m_startDirectory, true) || (m_canFilterAdvanced && filterUrl.HasOption("filter")))) { if (GoParentFolder()) return true; } return CGUIWindow::OnBack(actionID); } bool CGUIMediaWindow::OnMessage(CGUIMessage& message) { switch ( message.GetMessage() ) { case <API key>: { m_iLastControl = GetFocusedControlID(); CGUIWindow::OnMessage(message); // get rid of any active filtering if (m_canFilterAdvanced) { m_canFilterAdvanced = false; m_filter.Reset(); } m_strFilterPath.clear(); // Call ClearFileItems() after our window has finished doing any WindowClose // animations ClearFileItems(); return true; } break; case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); if (iControl == <API key>) { // view as control could be a select button int viewMode = 0; const CGUIControl *control = GetControl(<API key>); if (control && control->GetControlType() != CGUIControl::GUICONTROL_BUTTON) { CGUIMessage msg(<API key>, GetID(), <API key>); OnMessage(msg); viewMode = m_viewControl.GetViewModeNumber(msg.GetParam1()); } else viewMode = m_viewControl.GetNextViewMode(); if (m_guiState.get()) m_guiState->SaveViewAsControl(viewMode); UpdateButtons(); return true; } else if (iControl == CONTROL_BTNSORTASC) // sort asc { if (m_guiState.get()) m_guiState->SetNextSortOrder(); UpdateFileList(); return true; } else if (iControl == CONTROL_BTNSORTBY) // sort by { if (m_guiState.get() && m_guiState->ChooseSortMethod()) UpdateFileList(); return true; } else if (iControl == CONTROL_BTN_FILTER) return Filter(false); else if (m_viewControl.HasControl(iControl)) // list/thumb control { int iItem = m_viewControl.GetSelectedItem(); int iAction = message.GetParam1(); if (iItem < 0) break; if (iAction == ACTION_SELECT_ITEM || iAction == <API key>) { OnSelect(iItem); } else if (iAction == ACTION_CONTEXT_MENU || iAction == <API key>) { OnPopupMenu(iItem); return true; } } } break; case GUI_MSG_SETFOCUS: { if (m_viewControl.HasControl(message.GetControlId()) && m_viewControl.GetCurrentControl() != message.GetControlId()) { m_viewControl.SetFocused(); return true; } } break; case GUI_MSG_NOTIFY_ALL: { // Message is received even if this window is inactive if (message.GetParam1() == <API key>) { m_vecItems->SetPath("?"); return true; } else if ( message.GetParam1() == <API key> ) { for (int i = 0; i < m_vecItems->Size(); i++) m_vecItems->Get(i)->FreeMemory(true); break; // the window will take care of any info images } else if (message.GetParam1() == <API key>) { if ((m_vecItems-><API key>() || m_vecItems->IsSourcesPath()) && IsActive()) { int iItem = m_viewControl.GetSelectedItem(); Refresh(); m_viewControl.SetSelectedItem(iItem); } else if (m_vecItems->IsRemovable()) { // check that we have this removable share still if (!m_rootDir.IsInSource(m_vecItems->GetPath())) { // don't have this share any more if (IsActive()) Update(""); else { m_history.ClearPathHistory(); m_vecItems->SetPath(""); } } } return true; } else if (message.GetParam1()==<API key>) { // State of the sources changed, so update our view if ((m_vecItems-><API key>() || m_vecItems->IsSourcesPath()) && IsActive()) { int iItem = m_viewControl.GetSelectedItem(); Refresh(true); m_viewControl.SetSelectedItem(iItem); } return true; } else if (message.GetParam1()==GUI_MSG_UPDATE && IsActive()) { if (message.GetNumStringParams()) { if (message.GetParam2()) // param2 is used for resetting the history SetHistoryForPath(message.GetStringParam()); CFileItemList list(message.GetStringParam()); list.RemoveDiscCache(GetID()); Update(message.GetStringParam()); } else Refresh(true); // refresh the listing } else if (message.GetParam1()==GUI_MSG_UPDATE_ITEM && message.GetItem()) { CFileItemPtr newItem = std::static_pointer_cast<CFileItem>(message.GetItem()); if (IsActive()) { if (m_vecItems->UpdateItem(newItem.get()) && message.GetParam2() == 1) { // need the list updated as well UpdateFileList(); } } else if (newItem) { // need to remove the disc cache CFileItemList items; items.SetPath(URIUtils::GetDirectory(newItem->GetPath())); items.RemoveDiscCache(GetID()); } } else if (message.GetParam1()==GUI_MSG_UPDATE_PATH) { if (IsActive()) { if((message.GetStringParam() == m_vecItems->GetPath()) || (m_vecItems->IsMultiPath() && XFILE::CMultiPathDirectory::HasPath(m_vecItems->GetPath(), message.GetStringParam()))) Refresh(); } } else if (message.GetParam1() == <API key> && IsActive()) { std::string filter = GetProperty("filter").asString(); // check if this is meant for advanced filtering if (message.GetParam2() != 10) { if (message.GetParam2() == 1) // append filter += message.GetStringParam(); else if (message.GetParam2() == 2) { // delete if (filter.size()) filter.erase(filter.size() - 1); } else filter = message.GetStringParam(); } OnFilterItems(filter); UpdateButtons(); return true; } else return CGUIWindow::OnMessage(message); return true; } break; case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: case <API key>: { // send a notify all to all controls on this window CGUIMessage msg(GUI_MSG_NOTIFY_ALL, GetID(), 0, <API key>); OnMessage(msg); break; } case <API key>: { int viewMode = 0; if (message.GetParam1()) // we have an id viewMode = m_viewControl.GetViewModeByID(message.GetParam1()); else if (message.GetParam2()) viewMode = m_viewControl.GetNextViewMode((int)message.GetParam2()); if (m_guiState.get()) m_guiState->SaveViewAsControl(viewMode); UpdateButtons(); return true; } break; case <API key>: { if (m_guiState.get()) { if (message.GetParam1()) m_guiState-><API key>((int)message.GetParam1()); else if (message.GetParam2()) m_guiState->SetNextSortMethod((int)message.GetParam2()); } UpdateFileList(); return true; } break; case <API key>: { if (m_guiState.get()) m_guiState->SetNextSortOrder(); UpdateFileList(); return true; } break; case GUI_MSG_WINDOW_INIT: { if (m_vecItems->GetPath() == "?") m_vecItems->SetPath(""); std::string dir = message.GetStringParam(0); const std::string &ret = message.GetStringParam(1); bool returning = StringUtils::EqualsNoCase(ret, "return"); if (!dir.empty()) { // ensure our directory is valid dir = GetStartFolder(dir); bool resetHistory = false; if (!returning || !m_history.IsInHistory(dir)) { // we're not returning to the same path, so set our directory to the requested path m_vecItems->SetPath(dir); resetHistory = true; } // check for network up if (URIUtils::IsRemote(m_vecItems->GetPath()) && !WaitForNetwork()) { m_vecItems->SetPath(""); resetHistory = true; } if (resetHistory) SetHistoryForPath(m_vecItems->GetPath()); } if (message.GetParam1() != WINDOW_INVALID) { // first time to this window - make sure we set the root path m_startDirectory = returning ? dir : GetRootPath(); } if (message.GetParam2() == <API key>) { Refresh(); <API key>(); <API key>(); <API key>(); return true; } } break; } return CGUIWindow::OnMessage(message); } // \brief Updates the states (enable, disable, visible...) // of the controls defined by this window // Override this function in a derived class to add new controls void CGUIMediaWindow::UpdateButtons() { if (m_guiState.get()) { // Update sorting controls if (m_guiState->GetSortOrder() == SortOrderNone) { CONTROL_DISABLE(CONTROL_BTNSORTASC); } else { CONTROL_ENABLE(CONTROL_BTNSORTASC); <API key>(GetID(), CONTROL_BTNSORTASC, m_guiState->GetSortOrder() != SortOrderAscending); } // Update list/thumb control m_viewControl.SetCurrentView(m_guiState->GetViewAsControl()); // Update sort by button if (!m_guiState-><API key>()) CONTROL_DISABLE(CONTROL_BTNSORTBY); else CONTROL_ENABLE(CONTROL_BTNSORTBY); std::string sortLabel = StringUtils::Format(g_localizeStrings.Get(550).c_str(), g_localizeStrings.Get(m_guiState->GetSortMethodLabel()).c_str()); SET_CONTROL_LABEL(CONTROL_BTNSORTBY, sortLabel); } std::string items = StringUtils::Format("%i %s", m_vecItems->GetObjectCount(), g_localizeStrings.Get(127).c_str()); SET_CONTROL_LABEL(CONTROL_LABELFILES, items); SET_CONTROL_LABEL2(CONTROL_BTN_FILTER, GetProperty("filter").asString()); } void CGUIMediaWindow::ClearFileItems() { m_viewControl.Clear(); m_vecItems->Clear(); m_unfilteredItems->Clear(); } // \brief Sorts Fileitems based on the sort method and sort oder provided by guiViewState void CGUIMediaWindow::SortItems(CFileItemList &items) { std::unique_ptr<CGUIViewState> guiState(CGUIViewState::GetViewState(GetID(), items)); if (guiState.get()) { SortDescription sorting = guiState->GetSortMethod(); sorting.sortOrder = guiState->GetSortOrder(); // If the sort method is "sort by playlist" and we have a specific // sort order available we can use the specified sort order to do the sorting // We do this as the new SortBy methods are a superset of the SORT_METHOD methods, thus // not all are available. This may be removed once SORT_METHOD_* have been replaced by // SortBy. if ((sorting.sortBy == SortByPlaylistOrder) && items.HasProperty(PROPERTY_SORT_ORDER)) { SortBy sortBy = (SortBy)items.GetProperty(PROPERTY_SORT_ORDER).asInteger(); if (sortBy != SortByNone && sortBy != SortByPlaylistOrder && sortBy != SortByProgramCount) { sorting.sortBy = sortBy; sorting.sortOrder = items.GetProperty(<API key>).asBoolean() ? SortOrderAscending : SortOrderDescending; sorting.sortAttributes = CSettings::GetInstance().GetBool(CSettings::<API key>) ? <API key> : SortAttributeNone; // if the sort order is descending, we need to switch the original sort order, as we assume // in CGUIViewState::AddPlaylistOrder that SortByPlaylistOrder is ascending. if (guiState->GetSortOrder() == SortOrderDescending) sorting.sortOrder = sorting.sortOrder == SortOrderDescending ? SortOrderAscending : SortOrderDescending; } } items.Sort(sorting); } } // \brief Formats item labels based on the formatting provided by guiViewState void CGUIMediaWindow::FormatItemLabels(CFileItemList &items, const LABEL_MASKS &labelMasks) { CLabelFormatter fileFormatter(labelMasks.m_strLabelFile, labelMasks.m_strLabel2File); CLabelFormatter folderFormatter(labelMasks.m_strLabelFolder, labelMasks.m_strLabel2Folder); for (int i=0; i<items.Size(); ++i) { CFileItemPtr pItem=items[i]; if (pItem->IsLabelPreformated()) continue; if (pItem->m_bIsFolder) folderFormatter.FormatLabels(pItem.get()); else fileFormatter.FormatLabels(pItem.get()); } if (items.GetSortMethod() == SortByLabel) items.ClearSortState(); } // \brief Prepares and adds the fileitems list/thumb panel void CGUIMediaWindow::FormatAndSort(CFileItemList &items) { std::unique_ptr<CGUIViewState> viewState(CGUIViewState::GetViewState(GetID(), items)); if (viewState.get()) { LABEL_MASKS labelMasks; viewState-><API key>(labelMasks); FormatItemLabels(items, labelMasks); items.Sort(viewState->GetSortMethod().sortBy, viewState->GetSortOrder(), viewState->GetSortMethod().sortAttributes); } } /*! \brief Overwrite to fill fileitems from a source \param strDirectory Path to read \param items Fill with items specified in \e strDirectory */ bool CGUIMediaWindow::GetDirectory(const std::string &strDirectory, CFileItemList &items) { const CURL pathToUrl(strDirectory); std::string strParentPath = m_history.GetParentPath(); CLog::Log(LOGDEBUG,"CGUIMediaWindow::GetDirectory (%s)", CURL::GetRedacted(strDirectory).c_str()); CLog::Log(LOGDEBUG," ParentPath = [%s]", CURL::GetRedacted(strParentPath).c_str()); if (pathToUrl.IsProtocol("plugin")) CAddonMgr::GetInstance().UpdateLastUsed(pathToUrl.GetHostName()); // see if we can load a previously cached folder CFileItemList cachedItems(strDirectory); if (!strDirectory.empty() && cachedItems.Load(GetID())) { items.Assign(cachedItems); } else { unsigned int time = XbmcThreads::SystemClockMillis(); if (strDirectory.empty()) SetupShares(); CFileItemList dirItems; if (!m_rootDir.GetDirectory(pathToUrl, dirItems, UseFileDirectories())) return false; // assign fetched directory items items.Assign(dirItems); // took over a second, and not normally cached, so cache it if ((XbmcThreads::SystemClockMillis() - time) > 1000 && items.CacheToDiscIfSlow()) items.Save(GetID()); // if these items should replace the current listing, then pop it off the top if (items.GetReplaceListing()) m_history.RemoveParentPath(); } // update the view state's reference to the current items m_guiState.reset(CGUIViewState::GetViewState(GetID(), items)); bool bHideParent = false; if (m_guiState && m_guiState->HideParentDirItems()) bHideParent = true; if (items.GetPath() == GetRootPath()) bHideParent = true; if (!bHideParent) { CFileItemPtr pItem(new CFileItem("..")); pItem->SetPath(strParentPath); pItem->m_bIsFolder = true; pItem->m_bIsShareOrDrive = false; items.AddFront(pItem, 0); } int iWindow = GetID(); std::vector<std::string> regexps; //! @todo Do we want to limit the directories we apply the video ones to? if (iWindow == WINDOW_VIDEO_NAV) regexps = g_advancedSettings.<API key>; if (iWindow == WINDOW_MUSIC_NAV) regexps = g_advancedSettings.<API key>; if (iWindow == WINDOW_PICTURES) regexps = g_advancedSettings.<API key>; if (regexps.size()) { for (int i=0; i < items.Size();) { if (CUtil::ExcludeFileOrFolder(items[i]->GetPath(), regexps)) items.Remove(i); else i++; } } // clear the filter SetProperty("filter", ""); m_canFilterAdvanced = false; m_filter.Reset(); return true; } bool CGUIMediaWindow::Update(const std::string &strDirectory, bool updateFilterPath /* = true */) { //! @todo OnInitWindow calls Update() before window path has been set properly. if (strDirectory == "?") return false; // The path to load. Empty string is used in various places to denote root, so translate to the // real root path first const std::string path = strDirectory.empty() ? GetRootPath() : strDirectory; // stores the selected item in history <API key>(); const std::string previousPath = m_vecItems->GetPath(); // check if the path contains a filter and temporarily remove it // so that the retrieved list of items is unfiltered std::string pathNoFilter = path; if (CanContainFilter(pathNoFilter) && CURL(pathNoFilter).HasOption("filter")) pathNoFilter = <API key>(pathNoFilter, "filter"); if (!GetDirectory(pathNoFilter, *m_vecItems)) { CLog::Log(LOGERROR,"CGUIMediaWindow::GetDirectory(%s) failed", CURL(path).GetRedacted().c_str()); if (URIUtils::PathEquals(path, GetRootPath())) return false; // Nothing to fallback to // Try to return to the previous directory, if not the same // else fallback to root if (URIUtils::PathEquals(path, previousPath) || !Update(m_history.RemoveParentPath())) Update(""); // Fallback to root // Return false to be able to eg. show // an error message. return false; } if (m_vecItems->GetLabel().empty()) m_vecItems->SetLabel(CUtil::GetTitleFromPath(m_vecItems->GetPath(), true)); // check the given path for filter data UpdateFilterPath(path, *m_vecItems, updateFilterPath); // if we're getting the root source listing // make sure the path history is clean if (URIUtils::PathEquals(path, GetRootPath())) m_history.ClearPathHistory(); int iWindow = GetID(); int showLabel = 0; if (URIUtils::PathEquals(path, GetRootPath())) { if (iWindow == WINDOW_PICTURES) showLabel = 997; else if (iWindow == WINDOW_FILES) showLabel = 1026; } if (m_vecItems->IsPath("sources://video/")) showLabel = 999; else if (m_vecItems->IsPath("sources://music/")) showLabel = 998; else if (m_vecItems->IsPath("sources://pictures/")) showLabel = 997; else if (m_vecItems->IsPath("sources://files/")) showLabel = 1026; if (showLabel && (m_vecItems->Size() == 0 || !m_guiState-><API key>())) // add 'add source button' { std::string strLabel = g_localizeStrings.Get(showLabel); CFileItemPtr pItem(new CFileItem(strLabel)); pItem->SetPath("add"); pItem->SetIconImage("DefaultAddSource.png"); pItem->SetLabel(strLabel); pItem->SetLabelPreformated(true); pItem->m_bIsFolder = true; pItem->SetSpecialSort(SortSpecialOnBottom); m_vecItems->Add(pItem); } m_iLastControl = GetFocusedControlID(); // Check whether to enabled advanced filtering based on the content type m_canFilterAdvanced = CheckFilterAdvanced(*m_vecItems); if (m_canFilterAdvanced) m_filter.SetType(m_vecItems->GetContent()); // Ask the derived class if it wants to load additional info // for the fileitems like media info or additional // filtering on the items, setting thumbs. OnPrepareFileItems(*m_vecItems); m_vecItems->FillInDefaultIcons(); // remember the original (untouched) list of items (for filtering etc) m_unfilteredItems->Assign(*m_vecItems); // Cache the list of items if possible OnCacheFileItems(*m_vecItems); // Filter and group the items if necessary OnFilterItems(GetProperty("filter").asString()); UpdateButtons(); // Restore selected item from history <API key>(); m_history.AddPath(m_vecItems->GetPath(), m_strFilterPath); //m_history.DumpPathHistory(); return true; } bool CGUIMediaWindow::Refresh(bool clearCache /* = false */) { std::string strCurrentDirectory = m_vecItems->GetPath(); if (strCurrentDirectory == "?") return false; if (clearCache) m_vecItems->RemoveDiscCache(GetID()); // get the original number of items if (!Update(strCurrentDirectory, false)) return false; return true; } // \brief This function will be called by Update() before the // labels of the fileitems are formatted. Override this function // to set custom thumbs or load additional media info. // It's used to load tag info for music. void CGUIMediaWindow::OnPrepareFileItems(CFileItemList &items) { <API key>::GetInstance().Modify(items); } // \brief This function will be called by Update() before // any additional formatting, filtering or sorting is applied. // Override this function to define a custom caching behaviour. void CGUIMediaWindow::OnCacheFileItems(CFileItemList &items) { // Should these items be saved to the hdd if (items.CacheToDiscAlways() && !IsFiltered()) items.Save(GetID()); } // \brief With this function you can react on a users click in the list/thumb panel. // It returns true, if the click is handled. // This function calls OnPlayMedia() bool CGUIMediaWindow::OnClick(int iItem, const std::string &player) { if ( iItem < 0 || iItem >= (int)m_vecItems->Size() ) return true; CFileItemPtr pItem = m_vecItems->Get(iItem); if (pItem->IsParentFolder()) { GoParentFolder(); return true; } if (pItem->GetPath() == "add" || pItem->GetPath() == "sources://add/") // 'add source button' in empty root { if (CProfilesManager::GetInstance().IsMasterProfile()) { if (!g_passwordManager.<API key>(true)) return false; } else if (!CProfilesManager::GetInstance().GetCurrentProfile().canWriteSources() && !g_passwordManager.<API key>()) return false; if (OnAddMediaSource()) Refresh(true); return true; } if (!pItem->m_bIsFolder && pItem->IsFileFolder(<API key>)) { XFILE::IFileDirectory *pFileDirectory = NULL; pFileDirectory = XFILE::<API key>::Create(pItem->GetURL(), pItem.get(), ""); if(pFileDirectory) pItem->m_bIsFolder = true; else if(pItem->m_bIsFolder) pItem->m_bIsFolder = false; delete pFileDirectory; } if (pItem->IsScript()) { // execute the script CURL url(pItem->GetPath()); AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(url.GetHostName(), addon, ADDON_SCRIPT)) { if (!<API key>::GetInstance().Stop(addon->LibPath())) { CAddonMgr::GetInstance().UpdateLastUsed(addon->ID()); <API key>::GetInstance().ExecuteAsync(addon->LibPath(), addon); } return true; } } if (pItem->m_bIsFolder) { if ( pItem->m_bIsShareOrDrive ) { const std::string& strLockType=m_guiState->GetLockType(); if (CProfilesManager::GetInstance().GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE) if (!strLockType.empty() && !g_passwordManager.IsItemUnlocked(pItem.get(), strLockType)) return true; if (!<API key>(pItem->GetPath(), pItem->m_iDriveType)) return true; } // check for the partymode playlist items - they may not exist yet if ((pItem->GetPath() == CProfilesManager::GetInstance().GetUserDataItem("PartyMode.xsp")) || (pItem->GetPath() == CProfilesManager::GetInstance().GetUserDataItem("PartyMode-Video.xsp"))) { // party mode playlist item - if it doesn't exist, prompt for user to define it if (!XFILE::CFile::Exists(pItem->GetPath())) { m_vecItems->RemoveDiscCache(GetID()); if (<API key>::EditPlaylist(pItem->GetPath())) Refresh(); return true; } } // remove the directory cache if the folder is not normally cached CFileItemList items(pItem->GetPath()); if (!items.AlwaysCache()) items.RemoveDiscCache(GetID()); // if we have a filtered list, we need to add the filtered // path to be able to come back to the filtered view std::string strCurrentDirectory = m_vecItems->GetPath(); if (m_canFilterAdvanced && !m_filter.IsEmpty() && !URIUtils::PathEquals(m_strFilterPath, strCurrentDirectory)) { m_history.RemoveParentPath(); m_history.AddPath(strCurrentDirectory, m_strFilterPath); } CFileItem directory(*pItem); if (!Update(directory.GetPath())) <API key>(&directory); return true; } else if (pItem->IsPlugin() && !pItem->GetProperty("isplayable").asBoolean()) { return XFILE::CPluginDirectory::RunScriptWithParams(pItem->GetPath()); } #if defined(TARGET_ANDROID) else if (pItem->IsAndroidApp()) { std::string appName = URIUtils::GetFileName(pItem->GetPath()); CLog::Log(LOGDEBUG, "CGUIMediaWindow::OnClick Trying to run: %s",appName.c_str()); return CXBMCApp::StartActivity(appName); } #endif else { <API key>(); if (pItem->GetPath() == "newplaylist: { m_vecItems->RemoveDiscCache(GetID()); g_windowManager.ActivateWindow(<API key>,"newplaylist: return true; } else if (StringUtils::StartsWithNoCase(pItem->GetPath(), "newsmartplaylist: { m_vecItems->RemoveDiscCache(GetID()); if (<API key>::NewPlaylist(pItem->GetPath().substr(19))) Refresh(); return true; } bool autoplay = m_guiState.get() && m_guiState->AutoPlayNextItem(); if (m_vecItems->IsPlugin()) { CURL url(m_vecItems->GetPath()); AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(url.GetHostName(),addon)) { PluginPtr plugin = std::<API key><CPluginSource>(addon); if (plugin && plugin->Provides(CPluginSource::AUDIO)) { CFileItemList items; std::unique_ptr<CGUIViewState> state(CGUIViewState::GetViewState(GetID(), items)); autoplay = state.get() && state->AutoPlayNextItem(); } } } if (autoplay && !g_partyModeManager.IsEnabled() && !pItem->IsPlayList()) { return OnPlayAndQueueMedia(pItem, player); } else { return OnPlayMedia(iItem, player); } } return false; } bool CGUIMediaWindow::OnSelect(int item) { return OnClick(item); } // \brief Checks if there is a disc in the dvd drive and whether the // network is connected or not. bool CGUIMediaWindow::<API key>(const std::string& strPath, int iDriveType) { if (iDriveType==CMediaSource::SOURCE_TYPE_DVD) { if (!g_mediaManager.IsDiscInDrive(strPath)) { CGUIDialogOK::ShowAndGetInput(CVariant{218}, CVariant{219}); return false; } } else if (iDriveType==CMediaSource::SOURCE_TYPE_REMOTE) { //! @todo Handle not connected to a remote share if ( !g_application.getNetwork().IsConnected() ) { CGUIDialogOK::ShowAndGetInput(CVariant{220}, CVariant{221}); return false; } } return true; } // \brief Shows a standard errormessage for a given pItem. void CGUIMediaWindow::<API key>(CFileItem* pItem) { if (!pItem->m_bIsShareOrDrive) return; int idMessageText = 0; CURL url(pItem->GetPath()); if (url.IsProtocol("smb") && url.GetHostName().empty()) // smb workgroup idMessageText = 15303; // Workgroup not found else if (pItem->m_iDriveType == CMediaSource::SOURCE_TYPE_REMOTE || URIUtils::IsRemote(pItem->GetPath())) idMessageText = 15301; // Could not connect to network server else idMessageText = 15300; // Path not found or invalid CGUIDialogOK::ShowAndGetInput(CVariant{220}, CVariant{idMessageText}); } // \brief The functon goes up one level in the directory tree bool CGUIMediaWindow::GoParentFolder() { if (m_vecItems-><API key>()) return false; if (URIUtils::PathEquals(m_vecItems->GetPath(), GetRootPath())) return false; //m_history.DumpPathHistory(); const std::string currentPath = m_vecItems->GetPath(); std::string parentPath = m_history.GetParentPath(); // in case the path history is messed up and the current folder is on // the stack more than once, keep going until there's nothing left or they // dont match anymore. while (!parentPath.empty() && URIUtils::PathEquals(parentPath, currentPath, true)) { m_history.RemoveParentPath(); parentPath = m_history.GetParentPath(); } // remove the current filter but only if the parent // item doesn't have a filter as well CURL filterUrl(m_strFilterPath); if (filterUrl.HasOption("filter")) { CURL parentUrl(m_history.GetParentPath(true)); if (!parentUrl.HasOption("filter")) { // we need to overwrite m_strFilterPath because // Refresh() will set updateFilterPath to false m_strFilterPath.clear(); Refresh(); return true; } } // pop directory path from the stack m_strFilterPath = m_history.GetParentPath(true); m_history.RemoveParentPath(); if (!Update(parentPath, false)) return false; // No items to show so go another level up if (!m_vecItems->GetPath().empty() && (m_filter.IsEmpty() ? m_vecItems->Size() : m_unfilteredItems->Size()) <= 0) { CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Info, g_localizeStrings.Get(2080), g_localizeStrings.Get(2081)); return GoParentFolder(); } return true; } void CGUIMediaWindow::<API key>() { int iItem = m_viewControl.GetSelectedItem(); std::string strSelectedItem; if (iItem >= 0 && iItem < m_vecItems->Size()) { CFileItemPtr pItem = m_vecItems->Get(iItem); if (!pItem->IsParentFolder()) <API key>(pItem.get(), strSelectedItem); } m_history.SetSelectedItem(strSelectedItem, m_vecItems->GetPath()); } void CGUIMediaWindow::<API key>() { std::string strSelectedItem = m_history.GetSelectedItem(m_vecItems->GetPath()); if (!strSelectedItem.empty()) { for (int i = 0; i < m_vecItems->Size(); ++i) { CFileItemPtr pItem = m_vecItems->Get(i); std::string strHistory; <API key>(pItem.get(), strHistory); // set selected item if equals with history if (strHistory == strSelectedItem) { m_viewControl.SetSelectedItem(i); return; } } } // if we haven't found the selected item, select the first item m_viewControl.SetSelectedItem(0); } // \brief Override the function to change the default behavior on how // a selected item history should look like void CGUIMediaWindow::<API key>(const CFileItem* pItem, std::string& strHistoryString) { if (pItem->m_bIsShareOrDrive) { // We are in the virual directory // History string of the DVD drive // must be handel separately if (pItem->m_iDriveType == CMediaSource::SOURCE_TYPE_DVD) { // Remove disc label from item label // and use as history string, m_strPath // can change for new discs std::string strLabel = pItem->GetLabel(); size_t nPosOpen = strLabel.find('('); size_t nPosClose = strLabel.rfind(')'); if (nPosOpen != std::string::npos && nPosClose != std::string::npos && nPosClose > nPosOpen) { strLabel.erase(nPosOpen + 1, (nPosClose) - (nPosOpen + 1)); strHistoryString = strLabel; } else strHistoryString = strLabel; } else { // Other items in virual directory std::string strPath = pItem->GetPath(); URIUtils::RemoveSlashAtEnd(strPath); strHistoryString = pItem->GetLabel() + strPath; } } else if (pItem->m_lEndOffset>pItem->m_lStartOffset && pItem->m_lStartOffset != -1) { // Could be a cue item, all items of a cue share the same filename // so add the offsets to build the history string strHistoryString = StringUtils::Format("%i%i", pItem->m_lStartOffset, pItem->m_lEndOffset); strHistoryString += pItem->GetPath(); } else { // Normal directory items strHistoryString = pItem->GetPath(); } // remove any filter if (CanContainFilter(strHistoryString)) strHistoryString = <API key>(strHistoryString, "filter"); URIUtils::RemoveSlashAtEnd(strHistoryString); StringUtils::ToLower(strHistoryString); } // \brief Call this function to create a directory history for the // path given by strDirectory. void CGUIMediaWindow::SetHistoryForPath(const std::string& strDirectory) { // Make sure our shares are configured SetupShares(); if (!strDirectory.empty()) { // Build the directory history for default path std::string strPath, strParentPath; strPath = strDirectory; URIUtils::RemoveSlashAtEnd(strPath); CFileItemList items; m_rootDir.GetDirectory(CURL(), items, UseFileDirectories()); m_history.ClearPathHistory(); bool originalPath = true; while (URIUtils::GetParentPath(strPath, strParentPath)) { for (int i = 0; i < (int)items.Size(); ++i) { CFileItemPtr pItem = items[i]; std::string path(pItem->GetPath()); URIUtils::RemoveSlashAtEnd(path); if (URIUtils::PathEquals(path, strPath)) { std::string strHistory; <API key>(pItem.get(), strHistory); m_history.SetSelectedItem(strHistory, ""); URIUtils::AddSlashAtEnd(strPath); m_history.AddPathFront(strPath); m_history.AddPathFront(""); //m_history.DumpPathHistory(); return ; } } if (URIUtils::IsVideoDb(strPath)) { CURL url(strParentPath); url.SetOptions(""); // clear any URL options from recreated parent path strParentPath = url.Get(); } // set the original path exactly as it was passed in if (URIUtils::PathEquals(strPath, strDirectory, true)) strPath = strDirectory; else URIUtils::AddSlashAtEnd(strPath); m_history.AddPathFront(strPath, originalPath ? m_strFilterPath : ""); m_history.SetSelectedItem(strPath, strParentPath); originalPath = false; strPath = strParentPath; URIUtils::RemoveSlashAtEnd(strPath); } } else m_history.ClearPathHistory(); //m_history.DumpPathHistory(); } // \brief Override if you want to change the default behavior, what is done // when the user clicks on a file. // This function is called by OnClick() bool CGUIMediaWindow::OnPlayMedia(int iItem, const std::string &player) { // Reset Playlistplayer, playback started now does // not use the playlistplayer. g_playlistPlayer.Reset(); g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_NONE); CFileItemPtr pItem=m_vecItems->Get(iItem); CLog::Log(LOGDEBUG, "%s %s", __FUNCTION__, CURL::GetRedacted(pItem->GetPath()).c_str()); bool bResult = false; if (pItem->IsInternetStream() || pItem->IsPlayList()) bResult = g_application.PlayMedia(*pItem, player, m_guiState->GetPlaylist()); else bResult = g_application.PlayFile(*pItem, player) == PLAYBACK_OK; if (pItem->m_lStartOffset == STARTOFFSET_RESUME) pItem->m_lStartOffset = 0; return bResult; } // \brief Override if you want to change the default behavior of what is done // when the user clicks on a file in a "folder" with similar files. // This function is called by OnClick() bool CGUIMediaWindow::OnPlayAndQueueMedia(const CFileItemPtr &item, std::string player) { //play and add current directory to temporary playlist int iPlaylist = m_guiState->GetPlaylist(); if (iPlaylist != PLAYLIST_NONE) { g_playlistPlayer.ClearPlaylist(iPlaylist); g_playlistPlayer.Reset(); int mediaToPlay = 0; // first try to find mainDVD file (VIDEO_TS.IFO). // If we find this we should not allow to queue VOB files std::string mainDVD; for (int i = 0; i < m_vecItems->Size(); i++) { std::string path = URIUtils::GetFileName(m_vecItems->Get(i)->GetPath()); if (StringUtils::EqualsNoCase(path, "VIDEO_TS.IFO")) { mainDVD = path; break; } } // now queue... for ( int i = 0; i < m_vecItems->Size(); i++ ) { CFileItemPtr nItem = m_vecItems->Get(i); if (nItem->m_bIsFolder) continue; if (!nItem->IsPlayList() && !nItem->IsZIP() && !nItem->IsRAR() && (!nItem->IsDVDFile() || (URIUtils::GetFileName(nItem->GetPath()) == mainDVD))) g_playlistPlayer.Add(iPlaylist, nItem); if (item->IsSamePath(nItem.get())) { // item that was clicked mediaToPlay = g_playlistPlayer.GetPlaylist(iPlaylist).size() - 1; } } // Save current window and directory to know where the selected item was if (m_guiState.get()) m_guiState-><API key>(m_vecItems->GetPath()); // figure out where we start playback if (g_playlistPlayer.IsShuffled(iPlaylist)) { int iIndex = g_playlistPlayer.GetPlaylist(iPlaylist).FindOrder(mediaToPlay); g_playlistPlayer.GetPlaylist(iPlaylist).Swap(0, iIndex); mediaToPlay = 0; } // play g_playlistPlayer.SetCurrentPlaylist(iPlaylist); g_playlistPlayer.Play(mediaToPlay, player); } return true; } // \brief Synchonize the fileitems with the playlistplayer // It recreated the playlist of the playlistplayer based // on the fileitems of the window void CGUIMediaWindow::UpdateFileList() { int nItem = m_viewControl.GetSelectedItem(); std::string strSelected; if (nItem >= 0) strSelected = m_vecItems->Get(nItem)->GetPath(); FormatAndSort(*m_vecItems); UpdateButtons(); m_viewControl.SetItems(*m_vecItems); m_viewControl.SetSelectedItem(strSelected); // set the currently playing item as selected, if its in this directory if (m_guiState.get() && m_guiState-><API key>(m_vecItems->GetPath())) { int iPlaylist=m_guiState->GetPlaylist(); int nSong = g_playlistPlayer.GetCurrentSong(); CFileItem playlistItem; if (nSong > -1 && iPlaylist > -1) playlistItem=*g_playlistPlayer.GetPlaylist(iPlaylist)[nSong]; g_playlistPlayer.ClearPlaylist(iPlaylist); g_playlistPlayer.Reset(); for (int i = 0; i < m_vecItems->Size(); i++) { CFileItemPtr pItem = m_vecItems->Get(i); if (pItem->m_bIsFolder) continue; if (!pItem->IsPlayList() && !pItem->IsZIP() && !pItem->IsRAR()) g_playlistPlayer.Add(iPlaylist, pItem); if (pItem->GetPath() == playlistItem.GetPath() && pItem->m_lStartOffset == playlistItem.m_lStartOffset) g_playlistPlayer.SetCurrentSong(g_playlistPlayer.GetPlaylist(iPlaylist).size() - 1); } } } void CGUIMediaWindow::OnDeleteItem(int iItem) { if ( iItem < 0 || iItem >= m_vecItems->Size()) return; CFileItemPtr item = m_vecItems->Get(iItem); if (item->IsPlayList()) item->m_bIsFolder = false; if (CProfilesManager::GetInstance().GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE && CProfilesManager::GetInstance().GetCurrentProfile().filesLocked()) if (!g_passwordManager.<API key>(true)) return; if (!CFileUtils::DeleteItem(item)) return; Refresh(true); m_viewControl.SetSelectedItem(iItem); } void CGUIMediaWindow::OnRenameItem(int iItem) { if ( iItem < 0 || iItem >= m_vecItems->Size()) return; if (CProfilesManager::GetInstance().GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE && CProfilesManager::GetInstance().GetCurrentProfile().filesLocked()) if (!g_passwordManager.<API key>(true)) return; if (!CFileUtils::RenameFile(m_vecItems->Get(iItem)->GetPath())) return; Refresh(true); m_viewControl.SetSelectedItem(iItem); } void CGUIMediaWindow::OnInitWindow() { // initial fetch is done unthreaded to ensure the items are setup prior to skin animations kicking off m_rootDir.SetAllowThreads(false); // the start directory may change during Refresh bool <API key> = URIUtils::PathEquals(m_vecItems->GetPath(), m_startDirectory, true); // we have python scripts hooked in everywhere :( // those scripts may open windows and we can't open a window // while opening this one. // for plugin sources delay call to Refresh if (!URIUtils::IsPlugin(m_vecItems->GetPath())) { Refresh(); } else { CGUIMessage msg(GUI_MSG_WINDOW_INIT, 0, 0, 0, <API key>); g_windowManager.SendThreadMessage(msg, m_controlID); } if (<API key>) { // reset the start directory to the path of the items m_startDirectory = m_vecItems->GetPath(); // reset the history based on the path of the items SetHistoryForPath(m_startDirectory); } m_rootDir.SetAllowThreads(true); CGUIWindow::OnInitWindow(); } void CGUIMediaWindow::SaveControlStates() { CGUIWindow::SaveControlStates(); <API key>(); } void CGUIMediaWindow::<API key>() { CGUIWindow::<API key>(); <API key>(); } CGUIControl *CGUIMediaWindow::<API key>(int id) { if (m_viewControl.HasControl(id)) id = m_viewControl.GetCurrentControl(); return CGUIWindow::<API key>(id); } void CGUIMediaWindow::SetupShares() { // Setup shares and filemasks for this window CFileItemList items; CGUIViewState* viewState=CGUIViewState::GetViewState(GetID(), items); if (viewState) { m_rootDir.SetMask(viewState->GetExtensions()); m_rootDir.SetSources(viewState->GetSources()); delete viewState; } } bool CGUIMediaWindow::OnPopupMenu(int itemIdx) { auto InRange = [](int i, std::pair<int, int> range){ return i >= range.first && i < range.second; }; if (itemIdx < 0 || itemIdx >= m_vecItems->Size()) return false; auto item = m_vecItems->Get(itemIdx); if (!item) return false; CContextButtons buttons; //Add items from plugin { int i = 0; while (item->HasProperty(StringUtils::Format("contextmenulabel(%i)", i))) { buttons.emplace_back(-buttons.size(), item->GetProperty(StringUtils::Format("contextmenulabel(%i)", i)).asString()); ++i; } } auto pluginMenuRange = std::make_pair(0, buttons.size()); //Add the global menu auto globalMenu = CContextMenuManager::GetInstance().GetItems(*item, CContextMenuManager::MAIN); auto globalMenuRange = std::make_pair(buttons.size(), buttons.size() + globalMenu.size()); for (const auto& menu : globalMenu) buttons.emplace_back(-buttons.size(), menu->GetLabel(*item)); //Add legacy items from windows auto windowMenuRange = std::make_pair(buttons.size(), -1); GetContextButtons(itemIdx, buttons); windowMenuRange.second = buttons.size(); //Add addon menus auto addonMenu = CContextMenuManager::GetInstance().GetAddonItems(*item, CContextMenuManager::MAIN); auto addonMenuRange = std::make_pair(buttons.size(), buttons.size() + addonMenu.size()); for (const auto& menu : addonMenu) buttons.emplace_back(-buttons.size(), menu->GetLabel(*item)); if (buttons.empty()) return true; int idx = <API key>::Show(buttons); if (idx < 0 || idx >= static_cast<int>(buttons.size())) return false; if (InRange(idx, pluginMenuRange)) { <API key>::GetInstance().SendMsg(<API key>, -1, -1, nullptr, item->GetProperty(StringUtils::Format("contextmenuaction(%i)", idx - pluginMenuRange.first)).asString()); return true; } if (InRange(idx, windowMenuRange)) return OnContextButton(itemIdx, static_cast<CONTEXT_BUTTON>(buttons[idx].first)); if (InRange(idx, globalMenuRange)) return CONTEXTMENU::LoopFrom(*globalMenu[idx - globalMenuRange.first], item); return CONTEXTMENU::LoopFrom(*addonMenu[idx - addonMenuRange.first], item); } void CGUIMediaWindow::GetContextButtons(int itemNumber, CContextButtons &buttons) { CFileItemPtr item = (itemNumber >= 0 && itemNumber < m_vecItems->Size()) ? m_vecItems->Get(itemNumber) : CFileItemPtr(); if (!item || item->IsParentFolder()) return; //! @todo FAVOURITES Conditions on masterlock and localisation if (!item->IsParentFolder() && !item->IsPath("add") && !item->IsPath("newplaylist: !URIUtils::IsProtocol(item->GetPath(), "newsmartplaylist") && !URIUtils::IsProtocol(item->GetPath(), "newtag") && !URIUtils::IsProtocol(item->GetPath(), "musicsearch") && !StringUtils::StartsWith(item->GetPath(), "pvr://guide/") && !StringUtils::StartsWith(item->GetPath(), "pvr://timers/")) { if (XFILE::<API key>::IsFavourite(item.get(), GetID())) buttons.Add(<API key>, 14077); // Remove Favourite else buttons.Add(<API key>, 14076); // Add To Favourites; } if (item->IsFileFolder(<API key>)) buttons.Add(<API key>, 37015); } bool CGUIMediaWindow::OnContextButton(int itemNumber, CONTEXT_BUTTON button) { switch (button) { case <API key>: { CFileItemPtr item = m_vecItems->Get(itemNumber); XFILE::<API key>::AddOrRemove(item.get(), GetID()); return true; } case <API key>: { CFileItemPtr item = m_vecItems->Get(itemNumber); Update(item->GetPath()); return true; } default: break; } return false; } const CGUIViewState *CGUIMediaWindow::GetViewState() const { return m_guiState.get(); } const CFileItemList& CGUIMediaWindow::CurrentDirectory() const { return *m_vecItems; } bool CGUIMediaWindow::WaitForNetwork() const { if (g_application.getNetwork().IsAvailable()) return true; CGUIDialogProgress *progress = (CGUIDialogProgress *)g_windowManager.GetWindow(<API key>); if (!progress) return true; CURL url(m_vecItems->GetPath()); progress->SetHeading(CVariant{1040}); // Loading Directory progress->SetLine(1, CVariant{url.<API key>()}); progress->ShowProgressBar(false); progress->Open(); while (!g_application.getNetwork().IsAvailable()) { progress->Progress(); if (progress->IsCanceled()) { progress->Close(); return false; } } progress->Close(); return true; } void CGUIMediaWindow::UpdateFilterPath(const std::string &strDirectory, const CFileItemList &items, bool updateFilterPath) { bool canfilter = CanContainFilter(strDirectory); std::string filter; CURL url(strDirectory); if (canfilter && url.HasOption("filter")) filter = url.GetOption("filter"); // only set the filter path if it hasn't been marked // as preset or if it's empty if (updateFilterPath || m_strFilterPath.empty()) { if (items.HasProperty(PROPERTY_PATH_DB)) m_strFilterPath = items.GetProperty(PROPERTY_PATH_DB).asString(); else m_strFilterPath = items.GetPath(); } // maybe the filter path can contain a filter if (!canfilter && CanContainFilter(m_strFilterPath)) canfilter = true; // check if the filter path contains a filter CURL filterPathUrl(m_strFilterPath); if (canfilter && filter.empty()) { if (filterPathUrl.HasOption("filter")) filter = filterPathUrl.GetOption("filter"); } // check if there is a filter and re-apply it if (canfilter && !filter.empty()) { if (!m_filter.LoadFromJson(filter)) { CLog::Log(LOGWARNING, "CGUIMediaWindow::UpdateFilterPath(): unable to load existing filter (%s)", filter.c_str()); m_filter.Reset(); m_strFilterPath = m_vecItems->GetPath(); } else { // add the filter to the filter path filterPathUrl.SetOption("filter", filter); m_strFilterPath = filterPathUrl.Get(); } } } void CGUIMediaWindow::OnFilterItems(const std::string &filter) { CFileItemPtr currentItem; std::string currentItemPath; int item = m_viewControl.GetSelectedItem(); if (item >= 0 && item < m_vecItems->Size()) { currentItem = m_vecItems->Get(item); currentItemPath = currentItem->GetPath(); } m_viewControl.Clear(); CFileItemList items; items.Copy(*m_vecItems, false); // use the original path - it'll likely be relied on for other things later. items.Append(*m_unfilteredItems); bool filtered = GetFilteredItems(filter, items); m_vecItems->ClearItems(); // we need to clear the sort state and re-sort the items m_vecItems->ClearSortState(); m_vecItems->Append(items); // if the filter has changed, get the new filter path if (filtered && m_canFilterAdvanced) { if (items.HasProperty(PROPERTY_PATH_DB)) m_strFilterPath = items.GetProperty(PROPERTY_PATH_DB).asString(); // only set m_strFilterPath if it hasn't been set before // otherwise we might overwrite it with a non-filter path // in case GetFilteredItems() returns true even though no // db-based filter (e.g. watched filter) has been applied else if (m_strFilterPath.empty()) m_strFilterPath = items.GetPath(); } GetGroupedItems(*m_vecItems); FormatAndSort(*m_vecItems); // get the "filter" option std::string filterOption; CURL filterUrl(m_strFilterPath); if (filterUrl.HasOption("filter")) filterOption = filterUrl.GetOption("filter"); // apply the "filter" option to any folder item so that // the filter can be passed down to the sub-directory for (int index = 0; index < m_vecItems->Size(); index++) { CFileItemPtr pItem = m_vecItems->Get(index); // if the item is a folder we need to copy the path of // the filtered item to be able to keep the applied filters if (pItem->m_bIsFolder) { CURL itemUrl(pItem->GetPath()); if (!filterOption.empty()) itemUrl.SetOption("filter", filterOption); else itemUrl.RemoveOption("filter"); pItem->SetPath(itemUrl.Get()); } } SetProperty("filter", filter); if (filtered && m_canFilterAdvanced) { // to be able to select the same item as before we need to adjust // the path of the item i.e. add or remove the "filter=" URL option // but that's only necessary for folder items if (currentItem.get() != NULL && currentItem->m_bIsFolder) { CURL curUrl(currentItemPath), newUrl(m_strFilterPath); if (newUrl.HasOption("filter")) curUrl.SetOption("filter", newUrl.GetOption("filter")); else if (curUrl.HasOption("filter")) curUrl.RemoveOption("filter"); currentItemPath = curUrl.Get(); } } // The idea here is to ensure we have something to focus if our file list // is empty. As such, this check MUST be last and ignore the hide parent // fileitems settings. if (m_vecItems->IsEmpty()) { CFileItemPtr pItem(new CFileItem("..")); pItem->SetPath(m_history.GetParentPath()); pItem->m_bIsFolder = true; pItem->m_bIsShareOrDrive = false; m_vecItems->AddFront(pItem, 0); } // and update our view control + buttons m_viewControl.SetItems(*m_vecItems); m_viewControl.SetSelectedItem(currentItemPath); } bool CGUIMediaWindow::GetFilteredItems(const std::string &filter, CFileItemList &items) { bool result = false; if (m_canFilterAdvanced) result = <API key>(items); std::string trimmedFilter(filter); StringUtils::TrimLeft(trimmedFilter); StringUtils::ToLower(trimmedFilter); if (trimmedFilter.empty()) return result; CFileItemList filteredItems(items.GetPath()); // use the original path - it'll likely be relied on for other things later. bool numericMatch = StringUtils::IsNaturalNumber(trimmedFilter); for (int i = 0; i < items.Size(); i++) { CFileItemPtr item = items.Get(i); if (item->IsParentFolder()) { filteredItems.Add(item); continue; } //! @todo Need to update this to get all labels, ideally out of the displayed info (ie from m_layout and m_focusedLayout) //! though that isn't practical. Perhaps a better idea would be to just grab the info that we should filter on based on //! where we are in the library tree. //! Another idea is tying the filter string to the current level of the tree, so that going deeper disables the filter, //! but it's re-enabled on the way back out. std::string match; /* if (item->GetFocusedLayout()) match = item->GetFocusedLayout()->GetAllText(); else if (item->GetLayout()) match = item->GetLayout()->GetAllText(); else*/ match = item->GetLabel(); // Filter label only for now if (numericMatch) StringUtils::WordToDigits(match); size_t pos = StringUtils::FindWords(match.c_str(), trimmedFilter.c_str()); if (pos != std::string::npos) filteredItems.Add(item); } items.ClearItems(); items.Append(filteredItems); return items.GetObjectCount() > 0; } bool CGUIMediaWindow::<API key>(CFileItemList &items) { // don't run the advanced filter if the filter is empty // and there hasn't been a filter applied before which // would have to be removed CURL url(m_strFilterPath); if (m_filter.IsEmpty() && !url.HasOption("filter")) return false; CFileItemList resultItems; XFILE::<API key>::GetDirectory(m_filter, resultItems, m_strFilterPath, true); // put together a lookup map for faster path comparison std::map<std::string, CFileItemPtr> lookup; for (int j = 0; j < resultItems.Size(); j++) { std::string itemPath = CURL(resultItems[j]->GetPath()).GetWithoutOptions(); StringUtils::ToLower(itemPath); lookup[itemPath] = resultItems[j]; } // loop through all the original items and find // those which are still part of the filter CFileItemList filteredItems; for (int i = 0; i < items.Size(); i++) { CFileItemPtr item = items.Get(i); if (item->IsParentFolder()) { filteredItems.Add(item); continue; } // check if the item is part of the resultItems list // by comparing their paths (but ignoring any special // options because they differ from filter to filter) std::string path = CURL(item->GetPath()).GetWithoutOptions(); StringUtils::ToLower(path); std::map<std::string, CFileItemPtr>::iterator itItem = lookup.find(path); if (itItem != lookup.end()) { // add the item to the list of filtered items filteredItems.Add(item); // remove the item from the lists resultItems.Remove(itItem->second.get()); lookup.erase(itItem); } } if (resultItems.Size() > 0) CLog::Log(LOGWARNING, "CGUIMediaWindow::<API key>(): %d unknown items", resultItems.Size()); items.ClearItems(); items.Append(filteredItems); items.SetPath(resultItems.GetPath()); if (resultItems.HasProperty(PROPERTY_PATH_DB)) items.SetProperty(PROPERTY_PATH_DB, resultItems.GetProperty(PROPERTY_PATH_DB)); return true; } bool CGUIMediaWindow::IsFiltered() { return (!m_canFilterAdvanced && !GetProperty("filter").empty()) || (m_canFilterAdvanced && !m_filter.IsEmpty()); } bool CGUIMediaWindow::IsSameStartFolder(const std::string &dir) { const std::string startFolder = GetStartFolder(dir); return URIUtils::PathHasParent(m_vecItems->GetPath(), startFolder); } bool CGUIMediaWindow::Filter(bool advanced /* = true */) { // basic filtering if (!m_canFilterAdvanced || !advanced) { const CGUIControl *btnFilter = GetControl(CONTROL_BTN_FILTER); if (btnFilter != NULL && btnFilter->GetControlType() == CGUIControl::GUICONTROL_EDIT) { // filter updated CGUIMessage selected(<API key>, GetID(), CONTROL_BTN_FILTER); OnMessage(selected); OnFilterItems(selected.GetLabel()); UpdateButtons(); return true; } if (GetProperty("filter").empty()) { std::string filter = GetProperty("filter").asString(); CGUIKeyboardFactory::ShowAndGetFilter(filter, false); SetProperty("filter", filter); } else { OnFilterItems(""); UpdateButtons(); } } // advanced filtering else <API key>::<API key>(m_strFilterPath, m_filter); return true; } std::string CGUIMediaWindow::GetStartFolder(const std::string &dir) { if (StringUtils::EqualsNoCase(dir, "$root") || StringUtils::EqualsNoCase(dir, "root")) return ""; return dir; } std::string CGUIMediaWindow::<API key>(const std::string &strDirectory, const std::string &strParameter) { CURL url(strDirectory); if (url.HasOption(strParameter)) { url.RemoveOption(strParameter); return url.Get(); } return strDirectory; } void CGUIMediaWindow::ProcessRenderLoop(bool renderOnly) { g_windowManager.ProcessRenderLoop(renderOnly); }
#include <errno.h> #include "alloc-util.h" #include "bus-error.h" #include "bus-util.h" #include "dbus-timer.h" #include "fs-util.h" #include "parse-util.h" #include "random-util.h" #include "special.h" #include "string-table.h" #include "string-util.h" #include "timer.h" #include "unit-name.h" #include "unit.h" #include "user-util.h" #include "virt.h" static const UnitActiveState <API key>[_TIMER_STATE_MAX] = { [TIMER_DEAD] = UNIT_INACTIVE, [TIMER_WAITING] = UNIT_ACTIVE, [TIMER_RUNNING] = UNIT_ACTIVE, [TIMER_ELAPSED] = UNIT_ACTIVE, [TIMER_FAILED] = UNIT_FAILED }; static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata); static void timer_init(Unit *u) { Timer *t = TIMER(u); assert(u); assert(u->load_state == UNIT_STUB); t-><API key> = USEC_INFINITY; t-><API key> = USEC_INFINITY; t->accuracy_usec = u->manager-><API key>; t->remain_after_elapse = true; } void timer_free_values(Timer *t) { TimerValue *v; assert(t); while ((v = t->values)) { LIST_REMOVE(value, t->values, v); calendar_spec_free(v->calendar_spec); free(v); } } static void timer_done(Unit *u) { Timer *t = TIMER(u); assert(t); timer_free_values(t); t-><API key> = <API key>(t-><API key>); t-><API key> = <API key>(t-><API key>); free(t->stamp_path); } static int timer_verify(Timer *t) { assert(t); if (UNIT(t)->load_state != UNIT_LOADED) return 0; if (!t->values) { log_unit_error(UNIT(t), "Timer unit lacks value setting. Refusing."); return -EINVAL; } return 0; } static int <API key>(Timer *t) { int r; TimerValue *v; assert(t); if (!UNIT(t)-><API key>) return 0; r = <API key>(UNIT(t), UNIT_BEFORE, <API key>, NULL, true); if (r < 0) return r; if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) { r = <API key>(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, <API key>, NULL, true); if (r < 0) return r; LIST_FOREACH(value, v, t->values) { if (v->base == TIMER_CALENDAR) { r = <API key>(UNIT(t), UNIT_AFTER, <API key>, NULL, true); if (r < 0) return r; break; } } } return <API key>(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, <API key>, NULL, true); } static int <API key>(Timer *t) { int r; assert(t); if (!t->persistent) return 0; if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) { r = <API key>(UNIT(t), "/var/lib/systemd/timers"); if (r < 0) return r; t->stamp_path = strappend("/var/lib/systemd/timers/stamp-", UNIT(t)->id); } else { const char *e; e = getenv("XDG_DATA_HOME"); if (e) t->stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id); else { _cleanup_free_ char *h = NULL; r = get_home_dir(&h); if (r < 0) return <API key>(UNIT(t), r, "Failed to determine home directory: %m"); t->stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id); } } if (!t->stamp_path) return log_oom(); return 0; } static int timer_load(Unit *u) { Timer *t = TIMER(u); int r; assert(u); assert(u->load_state == UNIT_STUB); r = <API key>(u); if (r < 0) return r; if (u->load_state == UNIT_LOADED) { if (set_isempty(u->dependencies[UNIT_TRIGGERS])) { Unit *x; r = <API key>(u, ".service", &x); if (r < 0) return r; r = <API key>(u, UNIT_BEFORE, UNIT_TRIGGERS, x, true); if (r < 0) return r; } r = <API key>(t); if (r < 0) return r; r = <API key>(t); if (r < 0) return r; } return timer_verify(t); } static void timer_dump(Unit *u, FILE *f, const char *prefix) { char buf[FORMAT_TIMESPAN_MAX]; Timer *t = TIMER(u); Unit *trigger; TimerValue *v; trigger = UNIT_TRIGGER(u); fprintf(f, "%sTimer State: %s\n" "%sResult: %s\n" "%sUnit: %s\n" "%sPersistent: %s\n" "%sWakeSystem: %s\n" "%sAccuracy: %s\n" "%sRemainAfterElapse: %s\n", prefix, <API key>(t->state), prefix, <API key>(t->result), prefix, trigger ? trigger->id : "n/a", prefix, yes_no(t->persistent), prefix, yes_no(t->wake_system), prefix, format_timespan(buf, sizeof(buf), t->accuracy_usec, 1), prefix, yes_no(t->remain_after_elapse)); LIST_FOREACH(value, v, t->values) { if (v->base == TIMER_CALENDAR) { _cleanup_free_ char *p = NULL; <API key>(v->calendar_spec, &p); fprintf(f, "%s%s: %s\n", prefix, <API key>(v->base), strna(p)); } else { char timespan1[FORMAT_TIMESPAN_MAX]; fprintf(f, "%s%s: %s\n", prefix, <API key>(v->base), format_timespan(timespan1, sizeof(timespan1), v->value, 0)); } } } static void timer_set_state(Timer *t, TimerState state) { TimerState old_state; assert(t); old_state = t->state; t->state = state; if (state != TIMER_WAITING) { t-><API key> = <API key>(t-><API key>); t-><API key> = <API key>(t-><API key>); t-><API key> = USEC_INFINITY; t-><API key> = USEC_INFINITY; } if (state != old_state) log_unit_debug(UNIT(t), "Changed %s -> %s", <API key>(old_state), <API key>(state)); unit_notify(UNIT(t), <API key>[old_state], <API key>[state], true); } static void timer_enter_waiting(Timer *t, bool initial); static int timer_coldplug(Unit *u) { Timer *t = TIMER(u); assert(t); assert(t->state == TIMER_DEAD); if (t->deserialized_state == t->state) return 0; if (t->deserialized_state == TIMER_WAITING) timer_enter_waiting(t, false); else timer_set_state(t, t->deserialized_state); return 0; } static void timer_enter_dead(Timer *t, TimerResult f) { assert(t); if (t->result == TIMER_SUCCESS) t->result = f; timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD); } static void timer_enter_elapsed(Timer *t, bool leave_around) { assert(t); /* If a unit is marked with RemainAfterElapse=yes we leave it * around even after it elapsed once, so that starting it * later again does not necessarily mean immediate * retriggering. We unconditionally leave units with * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around, * since they might be restarted automatically at any time * later on. */ if (t->remain_after_elapse || leave_around) timer_set_state(t, TIMER_ELAPSED); else timer_enter_dead(t, TIMER_SUCCESS); } static usec_t <API key>(usec_t t) { usec_t a, b; if (t <= 0) return 0; a = now(<API key>()); b = now(CLOCK_MONOTONIC); if (t + a > b) return t + a - b; else return 0; } static void add_random(Timer *t, usec_t *v) { char s[FORMAT_TIMESPAN_MAX]; usec_t add; assert(t); assert(v); if (t->random_usec == 0) return; if (*v == USEC_INFINITY) return; add = random_u64() % t->random_usec; if (*v + add < *v) /* overflow */ *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */ else *v += add; log_unit_info(UNIT(t), "Adding %s random time.", format_timespan(s, sizeof(s), add, 0)); } static void timer_enter_waiting(Timer *t, bool initial) { bool found_monotonic = false, found_realtime = false; usec_t ts_realtime, ts_monotonic; usec_t base = 0; bool leave_around = false; TimerValue *v; Unit *trigger; int r; assert(t); trigger = UNIT_TRIGGER(UNIT(t)); if (!trigger) { log_unit_error(UNIT(t), "Unit to trigger vanished."); timer_enter_dead(t, <API key>); return; } /* If we shall wake the system we use the boottime clock * rather than the monotonic clock. */ ts_realtime = now(CLOCK_REALTIME); ts_monotonic = now(t->wake_system ? <API key>() : CLOCK_MONOTONIC); t-><API key> = t-><API key> = 0; LIST_FOREACH(value, v, t->values) { if (v->disabled) continue; if (v->base == TIMER_CALENDAR) { usec_t b; /* If we know the last time this was * triggered, schedule the job based relative * to that. If we don't just start from * now. */ b = t->last_trigger.realtime > 0 ? t->last_trigger.realtime : ts_realtime; r = <API key>(v->calendar_spec, b, &v->next_elapse); if (r < 0) continue; if (!found_realtime) t-><API key> = v->next_elapse; else t-><API key> = MIN(t-><API key>, v->next_elapse); found_realtime = true; } else { switch (v->base) { case TIMER_ACTIVE: if (<API key>[t->state] == UNIT_ACTIVE) base = UNIT(t)-><API key>.monotonic; else base = ts_monotonic; break; case TIMER_BOOT: if (detect_container() <= 0) { /* CLOCK_MONOTONIC equals the uptime on Linux */ base = 0; break; } /* In a container we don't want to include the time the host * was already up when the container started, so count from * our own startup. Fall through. */ case TIMER_STARTUP: base = UNIT(t)->manager->userspace_timestamp.monotonic; break; case TIMER_UNIT_ACTIVE: leave_around = true; base = trigger-><API key>.monotonic; if (base <= 0) base = t->last_trigger.monotonic; if (base <= 0) continue; break; case TIMER_UNIT_INACTIVE: leave_around = true; base = trigger-><API key>.monotonic; if (base <= 0) base = t->last_trigger.monotonic; if (base <= 0) continue; break; default: assert_not_reached("Unknown timer base"); } if (t->wake_system) base = <API key>(base); v->next_elapse = base + v->value; if (!initial && v->next_elapse < ts_monotonic && IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) { /* This is a one time trigger, disable it now */ v->disabled = true; continue; } if (!found_monotonic) t-><API key> = v->next_elapse; else t-><API key> = MIN(t-><API key>, v->next_elapse); found_monotonic = true; } } if (!found_monotonic && !found_realtime) { log_unit_debug(UNIT(t), "Timer is elapsed."); timer_enter_elapsed(t, leave_around); return; } if (found_monotonic) { char buf[FORMAT_TIMESPAN_MAX]; usec_t left; add_random(t, &t-><API key>); left = t-><API key> > ts_monotonic ? t-><API key> - ts_monotonic : 0; log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", format_timespan(buf, sizeof(buf), left, 0)); if (t-><API key>) { r = <API key>(t-><API key>, t-><API key>); if (r < 0) goto fail; r = <API key>(t-><API key>, SD_EVENT_ONESHOT); if (r < 0) goto fail; } else { r = sd_event_add_time( UNIT(t)->manager->event, &t-><API key>, t->wake_system ? <API key> : CLOCK_MONOTONIC, t-><API key>, t->accuracy_usec, timer_dispatch, t); if (r < 0) goto fail; (void) <API key>(t-><API key>, "timer-monotonic"); } } else if (t-><API key>) { r = <API key>(t-><API key>, SD_EVENT_OFF); if (r < 0) goto fail; } if (found_realtime) { char buf[<API key>]; add_random(t, &t-><API key>); log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", format_timestamp(buf, sizeof(buf), t-><API key>)); if (t-><API key>) { r = <API key>(t-><API key>, t-><API key>); if (r < 0) goto fail; r = <API key>(t-><API key>, SD_EVENT_ONESHOT); if (r < 0) goto fail; } else { r = sd_event_add_time( UNIT(t)->manager->event, &t-><API key>, t->wake_system ? <API key> : CLOCK_REALTIME, t-><API key>, t->accuracy_usec, timer_dispatch, t); if (r < 0) goto fail; (void) <API key>(t-><API key>, "timer-realtime"); } } else if (t-><API key>) { r = <API key>(t-><API key>, SD_EVENT_OFF); if (r < 0) goto fail; } timer_set_state(t, TIMER_WAITING); return; fail: <API key>(UNIT(t), r, "Failed to enter waiting state: %m"); timer_enter_dead(t, <API key>); } static void timer_enter_running(Timer *t) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; Unit *trigger; int r; assert(t); /* Don't start job if we are supposed to go down */ if (unit_stop_pending(UNIT(t))) return; trigger = UNIT_TRIGGER(UNIT(t)); if (!trigger) { log_unit_error(UNIT(t), "Unit to trigger vanished."); timer_enter_dead(t, <API key>); return; } r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, &error, NULL); if (r < 0) goto fail; dual_timestamp_get(&t->last_trigger); if (t->stamp_path) touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID); timer_set_state(t, TIMER_RUNNING); return; fail: log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r)); timer_enter_dead(t, <API key>); } static int timer_start(Unit *u) { Timer *t = TIMER(u); TimerValue *v; Unit *trigger; int r; assert(t); assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED); trigger = UNIT_TRIGGER(u); if (!trigger || trigger->load_state != UNIT_LOADED) { log_unit_error(u, "Refusing to start, unit to trigger not loaded."); return -ENOENT; } r = <API key>(u); if (r < 0) { timer_enter_dead(t, <API key>); return r; } r = <API key>(u); if (r < 0) return r; t->last_trigger = DUAL_TIMESTAMP_NULL; /* Reenable all timers that depend on unit activation time */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_ACTIVE) v->disabled = false; if (t->stamp_path) { struct stat st; if (stat(t->stamp_path, &st) >= 0) t->last_trigger.realtime = timespec_load(&st.st_atim); else if (errno == ENOENT) /* The timer has never run before, * make sure a stamp file exists. */ (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID); } t->result = TIMER_SUCCESS; timer_enter_waiting(t, true); return 1; } static int timer_stop(Unit *u) { Timer *t = TIMER(u); assert(t); assert(t->state == TIMER_WAITING || t->state == TIMER_RUNNING || t->state == TIMER_ELAPSED); timer_enter_dead(t, TIMER_SUCCESS); return 1; } static int timer_serialize(Unit *u, FILE *f, FDSet *fds) { Timer *t = TIMER(u); assert(u); assert(f); assert(fds); unit_serialize_item(u, f, "state", <API key>(t->state)); unit_serialize_item(u, f, "result", <API key>(t->result)); if (t->last_trigger.realtime > 0) <API key>(u, f, "<API key>", "%" PRIu64, t->last_trigger.realtime); if (t->last_trigger.monotonic > 0) <API key>(u, f, "<API key>", "%" PRIu64, t->last_trigger.monotonic); return 0; } static int <API key>(Unit *u, const char *key, const char *value, FDSet *fds) { Timer *t = TIMER(u); int r; assert(u); assert(key); assert(value); assert(fds); if (streq(key, "state")) { TimerState state; state = <API key>(value); if (state < 0) log_unit_debug(u, "Failed to parse state value: %s", value); else t->deserialized_state = state; } else if (streq(key, "result")) { TimerResult f; f = <API key>(value); if (f < 0) log_unit_debug(u, "Failed to parse result value: %s", value); else if (f != TIMER_SUCCESS) t->result = f; } else if (streq(key, "<API key>")) { r = safe_atou64(value, &t->last_trigger.realtime); if (r < 0) log_unit_debug(u, "Failed to parse <API key> value: %s", value); } else if (streq(key, "<API key>")) { r = safe_atou64(value, &t->last_trigger.monotonic); if (r < 0) log_unit_debug(u, "Failed to parse <API key> value: %s", value); } else log_unit_debug(u, "Unknown serialization key: %s", key); return 0; } _pure_ static UnitActiveState timer_active_state(Unit *u) { assert(u); return <API key>[TIMER(u)->state]; } _pure_ static const char *<API key>(Unit *u) { assert(u); return <API key>(TIMER(u)->state); } static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) { Timer *t = TIMER(userdata); assert(t); if (t->state != TIMER_WAITING) return 0; log_unit_debug(UNIT(t), "Timer elapsed."); timer_enter_running(t); return 0; } static void <API key>(Unit *u, Unit *other) { Timer *t = TIMER(u); TimerValue *v; assert(u); assert(other); if (other->load_state != UNIT_LOADED) return; /* Reenable all timers that depend on unit state */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_UNIT_ACTIVE || v->base == TIMER_UNIT_INACTIVE) v->disabled = false; switch (t->state) { case TIMER_WAITING: case TIMER_ELAPSED: /* Recalculate sleep time */ timer_enter_waiting(t, false); break; case TIMER_RUNNING: if (<API key>(unit_active_state(other))) { log_unit_debug(UNIT(t), "Got notified about unit deactivation."); timer_enter_waiting(t, false); } break; case TIMER_DEAD: case TIMER_FAILED: break; default: assert_not_reached("Unknown timer state"); } } static void timer_reset_failed(Unit *u) { Timer *t = TIMER(u); assert(t); if (t->state == TIMER_FAILED) timer_set_state(t, TIMER_DEAD); t->result = TIMER_SUCCESS; } static void timer_time_change(Unit *u) { Timer *t = TIMER(u); assert(u); if (t->state != TIMER_WAITING) return; log_unit_debug(u, "Time change, recalculating next elapse."); timer_enter_waiting(t, false); } static const char* const timer_base_table[_TIMER_BASE_MAX] = { [TIMER_ACTIVE] = "OnActiveSec", [TIMER_BOOT] = "OnBootSec", [TIMER_STARTUP] = "OnStartupSec", [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec", [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec", [TIMER_CALENDAR] = "OnCalendar" }; <API key>(timer_base, TimerBase); static const char* const timer_result_table[_TIMER_RESULT_MAX] = { [TIMER_SUCCESS] = "success", [<API key>] = "resources", [<API key>] = "start-limit-hit", }; <API key>(timer_result, TimerResult); const UnitVTable timer_vtable = { .object_size = sizeof(Timer), .sections = "Unit\0" "Timer\0" "Install\0", .private_section = "Timer", .init = timer_init, .done = timer_done, .load = timer_load, .coldplug = timer_coldplug, .dump = timer_dump, .start = timer_start, .stop = timer_stop, .serialize = timer_serialize, .deserialize_item = <API key>, .active_state = timer_active_state, .sub_state_to_string = <API key>, .trigger_notify = <API key>, .reset_failed = timer_reset_failed, .time_change = timer_time_change, .bus_vtable = bus_timer_vtable, .bus_set_property = <API key>, .can_transient = true, };
<?php namespace Magento\Backend\Block\Dashboard; /** * Adminhtml dashboard bottom tabs * * @author Magento Core Team <core@magentocommerce.com> */ class Grids extends \Magento\Backend\Block\Widget\Tabs { /** * @var string */ protected $_template = 'Magento_Backend::widget/tabshoriz.phtml'; /** * @return void */ protected function _construct() { parent::_construct(); $this->setId('grid_tab'); $this->setDestElementId('grid_tab_content'); } /** * Prepare layout for dashboard bottom tabs * * To load block statically: * 1) content must be generated * 2) url should not be specified * 3) class should not be 'ajax' * To load with ajax: * 1) do not load content * 2) specify url (BE CAREFUL) * 3) specify class 'ajax' * * @return $this */ protected function _prepareLayout() { // load this active tab statically $this->addTab( 'ordered_products', [ 'label' => __('Bestsellers'), 'content' => $this->getLayout()->createBlock( 'Magento\Backend\Block\Dashboard\Tab\Products\Ordered' )->toHtml(), 'active' => true ] ); // load other tabs with ajax $this->addTab( 'reviewed_products', [ 'label' => __('Most Viewed Products'), 'url' => $this->getUrl('adminhtml/*/productsViewed', ['_current' => true]), 'class' => 'ajax' ] ); $this->addTab( 'new_customers', [ 'label' => __('New Customers'), 'url' => $this->getUrl('adminhtml/*/customersNewest', ['_current' => true]), 'class' => 'ajax' ] ); $this->addTab( 'customers', [ 'label' => __('Customers'), 'url' => $this->getUrl('adminhtml/*/customersMost', ['_current' => true]), 'class' => 'ajax' ] ); return parent::_prepareLayout(); } }
package org.liferay.jukebox; import com.liferay.portal.kernel.exception.PortalException; /** * @author Julio Camarero */ public class SongNameException extends PortalException { public SongNameException() { super(); } public SongNameException(String msg) { super(msg); } public SongNameException(String msg, Throwable cause) { super(msg, cause); } public SongNameException(Throwable cause) { super(cause); } }
#ifndef CRASHDUMP_POWERPC_H #define CRASHDUMP_POWERPC_H struct kexec_info; int <API key>(struct kexec_info *info, char *mod_cmdline, unsigned long max_addr, unsigned long min_base); void add_usable_mem_rgns(unsigned long long base, unsigned long long size); extern struct arch_options_t arch_options; #ifdef CONFIG_PPC64 #define PAGE_OFFSET <API key> #define VMALLOCBASE <API key> #define MAXMEM (-<API key>) #else #define PAGE_OFFSET 0xC0000000 #define MAXMEM 0x30000000 /* Use CONFIG_LOWMEM_SIZE from kernel */ #endif #define KERNELBASE PAGE_OFFSET #define __pa(x) ((unsigned long)(x)-PAGE_OFFSET) #define COMMAND_LINE_SIZE 512 /* from kernel */ #ifdef CONFIG_BOOKE /* We don't need backup region in Book E */ #define BACKUP_SRC_START 0x0000 #define BACKUP_SRC_END 0x0000 #define BACKUP_SRC_SIZE 0x0000 #else /* Backup Region, First 64K of System RAM. */ #define BACKUP_SRC_START 0x0000 #define BACKUP_SRC_END 0xffff #define BACKUP_SRC_SIZE (BACKUP_SRC_END - BACKUP_SRC_START + 1) #endif #define KDUMP_BACKUP_LIMIT BACKUP_SRC_SIZE #define _ALIGN_UP(addr, size) (((addr)+((size)-1))&(~((size)-1))) #define _ALIGN_DOWN(addr, size) ((addr)&(~((size)-1))) extern unsigned long long crash_base; extern unsigned long long crash_size; extern unsigned int rtas_base; extern unsigned int rtas_size; #endif /* CRASHDUMP_POWERPC_H */
<?php function icl_get_home_url() { global $sitepress; return $sitepress->language_url($sitepress-><API key>()); } // args: // skip_missing (0|1|true|false) // orderby (id|code|name) // order (asc|desc) function icl_get_languages($a='') { if ($a) { parse_str($a, $args); } else { $args = ''; } global $sitepress; $langs = $sitepress->get_ls_languages($args); return $langs; } function icl_disp_language($native_name, $translated_name, $lang_native_hidden = false, $<API key> = false) { if (!$native_name && !$translated_name) { $ret = ''; } elseif ($native_name && $translated_name) { $hidden1 = $hidden2 = $hidden3 = ''; if ($lang_native_hidden) { $hidden1 = 'style="display:none;"'; } if ($<API key>) { $hidden2 = 'style="display:none;"'; } if ($lang_native_hidden && $<API key>) { $hidden3 = 'style="display:none;"'; } if ($native_name != $translated_name) { $ret = '<span ' . $hidden1 . ' class="icl_lang_sel_native">' . $native_name . '</span> <span ' . $hidden2 . ' class="<API key>"><span ' . $hidden1 . ' class="icl_lang_sel_native">(</span>' . $translated_name . '<span ' . $hidden1 . ' class="icl_lang_sel_native">)</span></span>'; } else { $ret = '<span ' . $hidden3 . ' class="<API key>">' . $native_name . '</span>'; } } elseif ($native_name) { $ret = $native_name; } elseif ($translated_name) { $ret = $translated_name; } return $ret; } function icl_link_to_element($element_id, $element_type='post', $link_text='', $optional_parameters=array(), $anchor='', $echoit = true, $<API key> = true) { global $sitepress, $wpdb, $wp_post_types, $wp_taxonomies; if ($element_type == 'tag') $element_type = 'post_tag'; if ($element_type == 'page') $element_type = 'post'; $post_types = array_keys((array) $wp_post_types); $taxonomies = array_keys((array) $wp_taxonomies); if (in_array($element_type, $taxonomies)) { $element_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id= %d AND taxonomy='{$element_type}'", $element_id)); } elseif (in_array($element_type, $post_types)) { $element_type = 'post'; } if (!$element_id) return ''; if (in_array($element_type, $taxonomies)) { $icl_element_type = 'tax_' . $element_type; } elseif (in_array($element_type, $post_types)) { $icl_element_type = 'post_' . $wpdb->get_var("SELECT post_type FROM {$wpdb->posts} WHERE ID='{$element_id}'"); } $trid = $sitepress->get_element_trid($element_id, $icl_element_type); $translations = $sitepress-><API key>($trid, $icl_element_type); // current language is ICL_LANGUAGE_CODE if (isset($translations[ICL_LANGUAGE_CODE])) { if ($element_type == 'post') { $url = get_permalink($translations[ICL_LANGUAGE_CODE]->element_id); $title = $translations[ICL_LANGUAGE_CODE]->post_title; } elseif ($element_type == 'post_tag') { list($term_id, $title) = $wpdb->get_row($wpdb->prepare("SELECT t.term_id, t.name FROM {$wpdb->term_taxonomy} tx JOIN {$wpdb->terms} t ON t.term_id = tx.term_id WHERE tx.term_taxonomy_id = %d AND tx.taxonomy='post_tag'", $translations[ICL_LANGUAGE_CODE]->element_id), ARRAY_N); $url = get_tag_link($term_id); $title = apply_filters('single_cat_title', $title); } elseif ($element_type == 'category') { list($term_id, $title) = $wpdb->get_row($wpdb->prepare("SELECT t.term_id, t.name FROM {$wpdb->term_taxonomy} tx JOIN {$wpdb->terms} t ON t.term_id = tx.term_id WHERE tx.term_taxonomy_id = %d AND tx.taxonomy='category'", $translations[ICL_LANGUAGE_CODE]->element_id), ARRAY_N); $url = get_category_link($term_id); $title = apply_filters('single_cat_title', $title); } else { list($term_id, $title) = $wpdb->get_row($wpdb->prepare("SELECT t.term_id, t.name FROM {$wpdb->term_taxonomy} tx JOIN {$wpdb->terms} t ON t.term_id = tx.term_id WHERE tx.term_taxonomy_id = %d AND tx.taxonomy='{$element_type}'", $translations[ICL_LANGUAGE_CODE]->element_id), ARRAY_N); $url = get_term_link($term_id, $element_type); $title = apply_filters('single_cat_title', $title); } } else { if (!$<API key>) { if ($echoit) { echo ''; } return ''; } if ($element_type == 'post') { $url = get_permalink($element_id); $title = get_the_title($element_id); } elseif ($element_type == 'post_tag') { $url = get_tag_link($element_id); $my_tag = &get_term($element_id, 'post_tag', OBJECT, 'display'); $title = apply_filters('single_tag_title', $my_tag->name); } elseif ($element_type == 'category') { $url = get_category_link($element_id); $my_cat = &get_term($element_id, 'category', OBJECT, 'display'); $title = apply_filters('single_cat_title', $my_cat->name); } else { $url = get_term_link((int) $element_id, $element_type); $my_cat = &get_term($element_id, $element_type, OBJECT, 'display'); $title = apply_filters('single_cat_title', $my_cat->name); } } if (!$url || is_wp_error($url)) return ''; if (!empty($optional_parameters)) { $url_glue = false === strpos($url, '?') ? '?' : '&'; $url .= $url_glue . http_build_query($optional_parameters); } if (isset($anchor) && $anchor) { $url .= '#' . $anchor; } $link = '<a href="' . $url . '">'; if (isset($link_text) && $link_text) { $link .= $link_text; } else { $link .= $title; } $link .= '</a>'; if ($echoit) { echo $link; } else { return $link; } } function icl_object_id($element_id, $element_type='post', $<API key>=false, $ulanguage_code=null) { global $sitepress, $wpdb, $wp_post_types, $wp_taxonomies; // special case of any - we assume it's a post type if($element_type == 'any' && $_dtype = $wpdb->get_var($wpdb->prepare("SELECT post_type FROM {$wpdb->posts} WHERE ID=%d", $element_id))){ $element_type = $_dtype; } static $fcache = array(); $fcache_key = $element_id . '#' . $element_type . '#' . intval($<API key>) . '#' . $ulanguage_code; if (isset($fcache[$fcache_key])) { return $fcache[$fcache_key]; } if ($element_id <= 0) { return $element_id; } $post_types = array_keys((array) $wp_post_types); $taxonomies = array_keys((array) $wp_taxonomies); $element_types = array_merge($post_types, $taxonomies); $element_types[] = 'comment'; if (!in_array($element_type, $element_types)) { trigger_error(sprintf(__('Invalid object kind: %s', 'sitepress'), $element_type), E_USER_NOTICE); return null; } elseif (!$element_id) { trigger_error(__('Invalid object id', 'sitepress'), E_USER_NOTICE); return null; } if (in_array($element_type, $taxonomies)) { $icl_element_id = $wpdb->get_var($wpdb->prepare("SELECT term_taxonomy_id FROM {$wpdb->term_taxonomy} WHERE term_id= %d AND taxonomy='{$element_type}'", $element_id)); } else { $icl_element_id = $element_id; } if (in_array($element_type, $taxonomies)) { $icl_element_type = 'tax_' . $element_type; } elseif (in_array($element_type, $post_types)) { $icl_element_type = 'post_' . $element_type; } else { $icl_element_type = $element_type; } $trid = $sitepress->get_element_trid($icl_element_id, $icl_element_type); $translations = $sitepress-><API key>($trid, $icl_element_type); if (is_null($ulanguage_code)) { $ulanguage_code = $sitepress-><API key>(); } if (isset($translations[$ulanguage_code]->element_id)) { $ret_element_id = $translations[$ulanguage_code]->element_id; if (in_array($element_type, $taxonomies)) { $ret_element_id = $wpdb->get_var($wpdb->prepare("SELECT t.term_id FROM {$wpdb->term_taxonomy} tx JOIN {$wpdb->terms} t ON t.term_id = tx.term_id WHERE tx.term_taxonomy_id = %d AND tx.taxonomy='{$element_type}'", $ret_element_id)); } } else { $ret_element_id = $<API key> ? $element_id : null; } $fcache[$fcache_key] = $ret_element_id; return $ret_element_id; } function <API key>() { global $sitepress; return $sitepress-><API key>(); } function <API key>($folder, $rec = 0) { global $sitepress; $dh = @opendir($folder); $lfn = $sitepress-><API key>(); while ($file = readdir($dh)) { if (0 === strpos($file, '.')) continue; if (is_file($folder . '/' . $file) && preg_match('#\.mo$#i', $file) && in_array(preg_replace('#\.mo$#i', '', $file), $lfn)) { return $folder; } elseif (is_dir($folder . '/' . $file) && $rec < 5) { if ($f = <API key>($folder . '/' . $file, $rec + 1)) { return $f; }; } } return false; } function <API key>($id, $custom_field = false, $class = 'wpml', $ajax = false, $default_value = 'ignore', $fieldset = false, $suppress_error = false) { $output = ''; if ($custom_field) { $custom_field = @strval($custom_field); } $class = @strval($class); if ($fieldset) { $output .= ' <fieldset id="<API key>' . $id . '" class="<API key> ' . $class . '-form-fieldset form-fieldset fieldset">' . '<legend>' . __('Translation preferences', 'wpml') . '</legend>'; } $actions = array('ignore' => 0, 'copy' => 1, 'translate' => 2); $action = isset($actions[@strval($default_value)]) ? $actions[@strval($default_value)] : 0; global $<API key>; if ($custom_field) { if (defined('WPML_TM_VERSION') && !empty($<API key>)) { if (isset($<API key>->settings['<API key>'][$custom_field])) { $action = intval($<API key>->settings['<API key>'][$custom_field]); } $disabled = $xml_override = in_array($custom_field, (array)$<API key>->settings['<API key>']); if ($disabled) { $output .= '<div style="color:Red;font-style:italic;margin: 10px 0 0 0;">' . __('The translation preference for this field are being controlled by a language configuration XML file. If you want to control it manually, remove the entry from the configuration file.', 'wpml') . '</div>'; } } else if (!$suppress_error) { $output .= '<span style="color:#FF0000;">' . __("To synchronize values for translations, you need to enable WPML's Translation Management module.", 'wpml') . '</span>'; $disabled = true; } } else if (!$suppress_error) { $output .= '<span style="color:#FF0000;">' . __('Error: Something is wrong with field value. Translation preferences can not be set.', 'wpml') . '</span>'; $disabled = true; } $disabled = !empty($disabled) ? ' readonly="readonly" disabled="disabled"' : ''; $output .= '<div class="description ' . $class . '-form-description ' . $class . '-<API key> <API key>">' . __('Choose what to do when translating content with this field:', 'wpml') . '</div> <input'; $output .= $action == 0 ? ' checked="checked"' : ''; $output .= ' id="<API key>' . $id . '" name="<API key>[' . $id . ']" value="0" class="' . $class . '-form-radio form-radio radio" type="radio"' . $disabled . '>&nbsp;<label class="' . $class . '-form-label ' . $class . '-form-radio-label" for="<API key>' . $id . '">' . __('Do nothing', 'wpml') . '</label> <br /> <input'; $output .= $action == 1 ? ' checked="checked"' : ''; $output .= ' id="<API key>' . $id . '" name="<API key>[' . $id . ']" value="1" class="' . $class . '-form-radio form-radio radio" type="radio"' . $disabled . '>&nbsp;<label class="' . $class . '-form-label ' . $class . '-form-radio-label" for="<API key>' . $id. '">' . __('Copy from original', 'wpml') . '</label> <br /> <input'; $output .= $action == 2 ? ' checked="checked"' : ''; $output .= ' id="<API key>' . $id . '" name="<API key>[' . $id . ']" value="2" class="' . $class . '-form-radio form-radio radio" type="radio"' . $disabled . '>&nbsp;<label class="' . $class . '-form-label ' . $class . '-form-radio-label" for="<API key>' . $id . '">' . __('Translate', 'wpml') . '</label> <br />'; if ($custom_field && $ajax) { $output .= ' <div style=";margin: 5px 0 5px 0;" id="<API key>' . $id . '"></div> <input type="button" onclick="<API key>(\'' . $id . '\', jQuery(this));" style="margin-top:5px;" class="button-secondary" value="' . __('Apply') . '" name="<API key>' . $id . '" /> <input type="hidden" name="<API key>' . $id . '" value="custom_field=' . $custom_field . '&amp;_icl_nonce=' . wp_create_nonce('<API key>') . '" />'; } if ($fieldset) { $output .= ' </fieldset> '; } return $output; } function <API key>($id, $custom_field) { if (defined('WPML_TM_VERSION')) { if (empty($id) || empty($custom_field) || !isset($_POST['<API key>'][$id])) { return false; } $custom_field = @strval($custom_field); $action = @intval($_POST['<API key>'][$id]); global $<API key>; if (!empty($<API key>)) { $<API key>->settings['<API key>'][$custom_field] = $action; $<API key>->save_settings(); return true; } else { return false; } } return false; } /** * <API key> * * return a list of fields that are marked for copying and the * original post id that the fields should be copied from * * This should be used to popupate any custom field controls when * a new translation is selected and the field is marked as "copy" (sync) */ function <API key>() { global $sitepress, $wpdb, $sitepress_settings, $pagenow; $copied_cf = array('fields' => array()); $translations = null; if (defined('WPML_TM_VERSION')) { if(($pagenow == 'post-new.php' || $pagenow == 'post.php')) { if (isset($_GET['trid'])){ $post_type = isset($_GET['post_type'])?$_GET['post_type']:'post'; $translations = $sitepress-><API key>($_GET['trid'], 'post_' . $post_type); $source_lang = isset($_GET['source_lang'])?$_GET['source_lang']:$sitepress-><API key>(); $lang_details = $sitepress-><API key>($source_lang); } else if (isset($_GET['post'])) { $post_id = @intval($_GET['post']); $post_type = $wpdb->get_var("SELECT post_type FROM {$wpdb->posts} WHERE ID='{$post_id}'"); $trid = $sitepress->get_element_trid($post_id, 'post_' . $post_type); $original_id = $wpdb->get_var($wpdb->prepare("SELECT element_id FROM {$wpdb->prefix}icl_translations WHERE <API key> IS NULL AND trid=%d", $trid)); if ($original_id != $post_id) { // Only return information if this is not the source language post. $translations = $sitepress-><API key>($trid, 'post_' . $post_type); $source_lang = $wpdb->get_var($wpdb->prepare("SELECT language_code FROM {$wpdb->prefix}icl_translations WHERE <API key> IS NULL AND trid=%d", $trid)); $lang_details = $sitepress-><API key>($source_lang); } } if ($translations) { $original_custom = get_post_custom($translations[$source_lang]->element_id); $copied_cf['original_post_id'] = $translations[$source_lang]->element_id; $ccf_note = '<img src="' . ICL_PLUGIN_URL . '/res/img/alert.png" alt="Notice" width="16" height="16" style="margin-right:8px" />'; $copied_cf['copy_message'] = $ccf_note . sprintf(__('WPML will copy this field from %s when you save this post.', 'sitepress'), $lang_details['display_name']); foreach((array)$sitepress_settings['<API key>']['<API key>'] as $key=>$sync_opt){ if($sync_opt == 1 && isset($original_custom[$key])){ $copied_cf['fields'][] = $key; } } } } } return $copied_cf; } function <API key>($post_id = null){ global $sitepress; if(is_null($post_id)){ $post_id = get_the_ID(); } if(empty($post_id)) return new WP_Error('missing_id', __('Missing post ID', 'sitepress')); $post = get_post($post_id); if(empty($post)) return new WP_Error('missing_post', sprintf(__('No such post for ID = %d', 'sitepress'), $post_id)); $language = $sitepress-><API key>($post_id, 'post_' . $post->post_type); $<API key> = $sitepress-><API key>($language); $info = array( 'locale' => $sitepress->get_locale($language), 'text_direction' => $sitepress->is_rtl($language), 'display_name' => $sitepress-><API key>($language, $sitepress-><API key>()), 'native_name' => $<API key>['display_name'], 'different_language' => $language != $sitepress-><API key>() ); return $info; } function <API key>($type_id){ global $sitepress, $sitepress_settings; $out = '<table id="<API key>" class="<API key> widefat"><thead><tr><th>' . __('Translation', 'sitepress') . '</th></tr></thead><tbody><tr><td>'; $type = <API key>($type_id); $translated = $sitepress-><API key>($type_id); if(defined('WPML_TM_VERSION')){ $link = admin_url('admin.php?page=' . WPML_TM_FOLDER . '/menu/main.php&sm=mcsetup#<API key>'); $link2 = admin_url('admin.php?page=' . WPML_TM_FOLDER . '/menu/main.php&sm=mcsetup#<API key>'); }else{ $link = admin_url('admin.php?page=' . ICL_PLUGIN_FOLDER . '/menu/translation-options.php#<API key>'); $link2 = admin_url('admin.php?page=' . ICL_PLUGIN_FOLDER . '/menu/translation-options.php#<API key>'); } if($translated){ $out .= sprintf(__('%s is translated via WPML. %sClick here to change translation options.%s', 'sitepress'), '<strong>' . $type->labels->singular_name . '</strong>', '<a href="'.$link.'">', '</a>'); if($type->rewrite['enabled']){ if($sitepress_settings['<API key>']['on']){ if(empty($sitepress_settings['<API key>']['types'][$type_id])){ $out .= '<ul><li>' . __('Slugs are currently not translated.', 'sitepress') . '<li></ul>'; }else{ $out .= '<ul><li>' . __('Slugs are currently translated. Click the link above to edit the translations.', 'sitepress') . '<li></ul>'; } }else{ $out .= '<ul><li>' . sprintf(__('Slug translation is currently disabled in WPML. %sClick here to enable.%s', 'sitepress'), '<a href="'.$link2.'">', '</a>') . '</li></ul>'; } } }else{ $out .= sprintf(__('%s is not translated. %sClick here to make this post type translatable.%s', 'sitepress'), '<strong>' . $type->labels->singular_name . '</strong>', '<a href="'.$link.'">', '</a>'); } $out .= '</tbody></table>'; return $out; }
!===================================================================== ! ! S p e c f e m 3 D V e r s i o n 3 . 0 ! ! ! Main historical authors: Dimitri Komatitsch and Jeroen Tromp ! Princeton University, USA ! and CNRS / University of Marseille, France ! (there are currently many more authors!) ! (c) Princeton University and CNRS / University of Marseille, July 2012 ! ! This program is free software; you can redistribute it and/or modify ! it under the terms of the GNU General Public License as published by ! the Free Software Foundation; either version 2 of the License, or ! (at your option) any later version. ! ! This program is distributed in the hope that it will be useful, ! but WITHOUT ANY WARRANTY; without even the implied warranty of ! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ! GNU General Public License for more details. ! ! You should have received a copy of the GNU General Public License along ! with this program; if not, write to the Free Software Foundation, Inc., ! 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ! !===================================================================== subroutine <API key>(NEX_PER_PROC_XI,NEX_PER_PROC_ETA,iproc_xi,iproc_eta,& isubregion,nbsubregions,subregions, & iaddx,iaddy,iaddz,ix1,ix2,dix,iy1,iy2,diy,ir1,ir2,dir,iax,iay,iar, & num_material) use constants implicit none integer NEX_PER_PROC_XI,NEX_PER_PROC_ETA integer iproc_xi,iproc_eta integer ix1,ix2,dix,iy1,iy2,diy,ir1,ir2,dir integer iax,iay,iar integer isubregion,nbsubregions integer num_material ! topology of the elements integer iaddx(NGNOD_EIGHT_CORNERS) integer iaddy(NGNOD_EIGHT_CORNERS) integer iaddz(NGNOD_EIGHT_CORNERS) ! definition of the different regions of the model in the mesh (nx,ny,nz) ! #1 #2 : nx_begining,nx_end ! #3 #4 : ny_begining,ny_end ! #5 #6 : nz_begining,nz_end ! #7 : material number integer subregions(nbsubregions,7) call usual_hex_nodes(NGNOD_EIGHT_CORNERS,iaddx,iaddy,iaddz) ix1=2*(subregions(isubregion,1) - iproc_xi*NEX_PER_PROC_XI - 1) if (ix1 < 0) ix1 = 0 ix2=2*(subregions(isubregion,2) - iproc_xi*NEX_PER_PROC_XI - 1) if (ix2 > 2*(NEX_PER_PROC_XI - 1)) ix2 = 2*(NEX_PER_PROC_XI - 1) dix=2 iy1=2*(subregions(isubregion,3) - iproc_eta*NEX_PER_PROC_ETA - 1) if (iy1 < 0) iy1 = 0 iy2=2*(subregions(isubregion,4) - iproc_eta*NEX_PER_PROC_ETA - 1) if (iy2 > 2*(NEX_PER_PROC_ETA - 1)) iy2 = 2*(NEX_PER_PROC_ETA - 1) diy=2 ir1=2*(subregions(isubregion,5) - 1) ir2=2*(subregions(isubregion,6) - 1) dir=2 iax=1 iay=1 iar=1 num_material = subregions(isubregion,7) end subroutine <API key> ! ! ! subroutine define_mesh_regions(USE_REGULAR_MESH,isubregion,NER,NEX_PER_PROC_XI,NEX_PER_PROC_ETA,iproc_xi,iproc_eta,& ndoublings,ner_doublings,& iaddx,iaddy,iaddz,ix1,ix2,dix,iy1,iy2,diy,ir1,ir2,dir,iax,iay,iar) use constants implicit none logical USE_REGULAR_MESH integer isubregion integer NEX_PER_PROC_XI,NEX_PER_PROC_ETA,NER integer iproc_xi,iproc_eta integer ix1,ix2,dix,iy1,iy2,diy,ir1,ir2,dir integer iax,iay,iar integer ndoublings ! topology of the elements integer iaddx(NGNOD_EIGHT_CORNERS) integer iaddy(NGNOD_EIGHT_CORNERS) integer iaddz(NGNOD_EIGHT_CORNERS) integer ner_doublings(2) ! to avoid compiler warnings integer idummy idummy = iproc_xi idummy = iproc_eta ! ************** ! !--- case of a regular mesh ! if (USE_REGULAR_MESH) then call usual_hex_nodes(NGNOD_EIGHT_CORNERS,iaddx,iaddy,iaddz) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=2 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=2 ir1=0 ir2=2*(NER - 1) dir=2 iax=1 iay=1 iar=1 else if (ndoublings == 1) then select case (isubregion) case (1) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=4 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=4 ir1=0 ir2=2*(ner_doublings(1) -2 -1) dir=2 iax=2 iay=2 iar=1 case (2) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=8 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=8 ir1=2*(ner_doublings(1) - 2) ir2=2*(ner_doublings(1) - 2) dir=2 iax=4 iay=4 iar=2 case (3) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=2 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=2 ir1=2*(ner_doublings(1)) ir2=2*(NER - 1) dir=2 iax=1 iay=1 iar=1 case default stop 'Wrong number of subregions' end select else if (ndoublings == 2) then select case (isubregion) case (1) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=8 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=8 ir1=0 ir2=2*(ner_doublings(2) -2 -1) dir=2 iax=4 iay=4 iar=1 case (2) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=16 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=16 ir1=2*(ner_doublings(2) - 2) ir2=2*(ner_doublings(2) - 2) dir=2 iax=8 iay=8 iar=2 case (3) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=4 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=4 ir1=2*ner_doublings(2) ir2=2*(ner_doublings(1) -2 -1) dir=2 iax=2 iay=2 iar=1 case (4) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=8 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=8 ir1=2*(ner_doublings(1) - 2) ir2=2*(ner_doublings(1) - 2) dir=2 iax=4 iay=4 iar=2 case (5) ix1=0 ix2=2*(NEX_PER_PROC_XI - 1) dix=2 iy1=0 iy2=2*(NEX_PER_PROC_ETA - 1) diy=2 ir1=2*(ner_doublings(1)) ir2=2*(NER - 1) dir=2 iax=1 iay=1 iar=1 case default stop 'Wrong number of subregions' end select else stop 'Wrong number of doublings' endif endif end subroutine define_mesh_regions
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ #pragma once #include <stdbool.h> #include "condition.h" #include "udev.h" bool net_match_config(const struct ether_addr *match_mac, char * const *match_path, char * const *match_driver, char * const *match_type, char * const *match_name, Condition *match_host, Condition *match_virt, Condition *match_kernel, Condition *match_arch, const struct ether_addr *dev_mac, const char *dev_path, const char *dev_parent_driver, const char *dev_driver, const char *dev_type, const char *dev_name); int <API key>(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata); int config_parse_hwaddr(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata); int config_parse_ifname(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata); int <API key>(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata); int <API key>(const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata); int <API key>(struct udev_device *device, uint64_t *result); const char *net_get_name(struct udev_device *device); void serialize_in_addrs(FILE *f, const struct in_addr *addresses, size_t size); int <API key>(struct in_addr **addresses, const char *string); void serialize_in6_addrs(FILE *f, const struct in6_addr *addresses, size_t size); int <API key>(struct in6_addr **addresses, const char *string); /* don't include "dhcp-lease-internal.h" as it causes conflicts between netinet/ip.h and linux/ip.h */ struct sd_dhcp_route; void <API key>(FILE *f, const char *key, struct sd_dhcp_route *routes, size_t size); int <API key>(struct sd_dhcp_route **ret, size_t *ret_size, size_t *ret_allocated, const char *string); int <API key>(FILE *f, const char *key, const void *data, size_t size); int <API key>(void **data, size_t *data_len, const char *string);
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstsirenenc.h" #include <string.h> GST_DEBUG_CATEGORY (sirenenc_debug); #define GST_CAT_DEFAULT (sirenenc_debug) #define FRAME_DURATION (20 * GST_MSECOND) static <API key> srctemplate = <API key> ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/x-siren, " "dct-length = (int) 320")); static <API key> sinktemplate = <API key> ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/x-raw-int, " "width = (int) 16, " "depth = (int) 16, " "endianness = (int) 1234, " "signed = (boolean) true, " "rate = (int) 16000, " "channels = (int) 1")); /* signals and args */ enum { /* FILL ME */ LAST_SIGNAL }; enum { ARG_0, }; static gboolean gst_siren_enc_start (GstAudioEncoder * enc); static gboolean gst_siren_enc_stop (GstAudioEncoder * enc); static gboolean <API key> (GstAudioEncoder * enc, GstAudioInfo * info); static GstFlowReturn <API key> (GstAudioEncoder * enc, GstBuffer * in_buf); static void _do_init (GType type) { <API key> (sirenenc_debug, "sirenenc", 0, "sirenenc"); } <API key> (GstSirenEnc, gst_siren_enc, GstAudioEncoder, <API key>, _do_init); static void <API key> (gpointer klass) { GstElementClass *element_class = GST_ELEMENT_CLASS (klass); <API key> (element_class, &srctemplate); <API key> (element_class, &sinktemplate); <API key> (element_class, "Siren Encoder element", "Codec/Encoder/Audio ", "Encode 16bit PCM streams into the Siren7 codec", "Youness Alaoui <kakaroto@kakaroto.homelinux.net>"); } static void <API key> (GstSirenEncClass * klass) { <API key> *base_class = <API key> (klass); GST_DEBUG ("Initializing Class"); base_class->start = GST_DEBUG_FUNCPTR (gst_siren_enc_start); base_class->stop = GST_DEBUG_FUNCPTR (gst_siren_enc_stop); base_class->set_format = GST_DEBUG_FUNCPTR (<API key>); base_class->handle_frame = GST_DEBUG_FUNCPTR (<API key>); GST_DEBUG ("Class Init done"); } static void gst_siren_enc_init (GstSirenEnc * enc, GstSirenEncClass * klass) { } static gboolean gst_siren_enc_start (GstAudioEncoder * enc) { GstSirenEnc *senc = GST_SIREN_ENC (enc); GST_DEBUG_OBJECT (enc, "start"); senc->encoder = Siren7_NewEncoder (16000); return TRUE; } static gboolean gst_siren_enc_stop (GstAudioEncoder * enc) { GstSirenEnc *senc = GST_SIREN_ENC (enc); GST_DEBUG_OBJECT (senc, "stop"); Siren7_CloseEncoder (senc->encoder); return TRUE; } static gboolean <API key> (GstAudioEncoder * benc, GstAudioInfo * info) { GstSirenEnc *enc; gboolean res; GstCaps *outcaps; enc = GST_SIREN_ENC (benc); outcaps = <API key> (&srctemplate); res = gst_pad_set_caps (<API key> (enc), outcaps); gst_caps_unref (outcaps); /* report needs to base class */ <API key> (benc, 320); <API key> (benc, 320); /* no remainder or flushing please */ <API key> (benc, TRUE); <API key> (benc, FALSE); return res; } static GstFlowReturn <API key> (GstAudioEncoder * benc, GstBuffer * buf) { GstSirenEnc *enc; GstFlowReturn ret = GST_FLOW_OK; GstBuffer *out_buf; guint8 *in_data, *out_data; guint i, size, num_frames; gint out_size, in_size; gint encode_ret; <API key> (buf != NULL, GST_FLOW_ERROR); enc = GST_SIREN_ENC (benc); size = GST_BUFFER_SIZE (buf); GST_LOG_OBJECT (enc, "Received buffer of size %d", GST_BUFFER_SIZE (buf)); <API key> (size > 0, GST_FLOW_ERROR); <API key> (size % 640 == 0, GST_FLOW_ERROR); /* we need to process 640 input bytes to produce 40 output bytes */ /* calculate the amount of frames we will handle */ num_frames = size / 640; /* this is the input/output size */ in_size = num_frames * 640; out_size = num_frames * 40; GST_LOG_OBJECT (enc, "we have %u frames, %u in, %u out", num_frames, in_size, out_size); /* get a buffer */ ret = <API key> (<API key> (benc), -1, out_size, GST_PAD_CAPS (<API key> (benc)), &out_buf); if (ret != GST_FLOW_OK) goto alloc_failed; /* get the input data for all the frames */ in_data = GST_BUFFER_DATA (buf); out_data = GST_BUFFER_DATA (out_buf); for (i = 0; i < num_frames; i++) { GST_LOG_OBJECT (enc, "Encoding frame %u/%u", i, num_frames); /* encode 640 input bytes to 40 output bytes */ encode_ret = Siren7_EncodeFrame (enc->encoder, in_data, out_data); if (encode_ret != 0) goto encode_error; /* move to next frame */ out_data += 40; in_data += 640; } GST_LOG_OBJECT (enc, "Finished encoding"); /* we encode all we get, pass it along */ ret = <API key> (benc, out_buf, -1); done: return ret; /* ERRORS */ alloc_failed: { GST_DEBUG_OBJECT (enc, "failed to pad_alloc buffer: %d (%s)", ret, gst_flow_get_name (ret)); goto done; } encode_error: { GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL), ("Error encoding frame: %d", encode_ret)); ret = GST_FLOW_ERROR; gst_buffer_unref (out_buf); goto done; } } gboolean <API key> (GstPlugin * plugin) { return <API key> (plugin, "sirenenc", GST_RANK_MARGINAL, GST_TYPE_SIREN_ENC); }
<?php /** * Test Generated example of using loc_block create API * Create locBlock with existing entities * */ function <API key>(){ $params = array( 'address_id' => 2, 'phone_id' => 2, 'email_id' => 32, ); try{ $result = civicrm_api3('loc_block', 'create', $params); } catch (<API key> $e) { // handle error here $errorMessage = $e->getMessage(); $errorCode = $e->getErrorCode(); $errorData = $e->getExtraParams(); return array('error' => $errorMessage, 'error_code' => $errorCode, 'error_data' => $errorData); } return $result; } /** * Function returns array of result expected from previous function */ function <API key>(){ $expectedResult = array( 'is_error' => 0, 'version' => 3, 'count' => 1, 'id' => 2, 'values' => array( '2' => array( 'id' => '2', 'address_id' => '2', 'email_id' => '32', 'phone_id' => '2', 'im_id' => '', 'address_2_id' => '', 'email_2_id' => '', 'phone_2_id' => '', 'im_2_id' => '', ), ), ); return $expectedResult; }
<?php namespace VuFindTest\RecordDriver; use VuFind\RecordDriver\EDS; class EDSTest extends \PHPUnit\Framework\TestCase { /** * Test getUniqueID for a record. * * @return void */ public function testGetUniqueID() { $overrides = [ 'Header' => ['DbId' => 'TDB123', 'An' => 'TAn456'] ]; $driver = $this->getDriver($overrides); $this->assertEquals('TDB123,TAn456', $driver->getUniqueID()); } /** * Test getShortTitle for a record. * * @return void */ public function testGetShortTitle() { $this->assertEquals('', $this->getDriver()->getShortTitle()); } /** * Test getItemsAbstract for a record. * * @return void */ public function <API key>() { $this->assertEquals('', $this->getDriver()->getItemsAbstract()); } /** * Test getAccessLevel for a record. * * @return void */ public function testGetAccessLevel() { $this->assertEquals('', $this->getDriver()->getAccessLevel()); } /** * Test getItemsAuthors for a record. * * @return void */ public function testGetItemsAuthors() { $this->assertEquals('', $this->getDriver()->getItemsAuthors()); } /** * Test getCustomLinks for a record. * * @return void */ public function testGetCustomLinks() { $this->assertEquals([], $this->getDriver()->getCustomLinks()); } /** * Test getFTCustomLinks for a record. * * @return void */ public function <API key>() { $this->assertEquals([], $this->getDriver()->getFTCustomLinks()); } /** * Test getDbLabel for a record. * * @return void */ public function testGetDbLabel() { $this->assertEquals('', $this->getDriver()->getDbLabel()); } /** * Test getHTMLFullText for a record. * * @return void */ public function testGetHTMLFullText() { $this->assertEquals('', $this->getDriver()->getHTMLFullText()); } /** * Test <API key> for a record. * * @return void */ public function <API key>() { $this->assertEquals(false, $this->getDriver()-><API key>()); } /** * Test getItems for a record. * * @return void */ public function testGetItems() { $this->assertEquals([], $this->getDriver()->getItems()); } /** * Test getPLink for a record. * * @return void */ public function testGetPLink() { $this->assertEquals('', $this->getDriver()->getPLink()); } /** * Test getPubType for a record. * * @return void */ public function testGetPubType() { $this->assertEquals('', $this->getDriver()->getPubType()); } /** * Test getPubTypeId for a record. * * @return void */ public function testGetPubTypeId() { $this->assertEquals('', $this->getDriver()->getPubTypeId()); } /** * Test hasPdfAvailable for a record. * * @return void */ public function testHasPdfAvailable() { $this->assertEquals(false, $this->getDriver()->hasPdfAvailable()); } /** * Test getPdfLink for a record. * * @return void */ public function testGetPdfLink() { $this->assertEquals(false, $this->getDriver()->getPdfLink()); } /** * Test getItemsSubjects for a record. * * @return void */ public function <API key>() { $this->assertEquals('', $this->getDriver()->getItemsSubjects()); } /** * Test getThumbnail for a record. * * @return void */ public function testGetThumbnail() { $this->assertEquals(false, $this->getDriver()->getThumbnail()); } /** * Test getItemsTitle for a record. * * @return void */ public function testGetItemsTitle() { $this->assertEquals('', $this->getDriver()->getItemsTitle()); } /** * Test getTitle for a record. * * @return void */ public function testGetTitle() { $this->assertEquals('', $this->getDriver()->getTitle()); } /** * Test getPrimaryAuthors for a record. * * @return void */ public function <API key>() { $this->assertEquals([], $this->getDriver()->getPrimaryAuthors()); } /** * Test getItemsTitleSource for a record. * * @return void */ public function <API key>() { $this->assertEquals('', $this->getDriver()->getItemsTitleSource()); } /** * Test linkUrls for a record. * * @return void */ public function testLinkUrls() { $str = "http://fictional.com/sample/url"; $this->assertEquals("<a href='" . $str . "'>" . $str . "</a>", $this->getDriver()->linkUrls($str)); } /** * Test getISSNs. * * @return void */ public function testGetISSNs() { $driver = $this-><API key>(); $this->assertEquals( ['1234-5678', '5678-1234'], $driver->getISSNs() ); } /** * Test getISBNs. * * @return void */ public function testGetISBNs() { $driver = $this-><API key>(); $this->assertEquals( ['0123456789X', 'fakeisbnxxx'], $driver->getISBNs() ); } /** * Get a record driver with fake identifier data. * * @return EDS */ protected function <API key>() { return $this->getDriver( [ 'RecordInfo' => [ 'BibRecord' => [ 'BibRelationships' => [ '<API key>' => [ [ 'BibEntity' => [ 'Identifiers' => [ [ 'Type' => 'issn-electronic', 'Value' => '1234-5678' ], [ 'Type' => 'issn-print', 'Value' => '5678-1234' ], [ 'Type' => 'isbn-electronic', 'Value' => '0123456789X' ], [ 'Type' => 'isbn-print', 'Value' => 'fakeisbnxxx' ], [ 'Type' => 'meaningless-noise', 'Value' => 'should never be seen' ], ] ] ] ] ] ] ] ] ); } /** * Get a record driver with fake data. * * @param array $overrides Raw data for testing * * @return EDS */ protected function getDriver($overrides = []) { $record = new EDS(); $record->setRawData($overrides); return $record; } }
;(function() { /*jshint eqeqeq:false curly:false latedef:false */ "use strict"; function setup($) { $.fn._fadeIn = $.fn.fadeIn; var noOp = $.noop || function() {}; // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle // confusing userAgent strings on Vista) var msie = /MSIE/.test(navigator.userAgent); var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent); var mode = document.documentMode || 0; var setExpr = $.isFunction( document.createElement('div').style.setExpression ); // global $ methods for blocking/unblocking the entire page $.blockUI = function(opts) { install(window, opts); }; $.unblockUI = function(opts) { remove(window, opts); }; $.growlUI = function(title, message, timeout, onClose) { var $m = $('<div class="growlUI"></div>'); if (title) $m.append('<h1>'+title+'</h1>'); if (message) $m.append('<h2>'+message+'</h2>'); if (timeout === undefined) timeout = 3000; // Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications var callBlock = function(opts) { opts = opts || {}; $.blockUI({ message: $m, fadeIn : typeof opts.fadeIn !== 'undefined' ? opts.fadeIn : 700, fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000, timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout, centerY: false, showOverlay: false, onUnblock: onClose, css: $.blockUI.defaults.growlCSS }); }; callBlock(); var nonmousedOpacity = $m.css('opacity'); $m.mouseover(function() { callBlock({ fadeIn: 0, timeout: 30000 }); var displayBlock = $('.blockMsg'); displayBlock.stop(); // cancel fadeout if it has started displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency }).mouseout(function() { $('.blockMsg').fadeOut(1000); }); // End konapun additions }; // plugin method for blocking element content $.fn.block = function(opts) { if ( this[0] === window ) { $.blockUI( opts ); return this; } var fullOpts = $.extend({}, $.blockUI.defaults, opts || {}); this.each(function() { var $el = $(this); if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked')) return; $el.unblock({ fadeOut: 0 }); }); return this.each(function() { if ($.css(this,'position') == 'static') { this.style.position = 'relative'; $(this).data('blockUI.static', true); } this.style.zoom = 1; // force 'hasLayout' in ie install(this, opts); }); }; // plugin method for unblocking element content $.fn.unblock = function(opts) { if ( this[0] === window ) { $.unblockUI( opts ); return this; } return this.each(function() { remove(this, opts); }); }; $.blockUI.version = 2.66; // 2nd generation blocking at no extra cost! // override these in your code to change the default behavior and style $.blockUI.defaults = { // message displayed when blocking (use null for no message) message: '<h1>Please wait...</h1>', title: null, // title string; only used when theme == true draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) theme: false, // set to true to use with jQuery UI themes // styles for the message when blocking; if you wish to disable // these and use an external stylesheet then do this in your code: // $.blockUI.defaults.css = {}; css: { padding: 0, margin: 0, width: '30%', top: '40%', left: '35%', textAlign: 'center', color: '#000', border: '3px solid #aaa', backgroundColor:'#fff', cursor: 'wait' }, // minimal style set used when themes are used themedCSS: { width: '30%', top: '40%', left: '35%' }, // styles for the overlay overlayCSS: { backgroundColor: '#000', opacity: 0.6, cursor: 'wait' }, // style to replace wait cursor before unblocking to correct issue // of lingering wait cursor cursorReset: 'default', // styles applied when using $.growlUI growlCSS: { width: '350px', top: '10px', left: '', right: '10px', border: 'none', padding: '5px', opacity: 0.6, cursor: 'default', color: '#fff', backgroundColor: '#000', '-<API key>':'10px', '-moz-border-radius': '10px', 'border-radius': '10px' }, // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w // (hat tip to Jorge H. N. de Vasconcelos) /*jshint scripturl:true */ iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', // force usage of iframe in non-IE browsers (handy for blocking applets) forceIframe: false, // z-index for the blocking overlay baseZ: 1000, // set these to true to have the message automatically centered centerX: true, // <-- only effects element blocking (page block controlled via css above) centerY: true, // allow body element to be stetched in ie6; this makes blocking look better // on "short" pages. disable if you wish to prevent changes to the body height allowBodyStretch: true, // enable if you want key and mouse events to be disabled for content that is blocked bindEvents: true, // be default blockUI will supress tab navigation from leaving blocking content // (if bindEvents is true) constrainTabKey: true, // fadeIn time in millis; set to 0 to disable fadeIn on block fadeIn: 200, // fadeOut time in millis; set to 0 to disable fadeOut on unblock fadeOut: 400, // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock timeout: 0, // disable if you don't want to show the overlay showOverlay: true, // if true, focus will be placed in the first available input field when // page blocking focusInput: true, // elements that can receive focus focusableElements: ':input:enabled:visible', // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) // no longer needed in 2012 // <API key>: true, // callback method invoked when fadeIn has completed and blocking message is visible onBlock: null, // callback method invoked when unblocking has completed; the callback is // passed the element that has been unblocked (which is the window object for page // blocks) and the options that were passed to the unblock call: // onUnblock(element, options) onUnblock: null, // callback method invoked when the overlay area is clicked. // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used. onOverlayClick: null, // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 <API key>: 4, // class name of the message block blockMsgClass: 'blockMsg', // if it is already blocked, then ignore it (don't unblock and reblock) ignoreIfBlocked: false }; // private data and functions follow... var pageBlock = null; var pageBlockEls = []; function install(el, opts) { var css, themedCSS; var full = (el == window); var msg = (opts && opts.message !== undefined ? opts.message : undefined); opts = $.extend({}, $.blockUI.defaults, opts || {}); if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked')) return; opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); if (opts.onOverlayClick) opts.overlayCSS.cursor = 'pointer'; themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); msg = msg === undefined ? opts.message : msg; // remove the current block (if there is one) if (full && pageBlock) remove(window, {fadeOut:0}); // if an existing element is being used as the blocking content then we capture // its current place in the DOM (and current display style) so we can restore // it when we unblock if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { var node = msg.jquery ? msg[0] : msg; var data = {}; $(el).data('blockUI.history', data); data.el = node; data.parent = node.parentNode; data.display = node.style.display; data.position = node.style.position; if (data.parent) data.parent.removeChild(node); } $(el).data('blockUI.onUnblock', opts.onUnblock); var z = opts.baseZ; // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; // layer1 is the iframe layer which is used to supress bleed through of underlying content // layer2 is the overlay layer which has opacity and a wait cursor (by default) // layer3 is the message content that is displayed while blocking var lyr1, lyr2, lyr3, s; if (msie || opts.forceIframe) lyr1 = $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>'); else lyr1 = $('<div class="blockUI" style="display:none"></div>'); if (opts.theme) lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>'); else lyr2 = $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'); if (opts.theme && full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">'; if ( opts.title ) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (opts.theme) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">'; if ( opts.title ) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>'; } else { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>'; } lyr3 = $(s); // if we have a message, style it if (msg) { if (opts.theme) { lyr3.css(themedCSS); lyr3.addClass('ui-widget-content'); } else lyr3.css(css); } // style the overlay if (!opts.theme /*&& (!opts.<API key>)*/) lyr2.css(opts.overlayCSS); lyr2.css('position', full ? 'fixed' : 'absolute'); // make iframe layer transparent in IE if (msie || opts.forceIframe) lyr1.css('opacity',0.0); //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el); $.each(layers, function() { this.appendTo($par); }); if (opts.theme && opts.draggable && $.fn.draggable) { lyr3.draggable({ handle: '.ui-dialog-titlebar', cancel: 'li' }); } // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0); if (ie6 || expr) { // give body 100% height if (full && opts.allowBodyStretch && $.support.boxModel) $('html,body').css('height','100%'); // fix ie6 issue when blocked element has a border width if ((ie6 || !$.support.boxModel) && !full) { var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth'); var fixT = t ? '(0 - '+t+')' : 0; var fixL = l ? '(0 - '+l+')' : 0; } // simulate fixed position $.each(layers, function(i,o) { var s = o[0].style; s.position = 'absolute'; if (i < 2) { if (full) s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.<API key>+') + "px"'); else s.setExpression('height','this.parentNode.offsetHeight + "px"'); if (full) s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'); else s.setExpression('width','this.parentNode.offsetWidth + "px"'); if (fixL) s.setExpression('left', fixL); if (fixT) s.setExpression('top', fixT); } else if (opts.centerY) { if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); s.marginTop = 0; } else if (!opts.centerY && full) { var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0; var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"'; s.setExpression('top',expression); } }); } // show the message if (msg) { if (opts.theme) lyr3.find('.ui-widget-content').append(msg); else lyr3.append(msg); if (msg.jquery || msg.nodeType) $(msg).show(); } if ((msie || opts.forceIframe) && opts.showOverlay) lyr1.show(); // opacity is zero if (opts.fadeIn) { var cb = opts.onBlock ? opts.onBlock : noOp; var cb1 = (opts.showOverlay && !msg) ? cb : noOp; var cb2 = msg ? cb : noOp; if (opts.showOverlay) lyr2._fadeIn(opts.fadeIn, cb1); if (msg) lyr3._fadeIn(opts.fadeIn, cb2); } else { if (opts.showOverlay) lyr2.show(); if (msg) lyr3.show(); if (opts.onBlock) opts.onBlock(); } // bind key and mouse events bind(1, el, opts); if (full) { pageBlock = lyr3[0]; pageBlockEls = $(opts.focusableElements,pageBlock); if (opts.focusInput) setTimeout(focus, 20); } else center(lyr3[0], opts.centerX, opts.centerY); if (opts.timeout) { // auto-unblock var to = setTimeout(function() { if (full) $.unblockUI(opts); else $(el).unblock(opts); }, opts.timeout); $(el).data('blockUI.timeout', to); } } // remove the block function remove(el, opts) { var count; var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if ( opts.cursorReset ) { if ( els.length > 1 ) els[1].style.cursor = opts.cursorReset; if ( els.length > 2 ) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { count = els.length; els.stop().fadeOut(opts.fadeOut, function() { if ( --count === 0) reset(els,data,opts,el); }); } else reset(els, data, opts, el); } // move blocking element back into the DOM where it started function reset(els,data,opts,el) { var $el = $(el); if ( $el.data('blockUI.isBlocked') ) return; els.each(function(i,o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; if (data.parent) data.parent.appendChild(data.el); $el.removeData('blockUI.history'); } if ($el.data('blockUI.static')) { $el.css('position', 'static'); // } if (typeof opts.onUnblock == 'function') opts.onUnblock(el,opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w-1).width(w); body[0].style.width = cssW; } // bind/unbind the handler function bind(b, el, opts) { var full = el == window, $el = $(el); // don't bother unbinding if there is nothing to unbind if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) return; $el.data('blockUI.isBlocked', b); // don't bind events when overlay is not in use or if bindEvents is false if (!full || !opts.bindEvents || (b && !opts.showOverlay)) return; // bind anchors and inputs for mouse and key events var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove'; if (b) $(document).bind(events, opts, handler); else $(document).unbind(events, handler); // former impl... // var $e = $('a,:input'); // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); } // event handler to suppress keyboard/mouse events when blocking function handler(e) { // allow tab navigation (conditionally) if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) { if (pageBlock && e.data.constrainTabKey) { var els = pageBlockEls; var fwd = !e.shiftKey && e.target === els[els.length-1]; var back = e.shiftKey && e.target === els[0]; if (fwd || back) { setTimeout(function(){focus(back);},10); return false; } } } var opts = e.data; var target = $(e.target); if (target.hasClass('blockOverlay') && opts.onOverlayClick) opts.onOverlayClick(e); // allow events within the message content if (target.parents('div.' + opts.blockMsgClass).length > 0) return true; // allow events for content that is not being blocked return target.parents().children().filter('div.blockUI').length === 0; } function focus(back) { if (!pageBlockEls) return; var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0]; if (e) e.focus(); } function center(el, x, y) { var p = el.parentNode, s = el.style; var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth'); var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth'); if (x) s.left = l > 0 ? (l+'px') : '0'; if (y) s.top = t > 0 ? (t+'px') : '0'; } function sz(el, p) { return parseInt($.css(el,p),10)||0; } } /*global define:true */ if (typeof define === 'function' && define.amd && define.amd.jQuery) { define(['jquery'], setup); } else { setup(jQuery); } })();
// { dg-do compile { target c++14 } } // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // with this library; see the file COPYING3. If not see #include <experimental/propagate_const> using std::experimental::propagate_const; propagate_const<void*> test1; // { dg-error "requires a class or a pointer to an object type" "" { target *-*-* } 0 } // { dg-prune-output "forming pointer to reference type" } // { dg-prune-output "not a pointer-to-object type" }
#include <cmath> #include "header.h" #include "../biophysics/SpikeGen.h" #include "HSolveStruct.h" void ChannelStruct::setPowers( double Xpower, double Ypower, double Zpower ) { Xpower_ = Xpower; takeXpower_ = selectPower( Xpower ); Ypower_ = Ypower; takeYpower_ = selectPower( Ypower ); Zpower_ = Zpower; takeZpower_ = selectPower( Zpower ); } double ChannelStruct::powerN( double x, double p ) { if ( x > 0.0 ) return exp( p * log( x ) ); return 0.0; } PFDD ChannelStruct::selectPower( double power ) { if ( power == 0.0 ) return powerN; else if ( power == 1.0 ) return power1; else if ( power == 2.0 ) return power2; else if ( power == 3.0 ) return power3; else if ( power == 4.0 ) return power4; else return powerN; } void ChannelStruct::process( double*& state, CurrentStruct& current ) { double fraction = modulation_; if( Xpower_ > 0.0 ) fraction *= takeXpower_( *( state++ ), Xpower_ ); if( Ypower_ > 0.0 ) fraction *= takeYpower_( *( state++ ), Ypower_ ); if( Zpower_ > 0.0 ) fraction *= takeZpower_( *( state++ ), Zpower_ ); current.Gk = Gbar_ * fraction; } void SpikeGenStruct::reinit( ProcPtr info ) { SpikeGen* spike = reinterpret_cast< SpikeGen* >( e_.data() ); spike->reinit( e_, info ); } void SpikeGenStruct::send( ProcPtr info ) { SpikeGen* spike = reinterpret_cast< SpikeGen* >( e_.data() ); spike->handleVm( *Vm_ ); spike->process( e_, info ); } CaConcStruct::CaConcStruct() : c_( 0.0 ), CaBasal_( 0.0 ), factor1_( 0.0 ), factor2_( 0.0 ), ceiling_( 0.0 ), floor_( 0.0 ) { ; } CaConcStruct::CaConcStruct( double Ca, double CaBasal, double tau, double B, double ceiling, double floor, double dt ) { setCa( Ca ); setCaBasal( CaBasal ); setTauB( tau, B, dt ); ceiling_ = ceiling; floor_ = floor; } void CaConcStruct::setCa( double Ca ) { c_ = Ca - CaBasal_; } void CaConcStruct::setCaBasal( double CaBasal ) { /* * Also updating 'c_' here, so that only 'CaBasal' changes, and 'Ca' * remains the same. This is good because otherwise one has to bother about * the order in which 'setCa()' and 'setCaBasal()' are called. * * 'Ca' is: * Ca = CaBasal_ + c_ * * if: * Ca_new = Ca_old * * then: * CaBasal_new + c_new = CaBasal_old + c_old * * so: * c_new = c_old + CaBasal_old - CaBasal_new */ c_ += CaBasal_ - CaBasal; CaBasal_ = CaBasal; } void CaConcStruct::setTauB( double tau, double B, double dt ) { factor1_ = 4.0 / ( 2.0 + dt / tau ) - 1.0; factor2_ = 2.0 * B * dt / ( 2.0 + dt / tau ); } double CaConcStruct::process( double activation ) { c_ = factor1_ * c_ + factor2_ * activation; double ca = CaBasal_ + c_; if ( ceiling_ > 0 && ca > ceiling_ ) { ca = ceiling_; setCa( ca ); } if ( ca < floor_ ) { ca = floor_; setCa( ca ); } return ca; }
/* Converts between INT_CST and GMP integer representations. */ tree <API key> (mpz_t, int); void <API key> (mpz_t, tree); /* Converts between REAL_CST and MPFR floating-point representations. */ tree <API key> (mpfr_t, int, int); void <API key> (mpfr_ptr, tree); /* Build a tree for a constant. Must be an EXPR_CONSTANT gfc_expr. For CHARACTER literal constants, the caller still has to set the string length as a separate operation. */ tree <API key> (gfc_expr *); /* Like <API key>, but works on simplified expression structures. Also sets the length of CHARACTER strings in the gfc_se. */ void gfc_conv_constant (gfc_se *, gfc_expr *); tree <API key> (int, const char *); tree <API key> (int, int, const gfc_char_t *); tree <API key> (const char *); tree <API key> (const char *); /* Translate a string constant for a static initializer. */ tree <API key> (tree, gfc_expr *); /* Create a tree node for the string length if it is constant. */ void <API key> (gfc_charlen *); /* Initialize the nodes for constants. */ void gfc_init_constants (void); /* Build a constant with given type from an int_cst. */ tree gfc_build_const (tree, tree); /* Integer constants 0..GFC_MAX_DIMENSIONS. */ extern GTY(()) tree gfc_rank_cst[GFC_MAX_DIMENSIONS + 1]; #define gfc_index_zero_node gfc_rank_cst[0] #define gfc_index_one_node gfc_rank_cst[1]
.quicktabs_main.<API key> { border: 0; border-top: none; clear: both; padding: 10px 0; } ul.quicktabs-tabs.<API key> { border-bottom: 1px solid #aaa; font-weight: bold; margin: 0; padding: 0 5px 0 0; } ul.quicktabs-tabs.<API key> a { color: #666; font-size: .9em; text-decoration: none; text-transform: uppercase; } ul.quicktabs-tabs.<API key> a:hover { color: #555 !important; } ul.quicktabs-tabs.<API key> li { display: inline; margin: 0 5px 0 0; padding: 2px 0; position: relative; } ul.quicktabs-tabs.<API key> li.last { margin-right: 0; } ul.quicktabs-tabs.<API key> li:hover { border-bottom: none; } ul.quicktabs-tabs.<API key> li.active { border-bottom: 1px solid #f3686d; } ul.quicktabs-tabs.<API key> li.active a { color: #f3686d; }
<?php /** * @package PayPal */ /** * Make sure our parent class is defined. */ require_once 'PayPal/Type/AbstractRequestType.php'; /** * <API key> * * @package PayPal */ class <API key> extends AbstractRequestType { /** * A unique token returned by the EnterBoarding API call that identifies this * boarding session. */ var $Token; function <API key>() { parent::AbstractRequestType(); $this->_namespace = 'urn:ebay:api:PayPalAPI'; $this->_elements = array_merge($this->_elements, array ( 'Token' => array ( 'required' => true, 'type' => '<API key>', 'namespace' => 'urn:ebay:api:PayPalAPI', ), )); } function getToken() { return $this->Token; } function setToken($Token, $charset = 'iso-8859-1') { $this->Token = $Token; $this->_elements['Token']['charset'] = $charset; } }
#include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "g10lib.h" #include "bithelp.h" #include "bufhelp.h" #include "cipher.h" #include "hash-common.h" #include "gost.h" #define max(a, b) (((a) > (b)) ? (a) : (b)) typedef struct { gcry_md_block_ctx_t bctx; GOST28147_context hd; union { u32 h[8]; byte result[32]; }; u32 sigma[8]; u32 len; int cryptopro; } GOSTR3411_CONTEXT; static unsigned int transform (void *c, const unsigned char *data, size_t nblks); static void gost3411_init (void *context, unsigned int flags) { GOSTR3411_CONTEXT *hd = context; (void)flags; memset (&hd->hd, 0, sizeof(hd->hd)); memset (hd->h, 0, 32); memset (hd->sigma, 0, 32); hd->bctx.nblocks = 0; hd->bctx.count = 0; hd->bctx.blocksize = 32; hd->bctx.bwrite = transform; hd->cryptopro = 0; } static void gost3411_cp_init (void *context, unsigned int flags) { GOSTR3411_CONTEXT *hd = context; gost3411_init (context, flags); hd->cryptopro = 1; } static void do_p (u32 *p, u32 *u, u32 *v) { int k; u32 t[8]; for (k = 0; k < 8; k++) t[k] = u[k] ^ v[k]; for (k = 0; k < 4; k++) { p[k+0] = ((t[0] >> (8*k)) & 0xff) << 0 | ((t[2] >> (8*k)) & 0xff) << 8 | ((t[4] >> (8*k)) & 0xff) << 16 | ((t[6] >> (8*k)) & 0xff) << 24; p[k+4] = ((t[1] >> (8*k)) & 0xff) << 0 | ((t[3] >> (8*k)) & 0xff) << 8 | ((t[5] >> (8*k)) & 0xff) << 16 | ((t[7] >> (8*k)) & 0xff) << 24; } } static void do_a (u32 *u) { u32 t[2]; int i; memcpy(t, u, 2*4); for (i = 0; i < 6; i++) u[i] = u[i+2]; u[6] = u[0] ^ t[0]; u[7] = u[1] ^ t[1]; } /* apply do_a twice: 1 2 3 4 -> 3 4 1^2 2^3 */ static void do_a2 (u32 *u) { u32 t[4]; int i; memcpy (t, u, 16); memcpy (u, u + 4, 16); for (i = 0; i < 2; i++) { u[4+i] = t[i] ^ t[i + 2]; u[6+i] = u[i] ^ t[i + 2]; } } static void do_apply_c2 (u32 *u) { u[ 0] ^= 0xff00ff00; u[ 1] ^= 0xff00ff00; u[ 2] ^= 0x00ff00ff; u[ 3] ^= 0x00ff00ff; u[ 4] ^= 0x00ffff00; u[ 5] ^= 0xff0000ff; u[ 6] ^= 0x000000ff; u[ 7] ^= 0xff00ffff; } #define do_chi_step12(e) \ e[6] ^= ((e[6] >> 16) ^ e[7] ^ (e[7] >> 16) ^ e[4] ^ (e[5] >>16)) & 0xffff; #define do_chi_step13(e) \ e[6] ^= ((e[7] ^ (e[7] >> 16) ^ e[0] ^ (e[4] >> 16) ^ e[6]) & 0xffff) << 16; #define do_chi_doublestep(e, i) \ e[i] ^= (e[i] >> 16) ^ (e[(i+1)%8] << 16) ^ e[(i+1)%8] ^ (e[(i+1)%8] >> 16) ^ (e[(i+2)%8] << 16) ^ e[(i+6)%8] ^ (e[(i+7)%8] >> 16); \ e[i] ^= (e[i] << 16); static void do_chi_submix12 (u32 *e, u32 *x) { e[6] ^= x[0]; e[7] ^= x[1]; e[0] ^= x[2]; e[1] ^= x[3]; e[2] ^= x[4]; e[3] ^= x[5]; e[4] ^= x[6]; e[5] ^= x[7]; } static void do_chi_submix13 (u32 *e, u32 *x) { e[6] ^= (x[0] << 16) | (x[7] >> 16); e[7] ^= (x[1] << 16) | (x[0] >> 16); e[0] ^= (x[2] << 16) | (x[1] >> 16); e[1] ^= (x[3] << 16) | (x[2] >> 16); e[2] ^= (x[4] << 16) | (x[3] >> 16); e[3] ^= (x[5] << 16) | (x[4] >> 16); e[4] ^= (x[6] << 16) | (x[5] >> 16); e[5] ^= (x[7] << 16) | (x[6] >> 16); } static void do_add (u32 *s, u32 *a) { u32 carry = 0; int i; for (i = 0; i < 8; i++) { u32 op = carry + a[i]; s[i] += op; carry = (a[i] > op) || (op > s[i]); } } static unsigned int do_hash_step (GOSTR3411_CONTEXT *hd, u32 *h, u32 *m) { u32 u[8], v[8]; u32 s[8]; u32 k[8]; unsigned int burn; int i; memcpy (u, h, 32); memcpy (v, m, 32); for (i = 0; i < 4; i++) { do_p (k, u, v); burn = _gcry_gost_enc_data (&hd->hd, k, &s[2*i], &s[2*i+1], h[2*i], h[2*i+1], hd->cryptopro); do_a (u); if (i == 1) do_apply_c2 (u); do_a2 (v); } for (i = 0; i < 5; i++) { do_chi_doublestep (s, 0); do_chi_doublestep (s, 1); do_chi_doublestep (s, 2); do_chi_doublestep (s, 3); do_chi_doublestep (s, 4); /* That is in total 12 + 1 + 61 = 74 = 16 * 4 + 10 rounds */ if (i == 4) break; do_chi_doublestep (s, 5); if (i == 0) do_chi_submix12(s, m); do_chi_step12 (s); if (i == 0) do_chi_submix13(s, h); do_chi_step13 (s); do_chi_doublestep (s, 7); } memcpy (h, s+5, 12); memcpy (h+3, s, 20); return /* burn_stack */ 4 * sizeof(void*) /* func call (ret addr + args) */ + 4 * 32 + 2 * sizeof(int) /* stack */ + max(burn /* _gcry_gost_enc_one */, sizeof(void*) * 2 /* do_a2 call */ + 16 + sizeof(int) /* do_a2 stack */ ); } static unsigned int transform_blk (void *ctx, const unsigned char *data) { GOSTR3411_CONTEXT *hd = ctx; u32 m[8]; unsigned int burn; int i; for (i = 0; i < 8; i++) m[i] = buf_get_le32(data + i*4); burn = do_hash_step (hd, hd->h, m); do_add (hd->sigma, m); return /* burn_stack */ burn + 3 * sizeof(void*) + 32 + 2 * sizeof(void*); } static unsigned int transform ( void *c, const unsigned char *data, size_t nblks ) { unsigned int burn; do { burn = transform_blk (c, data); data += 32; } while (--nblks); return burn; } /* The routine finally terminates the computation and returns the digest. The handle is prepared for a new cycle, but adding bytes to the handle will the destroy the returned buffer. Returns: 32 bytes with the message the digest. */ static void gost3411_final (void *context) { GOSTR3411_CONTEXT *hd = context; size_t padlen = 0; u32 l[8]; int i; MD_NBLOCKS_TYPE nblocks; if (hd->bctx.count > 0) { padlen = 32 - hd->bctx.count; memset (hd->bctx.buf + hd->bctx.count, 0, padlen); hd->bctx.count += padlen; <API key> (hd, NULL, 0); /* flush */; } if (hd->bctx.count != 0) return; /* Something went wrong */ memset (l, 0, 32); nblocks = hd->bctx.nblocks; if (padlen) { nblocks l[0] = 256 - padlen * 8; } l[0] |= nblocks << 8; nblocks >>= 24; for (i = 1; i < 8 && nblocks != 0; i++) { l[i] = nblocks; nblocks >>= 24; } do_hash_step (hd, hd->h, l); do_hash_step (hd, hd->h, hd->sigma); for (i = 0; i < 8; i++) hd->h[i] = le_bswap32(hd->h[i]); } static byte * gost3411_read (void *context) { GOSTR3411_CONTEXT *hd = context; return hd->result; } static unsigned char asn[6] = /* Object ID is 1.2.643.2.2.3 */ { 0x2a, 0x85, 0x03, 0x02, 0x02, 0x03 }; static gcry_md_oid_spec_t oid_spec_gostr3411[] = { /* iso.member-body.ru.rans.cryptopro.3 (<API key>) */ { "1.2.643.2.2.3" }, /* iso.member-body.ru.rans.cryptopro.9 (gostR3411-94) */ { "1.2.643.2.2.9" }, {NULL}, }; gcry_md_spec_t <API key> = { <API key>, {0, 0}, "GOSTR3411_94", NULL, 0, NULL, 32, gost3411_init, <API key>, gost3411_final, gost3411_read, sizeof (GOSTR3411_CONTEXT) }; gcry_md_spec_t <API key> = { <API key>, {0, 0}, "GOSTR3411_CP", asn, DIM (asn), oid_spec_gostr3411, 32, gost3411_cp_init, <API key>, gost3411_final, gost3411_read, sizeof (GOSTR3411_CONTEXT) };
<?php namespace Magento\Checkout\Controller; use Magento\Catalog\Controller\Product\View\ViewInterface; use Magento\Checkout\Model\Cart as CustomerCart; /** * Shopping cart controller */ abstract class Cart extends \Magento\Framework\App\Action\Action implements ViewInterface { /** * @var \Magento\Framework\App\Config\<API key> */ protected $_scopeConfig; /** * @var \Magento\Checkout\Model\Session */ protected $_checkoutSession; /** * @var \Magento\Store\Model\<API key> */ protected $_storeManager; /** * @var \Magento\Framework\Data\Form\FormKey\Validator */ protected $_formKeyValidator; /** * @var \Magento\Checkout\Model\Cart */ protected $cart; /** * @param \Magento\Framework\App\Action\Context $context * @param \Magento\Framework\App\Config\<API key> $scopeConfig * @param \Magento\Checkout\Model\Session $checkoutSession * @param \Magento\Store\Model\<API key> $storeManager * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator * @param CustomerCart $cart * @codeCoverageIgnore */ public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Framework\App\Config\<API key> $scopeConfig, \Magento\Checkout\Model\Session $checkoutSession, \Magento\Store\Model\<API key> $storeManager, \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator, CustomerCart $cart ) { $this->_formKeyValidator = $formKeyValidator; $this->_scopeConfig = $scopeConfig; $this->_checkoutSession = $checkoutSession; $this->_storeManager = $storeManager; $this->cart = $cart; parent::__construct($context); } /** * Set back redirect url to response * * @param null|string $backUrl * * @return \Magento\Framework\Controller\Result\Redirect */ protected function _goBack($backUrl = null) { $resultRedirect = $this-><API key>->create(); if ($backUrl || $backUrl = $this->getBackUrl($this->_redirect->getRefererUrl())) { $resultRedirect->setUrl($backUrl); } return $resultRedirect; } /** * Check if URL corresponds store * * @param string $url * @return bool */ protected function _isInternalUrl($url) { if (strpos($url, 'http') === false) { return false; } /** * Url must start from base secure or base unsecure url */ /** @var $store \Magento\Store\Model\Store */ $store = $this->_storeManager->getStore(); $unsecure = strpos($url, $store->getBaseUrl()) === 0; $secure = strpos($url, $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK, true)) === 0; return $unsecure || $secure; } /** * Get resolved back url * * @param null $defaultUrl * * @return mixed|null|string */ protected function getBackUrl($defaultUrl = null) { $returnUrl = $this->getRequest()->getParam('return_url'); if ($returnUrl && $this->_isInternalUrl($returnUrl)) { $this->messageManager->getMessages()->clear(); return $returnUrl; } $<API key> = $this->_scopeConfig->getValue( 'checkout/cart/redirect_to_cart', \Magento\Store\Model\ScopeInterface::SCOPE_STORE ); if ($<API key> || $this->getRequest()->getParam('in_cart')) { if ($this->getRequest()->getActionName() == 'add' && !$this->getRequest()->getParam('in_cart')) { $this->_checkoutSession-><API key>($this->_redirect->getRefererUrl()); } return $this->_url->getUrl('checkout/cart'); } return $defaultUrl; } }
<?php get_header(); ?> <div id="primary" class="content-area"> <div class="row"> <div class="large-12 columns"> <div id="content" class="site-content attachement" role="main"> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <div class="row"> <div class="large-12 columns"> <h1 class="entry-title"><?php the_title(); ?></h1> </div><!-- .large-12 .columns --> </div><!-- .row --> <div class="row"> <div class="large-8 large-centered columns"> <div class="<API key>"> <?php $metadata = <API key>(); printf( __( 'Published <span class="entry-date"><time class="entry-date" datetime="%1$s">%2$s</time></span>. Size: <i class="fa fa-picture-o"></i> <a href="%3$s" title="Link to full-size image">%4$s &times; %5$s</a> in <i class="fa fa-folder-open"></i> <a href="%6$s" title="Return to %7$s" rel="gallery">%7$s</a>', 'mr_tailor' ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ), <API key>(), $metadata['width'], $metadata['height'], get_permalink( $post->post_parent ), get_the_title( $post->post_parent ) ); ?> <?php //edit_post_link( __( 'Edit', 'mr_tailor' ), '<span class="sep"> | </span> <span class="edit-link">', '</span>' ); ?> </div><!-- .entry-meta --> </div><!-- .large-8 .large-centered .columns --> </div><!-- .row --> <div class="row"> <div class="large-6 small-6 columns"> <div class="previous-image"><?php previous_image_link( false, __( '&larr; Previous', 'mr_tailor' ) ); ?></div> </div><!-- .large-2 .columns --> <div class="large-6 small-6 columns"> <div class="next-image"><?php next_image_link( false, __( 'Next &rarr;', 'mr_tailor' ) ); ?></div> </div><!-- .large-2 .columns --> </div><!-- .row --> </header><!-- .entry-header --> <div class="entry-content"> <?php /** * Grab the IDs of all the image attachments in a gallery so we can get the URL of the next adjacent image in a gallery, * or the first image (if we're looking at the last image in a gallery), or, in a gallery of one, just the link to that image file */ $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) ); foreach ( $attachments as $k => $attachment ) { if ( $attachment->ID == $post->ID ) break; } $k++; // If there is more than 1 attachment in a gallery if ( count( $attachments ) > 1 ) { if ( isset( $attachments[ $k ] ) ) // get the URL of the next image attachment $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID ); else // or get the URL of the first image attachment $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID ); } else { // or, if there's only 1 image, get the URL of the image $next_attachment_url = <API key>(); } ?> <a href="<?php echo $next_attachment_url; ?>" title="<?php echo esc_attr( get_the_title() ); ?>" rel="attachment"><?php echo <API key>( $post->ID, "full" ); ?></a> </div><!-- .entry-content --> </article><!-- #post-<?php the_ID(); ?> --> <?php endwhile; // end of the loop. ?> </div><!-- #content --> </div><!-- .large-12 .columns --> </div><!-- .row --> </div><!-- #primary --> <?php get_footer(); ?>
#ifndef __REMUX_H #define __REMUX_H #include "channels.h" #include "tools.h" enum ePesHeader { phNeedMoreData = -1, phInvalid = 0, phMPEG1 = 1, phMPEG2 = 2 }; ePesHeader AnalyzePesHeader(const uchar *Data, int Count, int &PesPayloadOffset, bool *ContinuationHeader = NULL); class cRemux { public: static void SetBrokenLink(uchar *Data, int Length); }; // Some TS handling tools. // The following functions all take a pointer to one complete TS packet. #define TS_SYNC_BYTE 0x47 #define TS_SIZE 188 #define TS_ERROR 0x80 #define TS_PAYLOAD_START 0x40 #define <API key> 0x20 #define TS_PID_MASK_HI 0x1F #define <API key> 0xC0 #define <API key> 0x20 #define TS_PAYLOAD_EXISTS 0x10 #define TS_CONT_CNT_MASK 0x0F #define TS_ADAPT_DISCONT 0x80 #define TS_ADAPT_RANDOM_ACC 0x40 // would be perfect for detecting independent frames, but unfortunately not used by all broadcasters #define TS_ADAPT_ELEM_PRIO 0x20 #define TS_ADAPT_PCR 0x10 #define TS_ADAPT_OPCR 0x08 #define TS_ADAPT_SPLICING 0x04 #define TS_ADAPT_TP_PRIVATE 0x02 #define TS_ADAPT_EXTENSION 0x01 #define PATPID 0x0000 // PAT PID (constant 0) #define CATPID 0x0001 // CAT PID (constant 1) #define MAXPID 0x2000 // for arrays that use a PID as the index #define PTSTICKS 90000 // number of PTS ticks per second #define PCRFACTOR 300 // conversion from 27MHz PCR extension to 90kHz PCR base #define MAX33BIT <API key> // max. possible value with 33 bit #define MAX27MHZ ((MAX33BIT + 1) * PCRFACTOR - 1) // max. possible PCR value inline bool TsHasPayload(const uchar *p) { return p[3] & TS_PAYLOAD_EXISTS; } inline bool <API key>(const uchar *p) { return p[3] & <API key>; } inline bool TsPayloadStart(const uchar *p) { return p[1] & TS_PAYLOAD_START; } inline bool TsError(const uchar *p) { return p[1] & TS_ERROR; } inline int TsPid(const uchar *p) { return (p[1] & TS_PID_MASK_HI) * 256 + p[2]; } inline bool TsIsScrambled(const uchar *p) { return p[3] & <API key>; } inline uchar <API key>(const uchar *p) { return p[3] & TS_CONT_CNT_MASK; } inline void <API key>(uchar *p, uchar Counter) { p[3] = (p[3] & ~TS_CONT_CNT_MASK) | (Counter & TS_CONT_CNT_MASK); } inline int TsPayloadOffset(const uchar *p) { int o = <API key>(p) ? p[4] + 5 : 4; return o <= TS_SIZE ? o : TS_SIZE; } inline int TsGetPayload(const uchar **p) { if (TsHasPayload(*p)) { int o = TsPayloadOffset(*p); *p += o; return TS_SIZE - o; } return 0; } inline int TsContinuityCounter(const uchar *p) { return p[3] & TS_CONT_CNT_MASK; } inline int64_t TsGetPcr(const uchar *p) { if (<API key>(p)) { if (p[4] >= 7 && (p[5] & TS_ADAPT_PCR)) { return ((((int64_t)p[ 6]) << 25) | (((int64_t)p[ 7]) << 17) | (((int64_t)p[ 8]) << 9) | (((int64_t)p[ 9]) << 1) | (((int64_t)p[10]) >> 7)) * PCRFACTOR + (((((int)p[10]) & 0x01) << 8) | ( ((int)p[11]))); } } return -1; } void TsHidePayload(uchar *p); void TsSetPcr(uchar *p, int64_t Pcr); // The following functions all take a pointer to a sequence of complete TS packets. int64_t TsGetPts(const uchar *p, int l); int64_t TsGetDts(const uchar *p, int l); void TsSetPts(uchar *p, int l, int64_t Pts); void TsSetDts(uchar *p, int l, int64_t Dts); // Some PES handling tools: // The following functions that take a pointer to PES data all assume that // there is enough data so that PesLongEnough() returns true. inline bool PesLongEnough(int Length) { return Length >= 6; } inline bool PesHasLength(const uchar *p) { return p[4] | p[5]; } inline int PesLength(const uchar *p) { return 6 + p[4] * 256 + p[5]; } inline int PesPayloadOffset(const uchar *p) { return 9 + p[8]; } inline bool PesHasPts(const uchar *p) { return (p[7] & 0x80) && p[8] >= 5; } inline bool PesHasDts(const uchar *p) { return (p[7] & 0x40) && p[8] >= 10; } inline int64_t PesGetPts(const uchar *p) { return ((((int64_t)p[ 9]) & 0x0E) << 29) | (( (int64_t)p[10]) << 22) | ((((int64_t)p[11]) & 0xFE) << 14) | (( (int64_t)p[12]) << 7) | ((((int64_t)p[13]) & 0xFE) >> 1); } inline int64_t PesGetDts(const uchar *p) { return ((((int64_t)p[14]) & 0x0E) << 29) | (( (int64_t)p[15]) << 22) | ((((int64_t)p[16]) & 0xFE) << 14) | (( (int64_t)p[17]) << 7) | ((((int64_t)p[18]) & 0xFE) >> 1); } void PesSetPts(uchar *p, int64_t Pts); void PesSetDts(uchar *p, int64_t Dts); // PTS handling: inline int64_t PtsAdd(int64_t Pts1, int64_t Pts2) { return (Pts1 + Pts2) & MAX33BIT; } < Adds the given PTS values, taking into account the 33bit wrap around. int64_t PtsDiff(int64_t Pts1, int64_t Pts2); < Returns the difference between two PTS values. The result of Pts2 - Pts1 < is the actual number of 90kHz time ticks that pass from Pts1 to Pts2, < properly taking into account the 33bit wrap around. If Pts2 is "before" < Pts1, the result is negative. // A transprent TS payload handler: class cTsPayload { private: uchar *data; int length; int pid; int index; // points to the next byte to process int numPacketsPid; // the number of TS packets with the given PID (for statistical purposes) int numPacketsOther; // the number of TS packets with other PIDs (for statistical purposes) uchar SetEof(void); protected: void Reset(void); public: cTsPayload(void); cTsPayload(uchar *Data, int Length, int Pid = -1); < Creates a new TS payload handler and calls Setup() with the given Data. void Setup(uchar *Data, int Length, int Pid = -1); < Sets up this TS payload handler with the given Data, which points to a < sequence of Length bytes of complete TS packets. Any incomplete TS < packet at the end will be ignored. < If Pid is given, only TS packets with data for that PID will be processed. < Otherwise the PID of the first TS packet defines which payload will be < delivered. < Any intermediate TS packets with different PIDs will be skipped. bool AtTsStart(void) { return index < length && (index % TS_SIZE) == 0; } < Returns true if this payload handler is currently pointing to first byte < of a TS packet. bool AtPayloadStart(void) { return AtTsStart() && TsPayloadStart(data + index); } < Returns true if this payload handler is currently pointing to the first byte < of a TS packet that starts a new payload. int Available(void) { return length - index; } < Returns the number of raw bytes (including any TS headers) still available < in the TS payload handler. int Used(void) { return (index + TS_SIZE - 1) / TS_SIZE * TS_SIZE; } < Returns the number of raw bytes that have already been used (e.g. by calling < GetByte()). Any TS packet of which at least a single byte has been delivered < is counted with its full size. bool Eof(void) const { return index >= length; } < Returns true if all available bytes of the TS payload have been processed. void Statistics(void) const; < May be called after a new frame has been detected, and will log a warning < if the number of TS packets required to determine the frame type exceeded < some safety limits. uchar GetByte(void); < Gets the next byte of the TS payload, skipping any intermediate TS header data. bool SkipBytes(int Bytes); < Skips the given number of bytes in the payload and returns true if there < is still data left to read. bool SkipPesHeader(void); < Skips all bytes belonging to the PES header of the payload. int GetLastIndex(void); < Returns the index into the TS data of the payload byte that has most recently < been read. If no byte has been read yet, -1 will be returned. void SetByte(uchar Byte, int Index); < Sets the TS data byte at the given Index to the value Byte. < Index should be one that has been retrieved by a previous call to GetIndex(), < otherwise the behaviour is undefined. The current read index will not be < altered by a call to this function. bool Find(uint32_t Code); < Searches for the four byte sequence given in Code and returns true if it < was found within the payload data. The next call to GetByte() will return the < value immediately following the Code. If the code was not found, the read < index will remain the same as before this call, so that several calls to < Find() can be performed starting at the same index.. < The special code 0xFFFFFFFF can not be searched, because this value is used < to initialize the scanner. }; // PAT/PMT Generator: #define MAX_SECTION_SIZE 4096 // maximum size of an SI section #define MAX_PMT_TS (MAX_SECTION_SIZE / TS_SIZE + 1) class cPatPmtGenerator { private: uchar pat[TS_SIZE]; // the PAT always fits into a single TS packet uchar pmt[MAX_PMT_TS][TS_SIZE]; // the PMT may well extend over several TS packets int numPmtPackets; int patCounter; int pmtCounter; int patVersion; int pmtVersion; int pmtPid; uchar *esInfoLength; void IncCounter(int &Counter, uchar *TsPacket); void IncVersion(int &Version); void IncEsInfoLength(int Length); protected: int MakeStream(uchar *Target, uchar Type, int Pid); int MakeAC3Descriptor(uchar *Target, uchar Type); int <API key>(uchar *Target, const char *Language, uchar SubtitlingType, uint16_t CompositionPageId, uint16_t AncillaryPageId); int <API key>(uchar *Target, const char *Language); int MakeCRC(uchar *Target, const uchar *Data, int Length); void GeneratePmtPid(const cChannel *Channel); < Generates a PMT pid that doesn't collide with any of the actual < pids of the Channel. void GeneratePat(void); < Generates a PAT section for later use with GetPat(). void GeneratePmt(const cChannel *Channel); < Generates a PMT section for the given Channel, for later use < with GetPmt(). public: cPatPmtGenerator(const cChannel *Channel = NULL); void SetVersions(int PatVersion, int PmtVersion); < Sets the version numbers for the generated PAT and PMT, in case < this generator is used to, e.g., continue a previously interrupted < recording (in which case the numbers given should be derived from < the PAT/PMT versions last used in the existing recording, incremented < by 1. If the given numbers exceed the allowed range of 0..31, the < higher bits will automatically be cleared. < SetVersions() needs to be called before SetChannel() in order to < have an effect from the very start. void SetChannel(const cChannel *Channel); < Sets the Channel for which the PAT/PMT shall be generated. uchar *GetPat(void); < Returns a pointer to the PAT section, which consists of exactly < one TS packet. uchar *GetPmt(int &Index); < Returns a pointer to the Index'th TS packet of the PMT section. < Index must be initialized to 0 and will be incremented by each < call to GetPmt(). Returns NULL is all packets of the PMT section < have been fetched.. }; // PAT/PMT Parser: #define MAX_PMT_PIDS 32 class cPatPmtParser { private: uchar pmt[MAX_SECTION_SIZE]; int pmtSize; int patVersion; int pmtVersion; int pmtPids[MAX_PMT_PIDS + 1]; // list is zero-terminated int vpid; int ppid; int vtype; int apids[MAXAPIDS + 1]; // list is zero-terminated int atypes[MAXAPIDS + 1]; // list is zero-terminated char alangs[MAXAPIDS][MAXLANGCODE2]; int dpids[MAXDPIDS + 1]; // list is zero-terminated int dtypes[MAXDPIDS + 1]; // list is zero-terminated char dlangs[MAXDPIDS][MAXLANGCODE2]; int spids[MAXSPIDS + 1]; // list is zero-terminated char slangs[MAXSPIDS][MAXLANGCODE2]; uchar subtitlingTypes[MAXSPIDS]; uint16_t compositionPageIds[MAXSPIDS]; uint16_t ancillaryPageIds[MAXSPIDS]; bool updatePrimaryDevice; protected: int SectionLength(const uchar *Data, int Length) { return (Length >= 3) ? ((int(Data[1]) & 0x0F) << 8)| Data[2] : 0; } public: cPatPmtParser(bool UpdatePrimaryDevice = false); void Reset(void); < Resets the parser. This function must be called whenever a new < stream is parsed. void ParsePat(const uchar *Data, int Length); < Parses the PAT data from the single TS packet in Data. < Length is always TS_SIZE. void ParsePmt(const uchar *Data, int Length); < Parses the PMT data from the single TS packet in Data. < Length is always TS_SIZE. < The PMT may consist of several TS packets, which < are delivered to the parser through several subsequent calls to < ParsePmt(). The whole PMT data will be processed once the last packet < has been received. bool ParsePatPmt(const uchar *Data, int Length); < Parses the given Data (which may consist of several TS packets, typically < an entire frame) and extracts the PAT and PMT. < Returns true if a valid PAT/PMT has been detected. bool GetVersions(int &PatVersion, int &PmtVersion) const; < Returns true if a valid PAT/PMT has been parsed and stores < the current version numbers in the given variables. bool IsPmtPid(int Pid) const { for (int i = 0; pmtPids[i]; i++) if (pmtPids[i] == Pid) return true; return false; } < Returns true if Pid the one of the PMT pids as defined by the current PAT. < If no PAT has been received yet, false will be returned. int Vpid(void) const { return vpid; } < Returns the video pid as defined by the current PMT, or 0 if no video < pid has been detected, yet. int Ppid(void) const { return ppid; } < Returns the PCR pid as defined by the current PMT, or 0 if no PCR < pid has been detected, yet. int Vtype(void) const { return vtype; } < Returns the video stream type as defined by the current PMT, or 0 if no video < stream type has been detected, yet. const int *Apids(void) const { return apids; } const int *Dpids(void) const { return dpids; } const int *Spids(void) const { return spids; } int Apid(int i) const { return (0 <= i && i < MAXAPIDS) ? apids[i] : 0; } int Dpid(int i) const { return (0 <= i && i < MAXDPIDS) ? dpids[i] : 0; } int Spid(int i) const { return (0 <= i && i < MAXSPIDS) ? spids[i] : 0; } int Atype(int i) const { return (0 <= i && i < MAXAPIDS) ? atypes[i] : 0; } int Dtype(int i) const { return (0 <= i && i < MAXDPIDS) ? dtypes[i] : 0; } const char *Alang(int i) const { return (0 <= i && i < MAXAPIDS) ? alangs[i] : ""; } const char *Dlang(int i) const { return (0 <= i && i < MAXDPIDS) ? dlangs[i] : ""; } const char *Slang(int i) const { return (0 <= i && i < MAXSPIDS) ? slangs[i] : ""; } uchar SubtitlingType(int i) const { return (0 <= i && i < MAXSPIDS) ? subtitlingTypes[i] : uchar(0); } uint16_t CompositionPageId(int i) const { return (0 <= i && i < MAXSPIDS) ? compositionPageIds[i] : uint16_t(0); } uint16_t AncillaryPageId(int i) const { return (0 <= i && i < MAXSPIDS) ? ancillaryPageIds[i] : uint16_t(0); } }; // TS to PES converter: // Puts together the payload of several TS packets that form one PES // packet. class cTsToPes { private: uchar *data; int size; int length; int offset; uchar *lastData; int lastLength; bool repeatLast; public: cTsToPes(void); ~cTsToPes(); void PutTs(const uchar *Data, int Length); < Puts the payload data of the single TS packet at Data into the converter. < Length is always TS_SIZE. < If the given TS packet starts a new PES payload packet, the converter < will be automatically reset. Any packets before the first one that starts < a new PES payload packet will be ignored. < Once a TS packet has been put into a cTsToPes converter, all subsequent < packets until the next call to Reset() must belong to the same PID as < the first packet. There is no check whether this actually is the case, so < the caller is responsible for making sure this condition is met. const uchar *GetPes(int &Length); < Gets a pointer to the complete PES packet, or NULL if the packet < is not complete yet. If the packet is complete, Length will contain < the total packet length. The returned pointer is only valid until < the next call to PutTs() or Reset(), or until this object is destroyed. < Once GetPes() has returned a non-NULL value, it must be called < repeatedly, and the data processed, until it returns NULL. This < is because video packets may be larger than the data a single < PES packet with an actual length field can hold, and are therefore < split into several PES packets with smaller sizes. < Note that for video data GetPes() may only be called if the next < TS packet that will be given to PutTs() has the "payload start" flag < set, because this is the only way to determine the end of a video PES < packet. void SetRepeatLast(void); < Makes the next call to GetPes() return exactly the same data as the < last one (provided there was no call to Reset() in the meantime). void Reset(void); < Resets the converter. This needs to be called after a PES packet has < been fetched by a call to GetPes(), and before the next call to < PutTs(). }; // Some helper functions for debugging: void BlockDump(const char *Name, const u_char *Data, int Length); void TsDump(const char *Name, const u_char *Data, int Length); void PesDump(const char *Name, const u_char *Data, int Length); // Frame detector: #define <API key> 100 class cFrameParser; class cFrameDetector { private: enum { MaxPtsValues = 150 }; int pid; int type; bool synced; bool newFrame; bool independentFrame; uint32_t ptsValues[MaxPtsValues]; // 32 bit is enough - we only need the delta int numPtsValues; int numIFrames; bool isVideo; double framesPerSecond; int framesInPayloadUnit; int <API key>; // Some broadcasters send one frame per payload unit (== 1), // while others put an entire GOP into one payload unit (> 1). bool scanning; cFrameParser *parser; public: cFrameDetector(int Pid = 0, int Type = 0); < Sets up a frame detector for the given Pid and stream Type. < If no Pid and Type is given, they need to be set by a separate < call to SetPid(). void SetPid(int Pid, int Type); < Sets the Pid and stream Type to detect frames for. int Analyze(const uchar *Data, int Length); < Analyzes the TS packets pointed to by Data. Length is the number of < bytes Data points to, and must be a multiple of TS_SIZE. < Returns the number of bytes that have been analyzed. < If the return value is 0, the data was not sufficient for analyzing and < Analyze() needs to be called again with more actual data. bool Synced(void) { return synced; } < Returns true if the frame detector has synced on the data stream. bool NewFrame(void) { return newFrame; } < Returns true if the data given to the last call to Analyze() started a < new frame. bool IndependentFrame(void) { return independentFrame; } < Returns true if a new frame was detected and this is an independent frame < (i.e. one that can be displayed by itself, without using data from any < other frames). double FramesPerSecond(void) { return framesPerSecond; } < Returns the number of frames per second, or 0 if this information is not < available. }; #endif // __REMUX_H
#ifndef <API key> #define <API key> #include "Java/Object.hpp" #include "Java/Class.hpp" #include "Compiler.h" #include <jni.h> #include <vector> class Context; // Consolidated class for handling Java objects that work with Android GPS // and sensor facilities. Public methods handle activation and deactivation of // specific sensors. class InternalSensors { static Java::TrivialClass gps_cls, sensors_cls; // IDs for methods in InternalGPS.java. static jmethodID gps_ctor_id, close_method; // IDs for methods in NonGPSSensors.java. static jmethodID sensors_ctor_id; static jmethodID <API key>; static jmethodID <API key>; static jmethodID <API key>; static jmethodID <API key>; static jmethodID <API key>; public: static bool Initialise(JNIEnv *env); static void Deinitialise(JNIEnv *env); private: // Java objects working with the GPS and the other sensors respectively. Java::Object obj_InternalGPS_; Java::Object obj_NonGPSSensors_; std::vector<int> <API key>; InternalSensors(JNIEnv* env, jobject gps_obj, jobject sensors_obj); void <API key>(JNIEnv* env, jobject sensors_obj); public: ~InternalSensors(); /* Sensor type identifier constants for use with subscription methods below. These must have the same numerical values as their counterparts in the Android API's Sensor class. */ static constexpr int TYPE_ACCELEROMETER = 0x1; static constexpr int TYPE_GYROSCOPE = 0x4; static constexpr int TYPE_MAGNETIC_FIELD = 0x2; static constexpr int TYPE_PRESSURE = 0x6; // For information on these methods, see comments around analogous methods // in NonGPSSensors.java. const std::vector<int>& <API key>() const { return <API key>; } bool subscribeToSensor(int id); bool <API key>(int id); bool subscribedToSensor(int id) const; void <API key>(); gcc_malloc static InternalSensors *create(JNIEnv* env, Context* native_view, unsigned int index); }; #endif
<?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); // addon for joomla modal Box JHTML::_('behavior.modal'); // JHTML::_('behavior.tooltip'); $url = JRoute::_('index.php?option=com_virtuemart&view=productdetails&task=askquestion&<API key>=' . $this->product-><API key> . '&<API key>=' . $this->product-><API key> . '&tmpl=component'); $document = JFactory::getDocument(); $document-><API key>(" jQuery(document).ready(function($) { $('a.ask-a-question').click( function(){ $.facebox({ iframe: '" . $url . "', rev: 'iframe|550|550' }); return false ; }); /* $('.additional-images a').mouseover(function() { var himg = this.href ; var extension=himg.substring(himg.lastIndexOf('.')+1); if (extension =='png' || extension =='jpg' || extension =='gif') { $('.main-image img').attr('src',himg ); } console.log(extension) });*/ }); "); /* Let's see if we found the product */ if (empty($this->product)) { echo JText::_('<API key>'); echo '<br /><br /> ' . $this->continue_link_html; return; } ?> <div class="productdetails-view productdetails"> <?php // Product Navigation if (VmConfig::get('product_navigation', 1)) { ?> <div class="product-neighbours"> <?php if (!empty($this->product->neighbours ['previous'][0])) { $prev_link = JRoute::_('index.php?option=com_virtuemart&view=productdetails&<API key>=' . $this->product->neighbours ['previous'][0] ['<API key>'] . '&<API key>=' . $this->product-><API key>); echo JHTML::_('link', $prev_link, $this->product->neighbours ['previous'][0] ['product_name'], array('class' => 'previous-page')); } if (!empty($this->product->neighbours ['next'][0])) { $next_link = JRoute::_('index.php?option=com_virtuemart&view=productdetails&<API key>=' . $this->product->neighbours ['next'][0] ['<API key>'] . '&<API key>=' . $this->product-><API key>); echo JHTML::_('link', $next_link, $this->product->neighbours ['next'][0] ['product_name'], array('class' => 'next-page')); } ?> <div class="clear"></div> </div> <?php } // Product Navigation END ?> <?php // Back To Category Button if ($this->product-><API key>) { $catURL = JRoute::_('index.php?option=com_virtuemart&view=category&<API key>='.$this->product-><API key>); $categoryName = $this->product->category_name ; } else { $catURL = JRoute::_('index.php?option=com_virtuemart'); $categoryName = jText::_('<API key>') ; } ?> <div class="back-to-category"> <a href="<?php echo $catURL ?>" class="product-details" title="<?php echo $categoryName ?>"><?php echo JText::sprintf('<API key>',$categoryName) ?></a> </div> <?php // Product Title ?> <h1><?php echo $this->product->product_name ?></h1> <?php // Product Title END ?> <?php // afterDisplayTitle Event echo $this->product->event->afterDisplayTitle ?> <?php // Product Edit Link echo $this->edit_link; // Product Edit Link END ?> <?php // PDF - Print - Email Icon if (VmConfig::get('show_emailfriend') || VmConfig::get('show_printicon') || VmConfig::get('pdf_button_enable')) { ?> <div class="icons"> <?php $link = 'index.php?tmpl=component&option=com_virtuemart&view=productdetails&<API key>=' . $this->product-><API key>; $MailLink = 'index.php?option=com_virtuemart&view=productdetails&task=recommend&<API key>=' . $this->product-><API key> . '&<API key>=' . $this->product-><API key> . '&tmpl=component'; if (VmConfig::get('pdf_icon', 1) == '1') { echo $this->linkIcon($link . '&format=pdf', 'COM_VIRTUEMART_PDF', 'pdf_button', 'pdf_button_enable', false); } echo $this->linkIcon($link . '&print=1', '<API key>', 'printButton', 'show_printicon'); echo $this->linkIcon($MailLink, '<API key>', 'emailButton', 'show_emailfriend'); ?> <div class="clear"></div> </div> <?php } // PDF - Print - Email Icon END ?> <?php // Product Short Description if (!empty($this->product->product_s_desc)) { ?> <div class="<API key>"> <?php /** @todo Test if content plugins modify the product description */ echo nl2br($this->product->product_s_desc); ?> </div> <?php } // Product Short Description END if (!empty($this->product->customfieldsSorted['ontop'])) { $this->position = 'ontop'; echo $this->loadTemplate('customfields'); } // Product Custom ontop end ?> <div> <div class="width50 floatleft"> <?php echo $this->loadTemplate('images'); ?> </div> <div class="width50 floatright"> <div class="spacer-buy-area"> <?php // TODO in Multi-Vendor not needed at the moment and just would lead to confusion /* $link = JRoute::_('index2.php?option=com_virtuemart&view=virtuemart&task=vendorinfo&<API key>='.$this->product-><API key>); $text = JText::_('<API key>'); echo '<span class="bold">'. JText::_('<API key>'). '</span>'; ?><a class="modal" href="<?php echo $link ?>"><?php echo $text ?></a><br /> */ ?> <?php if ($this->showRating) { $maxrating = VmConfig::get('<API key>', 5); if (empty($this->rating)) { ?> <span class="vote"><?php echo JText::_('<API key>') . ' ' . JText::_('<API key>') ?></span> <?php } else { $ratingwidth = $this->rating->rating * 24; //I don't use round as percetntage with works perfect, as for me ?> <span class="vote"> <?php echo JText::_('<API key>') . ' ' . round($this->rating->rating) . '/' . $maxrating; ?><br/> <span title=" <?php echo (JText::_("<API key>") . round($this->rating->rating) . '/' . $maxrating) ?>" class="ratingbox" style="display:inline-block;"> <span class="stars-orange" style="width:<?php echo $ratingwidth.'px'; ?>"> </span> </span> </span> <?php } } if (is_array($this-><API key>)) { foreach ($this-><API key> as $<API key>) { echo $<API key> . '<br />'; } } if (is_array($this-><API key>)) { foreach ($this-><API key> as $<API key>) { echo $<API key> . '<br />'; } } // Product Price if ($this->show_prices and (empty($this->product->images[0]) or $this->product->images[0]-><API key> == 0)) { echo $this->loadTemplate('showprices'); } ?> <?php // Add To Cart Button // if (!empty($this->product->prices) and !empty($this->product->images[0]) and $this->product->images[0]-><API key>==0 ) { if (!VmConfig::get('use_as_catalog', 0) and !empty($this->product->prices)) { echo $this->loadTemplate('addtocart'); } // Add To Cart Button END ?> <?php // Availability Image $stockhandle = VmConfig::get('stockhandle', 'none'); if (($this->product->product_in_stock - $this->product->product_ordered) < 1) { if ($stockhandle == 'risetime' and VmConfig::get('rised_availability') and empty($this->product-><API key>)) { ?> <div class="availability"> <?php echo (file_exists(JPATH_BASE . DS . VmConfig::get('assets_general_path') . 'images/availability/' . VmConfig::get('rised_availability'))) ? JHTML::image(JURI::root() . VmConfig::get('assets_general_path') . 'images/availability/' . VmConfig::get('rised_availability', '7d.gif'), VmConfig::get('rised_availability', '7d.gif'), array('class' => 'availability')) : VmConfig::get('rised_availability'); ?> </div> <?php } else if (!empty($this->product-><API key>)) { ?> <div class="availability"> <?php echo (file_exists(JPATH_BASE . DS . VmConfig::get('assets_general_path') . 'images/availability/' . $this->product-><API key>)) ? JHTML::image(JURI::root() . VmConfig::get('assets_general_path') . 'images/availability/' . $this->product-><API key>, $this->product-><API key>, array('class' => 'availability')) : $this->product-><API key>; ?> </div> <?php } } ?> <?php // Ask a question about this product if (VmConfig::get('ask_question', 1) == 1) { ?> <div class="ask-a-question"> <a class="ask-a-question" href="<?php echo $url ?>" ><?php echo JText::_('<API key>') ?></a> <!--<a class="ask-a-question modal" rel="{handler: 'iframe', size: {x: 700, y: 550}}" href="<?php echo $url ?>"><?php echo JText::_('<API key>') ?></a>--> </div> <?php } ?> <?php // Manufacturer of the Product if (VmConfig::get('show_manufacturers', 1) && !empty($this->product-><API key>)) { echo $this->loadTemplate('manufacturer'); } ?> </div> </div> <div class="clear"></div> </div> <?php // event <API key> echo $this->product->event-><API key>; ?> <?php // Product Description if (!empty($this->product->product_desc)) { ?> <div class="product-description"> <?php /** @todo Test if content plugins modify the product description */ ?> <span class="title"><?php echo JText::_('<API key>') ?></span> <?php echo $this->product->product_desc; ?> </div> <?php } // Product Description END if (!empty($this->product->customfieldsSorted['normal'])) { $this->position = 'normal'; echo $this->loadTemplate('customfields'); } // Product custom_fields END // Product Packaging $product_packaging = ''; if ($this->product->packaging || $this->product->box) { ?> <div class="product-packaging"> <?php if ($this->product->packaging) { $product_packaging .= JText::_('<API key>') . $this->product->packaging; if ($this->product->box) $product_packaging .= '<br />'; } if ($this->product->box) $product_packaging .= JText::_('<API key>') . $this->product->box; echo str_replace("{unit}", $this->product->product_unit ? $this->product->product_unit : JText::_('<API key>'), $product_packaging); ?> </div> <?php } // Product Packaging END ?> <?php // Product Files // foreach ($this->product->images as $fkey => $file) { // Todo add downloadable files again // if( $file->filesize > 0.5) $filesize_display = ' ('. number_format($file->filesize, 2,',','.')." MB)"; // else $filesize_display = ' ('. number_format($file->filesize*1024, 2,',','.')." KB)"; /* Show pdf in a new Window, other file types will be offered as download */ // $target = stristr($file->file_mimetype, "pdf") ? "_blank" : "_self"; // $link = JRoute::_('index.php?view=productdetails&task=getfile&virtuemart_media_id='.$file->virtuemart_media_id.'&<API key>='.$this->product-><API key>); // echo JHTMl::_('link', $link, $file->file_title.$filesize_display, array('target' => $target)); if (!empty($this->product-><API key>)) { echo $this->loadTemplate('relatedproducts'); } // Product <API key> END if (!empty($this->product-><API key>)) { echo $this->loadTemplate('relatedcategories'); } // Product <API key> END // Show child categories if (VmConfig::get('showCategory', 1)) { echo $this->loadTemplate('showcategory'); } if (!empty($this->product->customfieldsSorted['onbot'])) { $this->position='onbot'; echo $this->loadTemplate('customfields'); } // Product Custom ontop end ?> <?php // <API key> event echo $this->product->event->afterDisplayContent; ?> <?php echo $this->loadTemplate('reviews'); ?> </div>
package com.codename1.ui.scene; import com.codename1.properties.Property; import com.codename1.ui.Component; import com.codename1.ui.Container; import com.codename1.ui.Graphics; import com.codename1.ui.plaf.Border; /** * A scene graph. Supports 3D on platforms where {@link com.codename1.ui.Transform#<API key>() } is true (iOS and Android currently). * @author Steve Hannah * @deprecated For internal use only */ public class Scene extends Container { /** * The root node. */ private Node root; public final Property<Camera,Scene> camera; public Scene() { setUIID("Scene"); camera = new Property<Camera,Scene>("camera", (Camera)null); } /** * Set the root node. * @param root The root node. */ public void setRoot(Node root) { if (this.root != null) { this.root.setScene(null); } this.root = root; if (this.root != null) { root.setScene(this); } } @Override public void paint(Graphics g) { super.paint(g); if (root != null) { g.resetAffine(); int clipX = g.getClipX(); int clipY = g.getClipY(); int clipW = g.getClipWidth(); int clipH = g.getClipHeight(); g.translate(getX(), getY()); g.setAntiAliased(true); root.render(g); g.translate(-getX(), -getY()); g.resetAffine(); g.setClip(clipX, clipY, clipW, clipH); } } @Override public void layoutContainer() { root.setNeedsLayout(true); super.layoutContainer(); } }
#ifndef QUERYRESULT_H #define QUERYRESULT_H #undef <API key> #include <ace/Refcounted_Auto_Ptr.h> #include <ace/Null_Mutex.h> #include "Common.h" #include "Field.h" #include "Log.h" class QueryResult { public: QueryResult(uint64 rowCount, uint32 fieldCount) : mFieldCount(fieldCount), mRowCount(rowCount) {} virtual ~QueryResult() {} virtual bool NextRow() = 0; Field *Fetch() const { return mCurrentRow; } const Field & operator [] (int index) const { return mCurrentRow[index]; } uint32 GetFieldCount() const { return mFieldCount; } uint64 GetRowCount() const { return mRowCount; } protected: Field *mCurrentRow; uint32 mFieldCount; uint64 mRowCount; }; typedef <API key> <QueryResult, ACE_Null_Mutex> QueryResultAutoPtr; typedef std::vector<std::string> QueryFieldNames; class QueryNamedResult { public: explicit QueryNamedResult(QueryResultAutoPtr query, QueryFieldNames const& names) : mQuery(query), mFieldNames(names) {} ~QueryNamedResult() { } // compatible interface with QueryResult bool NextRow() { return mQuery->NextRow(); } Field *Fetch() const { return mQuery->Fetch(); } uint32 GetFieldCount() const { return mQuery->GetFieldCount(); } uint64 GetRowCount() const { return mQuery->GetRowCount(); } Field const& operator[] (int index) const { return (*mQuery)[index]; } // named access Field const& operator[] (const std::string &name) const { return mQuery->Fetch()[GetField_idx(name)]; } QueryFieldNames const& GetFieldNames() const { return mFieldNames; } uint32 GetField_idx(const std::string &name) const { for(size_t idx = 0; idx < mFieldNames.size(); ++idx) { if(mFieldNames[idx] == name) return idx; } ASSERT(false && "unknown field name"); return uint32(-1); } protected: QueryResultAutoPtr mQuery; QueryFieldNames mFieldNames; }; #endif
# This file is part of EasyBuild, # EasyBuild is free software: you can redistribute it and/or modify # the Free Software Foundation v2. # EasyBuild is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the from easybuild.toolchains.gompi import Gompi from easybuild.toolchains.gmkl import Gmkl from easybuild.toolchains.fft.intelfftw import IntelFFTW from easybuild.toolchains.linalg.intelmkl import IntelMKL class Gomkl(Gompi, IntelMKL, IntelFFTW): """Compiler toolchain with GCC, OpenMPI, Intel Math Kernel Library (MKL) and Intel FFTW wrappers.""" NAME = 'gomkl' SUBTOOLCHAIN = [Gompi.NAME, Gmkl.NAME]
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ #ifndef _PLUGIN_H_ #define _PLUGIN_H_ #include <glib-object.h> #define <API key> (<API key> ()) #define SC_PLUGIN_IFNET(obj) (<API key> ((obj), <API key>, SCPluginIfnet)) #define <API key>(klass) (<API key> ((klass), <API key>, SCPluginIfnetClass)) #define SC_IS_PLUGIN_IFNET(obj) (<API key> ((obj), <API key>)) #define <API key>(klass) (<API key> ((klass), <API key>)) #define <API key>(obj) (<API key> ((obj), <API key>, SCPluginIfnetClass)) typedef struct _SCPluginIfnet SCPluginIfnet; typedef struct _SCPluginIfnetClass SCPluginIfnetClass; struct _SCPluginIfnet { GObject parent; }; struct _SCPluginIfnetClass { GObjectClass parent; }; const char * <API key> (void); GType <API key> (void); #endif
// This file is part of PISM. // PISM is free software; you can redistribute it and/or modify it under the // version. // PISM is distributed in the hope that it will be useful, but WITHOUT ANY // details. // along with PISM; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "bedrockThermalUnit.hh" #include "PIO.hh" #include "PISMVars.hh" #include "LocalInterpCtx.hh" #include "IceGrid.hh" #include "pism_options.hh" bool IceModelVec3BTU::good_init() { return ((n_levels >= 2) && (Lbz > 0.0) && (v != PETSC_NULL)); } PetscErrorCode IceModelVec3BTU::create(IceGrid &mygrid, const char my_short_name[], bool local, int myMbz, PetscReal myLbz, int stencil_width) { PetscErrorCode ierr; grid = &mygrid; if (!utIsInit()) { SETERRQ(grid->com, 1, "PISM ERROR: UDUNITS *was not* initialized.\n"); } if (v != PETSC_NULL) { SETERRQ1(grid->com, 2,"IceModelVec3BTU with name='%s' already allocated\n",name.c_str()); } name = my_short_name; n_levels = myMbz; Lbz = myLbz; zlevels.resize(n_levels); double dz = Lbz / (myMbz - 1); for (int i = 0; i < n_levels; ++i) zlevels[i] = -Lbz + i * dz; zlevels.back() = 0; da_stencil_width = stencil_width; ierr = create_2d_da(da, n_levels, da_stencil_width); CHKERRQ(ierr); localp = local; if (local) { ierr = DMCreateLocalVector(da, &v); CHKERRQ(ierr); } else { ierr = <API key>(da, &v); CHKERRQ(ierr); } vars[0].init_3d(name, mygrid, zlevels); vars[0].dimensions["z"] = "zb"; map<string,string> &attrs = vars[0].z_attrs; attrs["axis"] = "Z"; attrs["long_name"] = "Z-coordinate in bedrock"; // PROPOSED: attrs["standard_name"] = "<API key>"; attrs["units"] = "m"; attrs["positive"] = "up"; if (!good_init()) { SETERRQ1(grid->com, 1,"create() says IceModelVec3BTU with name %s was not properly created\n", name.c_str()); } return 0; } PetscErrorCode IceModelVec3BTU::get_layer_depth(PetscReal &depth) { if (!good_init()) { SETERRQ1(grid->com, 1,"get_layer_depth() says IceModelVec3BTU with name %s was not properly created\n", name.c_str()); } depth = Lbz; return 0; } PetscErrorCode IceModelVec3BTU::get_spacing(PetscReal &dzb) { if (!good_init()) { SETERRQ1(grid->com, 1,"get_spacing() says IceModelVec3BTU with name %s was not properly created\n", name.c_str()); } dzb = Lbz / (n_levels - 1); return 0; } PISMBedThermalUnit::PISMBedThermalUnit(IceGrid &g, const NCConfigVariable &conf) : PISMComponent_TS(g, conf) { bedtoptemp = NULL; ghf = NULL; Mbz = 1; Lbz = 0; } //! \brief Allocate storage for the temperature in the bedrock layer (if there //! is a bedrock layer). PetscErrorCode PISMBedThermalUnit::allocate(int my_Mbz, double my_Lbz) { PetscErrorCode ierr; // to allow multiple calls to init() during the initialization sequence if (temp.was_created()) return 0; Mbz = my_Mbz; Lbz = my_Lbz; if ((Lbz <= 0.0) && (Mbz > 1)) { SETERRQ(grid.com, 1,"PISMBedThermalUnit can not be created with negative or zero Lbz value\n" " and more than one layers\n"); } if (Mbz > 1) { ierr = temp.create(grid, "litho_temp", false, Mbz, Lbz); CHKERRQ(ierr); ierr = temp.set_attrs("model_state", "lithosphere (bedrock) temperature, in PISMBedThermalUnit", "K", ""); CHKERRQ(ierr); ierr = temp.set_attr("valid_min", 0.0); CHKERRQ(ierr); } return 0; } //! \brief Initialize the bedrock thermal unit. PetscErrorCode PISMBedThermalUnit::init(PISMVars &vars) { PetscErrorCode ierr; bool i_set, Mbz_set, Lbz_set; string input_file; grid_info g; t = dt = GSL_NAN; // every re-init restarts the clock ierr = verbPrintf(2,grid.com, "* Initializing the bedrock thermal unit ... setting constants ...\n"); CHKERRQ(ierr); // Get pointers to fields owned by IceModel. bedtoptemp = dynamic_cast<IceModelVec2S*>(vars.get("bedtoptemp")); if (bedtoptemp == NULL) SETERRQ(grid.com, 1, "bedtoptemp is not available"); ghf = dynamic_cast<IceModelVec2S*>(vars.get("bheatflx")); if (ghf == NULL) SETERRQ(grid.com, 2, "bheatflx is not available"); Mbz = (PetscInt)config.get("grid_Mbz"); Lbz = (PetscInt)config.get("grid_Lbz"); // build constant diffusivity for heat equation bed_rho = config.get("<API key>"); bed_c = config.get("<API key>"); bed_k = config.get("<API key>"); bed_D = bed_k / (bed_rho * bed_c); ierr = PetscOptionsBegin(grid.com, "", "PISMBedThermalUnit options", ""); CHKERRQ(ierr); { ierr = PISMOptionsString("-i", "PISM input file name", input_file, i_set); CHKERRQ(ierr); ierr = PISMOptionsInt("-Mbz", "number of levels in bedrock thermal layer", Mbz, Mbz_set); CHKERRQ(ierr); ierr = PISMOptionsReal("-Lbz", "depth (thickness) of bedrock thermal layer", Lbz, Lbz_set); CHKERRQ(ierr); } ierr = PetscOptionsEnd(); CHKERRQ(ierr); if (i_set) { // If we're initializing from a file we need to get the number of bedrock // levels and the depth of the bed thermal layer from it: PIO nc(grid.com, grid.rank, "netcdf3"); ierr = nc.open(input_file, PISM_NOWRITE); CHKERRQ(ierr); bool exists; ierr = nc.inq_var("litho_temp", exists); CHKERRQ(ierr); if (exists) { ierr = nc.inq_grid_info("litho_temp", g); CHKERRQ(ierr); Mbz = g.z_len; Lbz = - g.z_min; ierr = allocate(Mbz, Lbz); CHKERRQ(ierr); int last_record = g.t_len - 1; ierr = temp.read(input_file, last_record); CHKERRQ(ierr); } else { Mbz = 1; Lbz = 0; } ierr = nc.close(); CHKERRQ(ierr); ierr = ignore_option(grid.com, "-Mbz"); CHKERRQ(ierr); ierr = ignore_option(grid.com, "-Lbz"); CHKERRQ(ierr); } else { // Bootstrapping if (Mbz_set && Mbz == 1) { ierr = ignore_option(grid.com, "-Lbz"); CHKERRQ(ierr); Lbz = 0; } else if (Mbz_set ^ Lbz_set) { PetscPrintf(grid.com, "PISMBedThermalUnit ERROR: please specify both -Mbz and -Lbz.\n"); PISMEnd(); } ierr = allocate(Mbz, Lbz); CHKERRQ(ierr); ierr = bootstrap(); CHKERRQ(ierr); } // If we're using a minimal model, then we're done: if (!temp.was_created()) { ierr = verbPrintf(2,grid.com, " minimal model for lithosphere: stored geothermal flux applied to ice base ...\n"); CHKERRQ(ierr); return 0; } ierr = regrid(); CHKERRQ(ierr); return 0; } void PISMBedThermalUnit::add_vars_to_output(string /*keyword*/, map<string,NCSpatialVariable> &result) { if (temp.was_created()) { result[temp.string_attr("short_name")] = temp.get_metadata(); } } PetscErrorCode PISMBedThermalUnit::define_variables( set<string> vars, const PIO &nc, PISM_IO_Type nctype) { if (temp.was_created()) { PetscErrorCode ierr; if (set_contains(vars, temp.string_attr("short_name"))) { ierr = temp.define(nc, nctype); CHKERRQ(ierr); } } return 0; } PetscErrorCode PISMBedThermalUnit::write_variables(set<string> vars, string filename) { if (temp.was_created()) { PetscErrorCode ierr; if (set_contains(vars, temp.string_attr("short_name"))) { ierr = temp.write(filename.c_str()); CHKERRQ(ierr); } } return 0; } /*! Because the grid for the bedrock thermal layer is equally-spaced, and because the heat equation being solved in the bedrock is time-invariant (%e.g. no advection at evolving velocity and no time-dependence to physical constants), the explicit time-stepping can compute the maximum stable time step easily. The basic scheme is \f[T_k^{n+1} = T_k^n + R (T_{k-1}^n - 2 T_k^n + T_{k+1}^n)\f] where \f[R = \frac{k \Delta t}{\rho c \Delta z^2} = \frac{D \Delta t}{\Delta z^2}.\f] The stability condition is that the coefficients of temperatures on the right are all nonnegative, equivalently \f$1-2R\ge 0\f$ or \f$R\le 1/2\f$ or \f[\Delta t \le \frac{\Delta z^2}{2 D}.\f] This is a formula for the maximum stable timestep. For more, see [\ref MortonMayers]. The above describes the general case where Mbz > 1. */ PetscErrorCode PISMBedThermalUnit::max_timestep(PetscReal /*my_t*/, PetscReal &my_dt, bool &restrict) { if (temp.was_created()) { PetscReal dzb; temp.get_spacing(dzb); my_dt = dzb * dzb / (2.0 * bed_D); // max dt from stability; in seconds restrict = true; } else { my_dt = 0; restrict = false; } return 0; } /* FIXME: the old scheme had better stability properties, as follows: Because there is no advection, the simplest centered implicit (backward Euler) scheme is easily "bombproof" without choosing \f$\lambda\f$, or other complications. It has this scaled form, \anchor bedrockeqn \f[ -R_b T_{k-1}^{n+1} + \left(1 + 2 R_b\right) T_k^{n+1} - R_b T_{k+1}^{n+1} = T_k^n, \tag{bedrockeqn} \f] where \f[ R_b = \frac{k_b \Delta t}{\rho_b c_b \Delta z^2}. \f] This is unconditionally stable for a pure bedrock problem, and has a maximum principle, without any further qualification [\ref MortonMayers]. FIXME: now a trapezoid rule could be used */ PetscErrorCode PISMBedThermalUnit::update(PetscReal my_t, PetscReal my_dt) { PetscErrorCode ierr; if (!temp.was_created()) return 0; // in this case we are up to date // as a derived class of PISMComponent_TS, has t,dt members which keep track // of last update time-interval; so we do some checks ... // CHECK: has the desired time-interval already been dealt with? if ((fabs(my_t - t) < 1e-12) && (fabs(my_dt - dt) < 1e-12)) return 0; // CHECK: is the desired time interval a forward step?; backward heat equation not good! if (my_dt < 0) { SETERRQ(grid.com, 1,"PISMBedThermalUnit::update() does not allow negative timesteps\n"); } // CHECK: is desired time-interval equal to [my_t,my_t+my_dt] where my_t = t + dt? if ((!gsl_isnan(t)) && (!gsl_isnan(dt))) { // this check should not fire on first use bool contiguous = true; if (fabs(t + dt) < 1) { if ( fabs(my_t - (t + dt)) >= 1e-12 ) // check if the absolute difference is small contiguous = false; } else { if ( fabs(my_t - (t + dt)) / (t + dt) >= 1e-12 ) // check if the relative difference is small contiguous = false; } if (contiguous == false) { SETERRQ4(grid.com, 2,"PISMBedThermalUnit::update() requires next update to be contiguous with last;\n" " stored: t = %f s, dt = %f s\n" " desired: my_t = %f s, my_dt = %f s\n", t,dt,my_t,my_dt); } } // CHECK: is desired time-step too long? PetscScalar my_max_dt; bool restrict_dt; ierr = max_timestep(my_t, my_max_dt, restrict_dt); CHKERRQ(ierr); if (restrict_dt && my_max_dt < my_dt) { SETERRQ(grid.com, 3,"PISMBedThermalUnit::update() thinks you asked for too big a timestep\n"); } // o.k., we have checked; we are going to do the desired timestep! t = my_t; dt = my_dt; if (bedtoptemp == NULL) SETERRQ(grid.com, 5, "bedtoptemp was never initialized"); if (ghf == NULL) SETERRQ(grid.com, 6, "bheatflx was never initialized"); PetscReal dzb; temp.get_spacing(dzb); const PetscInt k0 = Mbz - 1; // Tb[k0] = ice/bed interface temp, at z=0 #if (PISM_DEBUG==1) for (PetscInt k = 0; k < Mbz; k++) { // working upward from base const PetscReal z = - Lbz + (double)k * dzb; ierr = temp.isLegalLevel(z); CHKERRQ(ierr); } #endif const PetscReal bed_R = bed_D * my_dt / (dzb * dzb); PetscScalar *Tbold; vector<PetscScalar> Tbnew(Mbz); ierr = temp.begin_access(); CHKERRQ(ierr); ierr = ghf->begin_access(); CHKERRQ(ierr); ierr = bedtoptemp->begin_access(); CHKERRQ(ierr); for (PetscInt i = grid.xs; i < grid.xs+grid.xm; ++i) { for (PetscInt j = grid.ys; j < grid.ys+grid.ym; ++j) { ierr = temp.getInternalColumn(i,j,&Tbold); CHKERRQ(ierr); // Tbold actually points into temp memory Tbold[k0] = (*bedtoptemp)(i,j); // sets Dirichlet explicit-in-time b.c. at top of bedrock column const PetscReal Tbold_negone = Tbold[1] + 2 * (*ghf)(i,j) * dzb / bed_k; Tbnew[0] = Tbold[0] + bed_R * (Tbold_negone - 2 * Tbold[0] + Tbold[1]); for (PetscInt k = 1; k < k0; k++) { // working upward from base Tbnew[k] = Tbold[k] + bed_R * (Tbold[k-1] - 2 * Tbold[k] + Tbold[k+1]); } Tbnew[k0] = (*bedtoptemp)(i,j); ierr = temp.setInternalColumn(i,j,&Tbnew[0]); CHKERRQ(ierr); // copy from Tbnew into temp memory } } ierr = bedtoptemp->end_access(); CHKERRQ(ierr); ierr = ghf->end_access(); CHKERRQ(ierr); ierr = temp.end_access(); CHKERRQ(ierr); return 0; } /*! Computes the heat flux from the bedrock thermal layer upward into the ice/bedrock interface: \f[G_0 = -k_b \frac{\partial T_b}{\partial z}\big|_{z=0}.\f] Uses the second-order finite difference expression \f[\frac{\partial T_b}{\partial z}\big|_{z=0} \approx \frac{3 T_b(0) - 4 T_b(-\Delta z) + T_b(-2\Delta z)}{2 \Delta z}\f] where \f$\Delta z\f$ is the equal spacing in the bedrock. The above expression only makes sense when \c Mbz = \c temp.n_levels >= 3. When \c Mbz = 2 we use first-order differencing. When temp was not created, the \c Mbz <= 1 cases, we return the stored geothermal flux. */ PetscErrorCode PISMBedThermalUnit::<API key>(IceModelVec2S &result) { PetscErrorCode ierr; if (!temp.was_created()) { result.copy_from(*ghf); return 0; } PetscReal dzb; temp.get_spacing(dzb); const PetscInt k0 = Mbz - 1; // Tb[k0] = ice/bed interface temp, at z=0 PetscScalar *Tb; ierr = temp.begin_access(); CHKERRQ(ierr); ierr = result.begin_access(); CHKERRQ(ierr); for (PetscInt i = grid.xs; i < grid.xs+grid.xm; ++i) { for (PetscInt j = grid.ys; j < grid.ys+grid.ym; ++j) { ierr = temp.getInternalColumn(i,j,&Tb); CHKERRQ(ierr); if (Mbz >= 3) { result(i,j) = - bed_k * (3 * Tb[k0] - 4 * Tb[k0-1] + Tb[k0-2]) / (2 * dzb); } else { result(i,j) = - bed_k * (Tb[k0] - Tb[k0-1]) / dzb; } } } ierr = temp.end_access(); CHKERRQ(ierr); ierr = result.end_access(); CHKERRQ(ierr); return 0; } PetscErrorCode PISMBedThermalUnit::regrid() { PetscErrorCode ierr; bool regrid_file_set, regrid_vars_set; string regrid_file; vector<string> regrid_vars; ierr = PetscOptionsBegin(grid.com, "", "PISMBedThermalUnit regridding options", ""); CHKERRQ(ierr); { ierr = PISMOptionsString("-regrid_file", "regridding file name", regrid_file, regrid_file_set); CHKERRQ(ierr); ierr = <API key>("-regrid_vars", "comma-separated list of regridding variables", "", regrid_vars, regrid_vars_set); CHKERRQ(ierr); } ierr = PetscOptionsEnd(); CHKERRQ(ierr); // stop unless both options are set if (! regrid_file_set) return 0; // stop if temp was not allocated if (! temp.was_created()) return 0; set<string> vars; for (unsigned int i = 0; i < regrid_vars.size(); ++i) vars.insert(regrid_vars[i]); // stop if the user did not ask to regrid BTU temperature if (regrid_vars_set && ! set_contains(vars, temp.string_attr("short_name"))) return 0; ierr = temp.regrid(regrid_file.c_str(), true); CHKERRQ(ierr); return 0; } PetscErrorCode PISMBedThermalUnit::bootstrap() { PetscErrorCode ierr; if (Mbz < 2) return 0; ierr = verbPrintf(2,grid.com, " bootstrapping to fill lithosphere temperatures in bedrock thermal layers,\n" " using provided bedtoptemp and a linear function from provided geothermal flux ...\n"); CHKERRQ(ierr); PetscScalar* Tb; PetscReal dzb; temp.get_spacing(dzb); const PetscInt k0 = Mbz-1; // Tb[k0] = ice/bedrock interface temp ierr = bedtoptemp->begin_access(); CHKERRQ(ierr); ierr = ghf->begin_access(); CHKERRQ(ierr); ierr = temp.begin_access(); CHKERRQ(ierr); for (PetscInt i = grid.xs; i < grid.xs+grid.xm; ++i) { for (PetscInt j = grid.ys; j < grid.ys+grid.ym; ++j) { ierr = temp.getInternalColumn(i,j,&Tb); CHKERRQ(ierr); // Tb points into temp memory Tb[k0] = (*bedtoptemp)(i,j); for (PetscInt k = k0-1; k >= 0; k Tb[k] = Tb[k+1] + dzb * (*ghf)(i,j) / bed_k; } } } ierr = bedtoptemp->end_access(); CHKERRQ(ierr); ierr = ghf->end_access(); CHKERRQ(ierr); ierr = temp.end_access(); CHKERRQ(ierr); return 0; }
// Experimental unified task-data parallel manycore LDRD #ifndef <API key> #define <API key> #include <Kokkos_Macros.hpp> #if defined(<API key>) #include <<API key>.hpp> #include <Kokkos_Core_fwd.hpp> #include <Kokkos_MemoryPool.hpp> #include <impl/Kokkos_TaskBase.hpp> #include <impl/Kokkos_TaskResult.hpp> #include <impl/Kokkos_TaskQueue.hpp> #include <Kokkos_Atomic.hpp> #include <string> #include <typeinfo> #include <stdexcept> #include <cassert> namespace Kokkos { namespace Impl { template <typename ExecSpace, typename MemorySpace = typename ExecSpace::memory_space> class <API key>; template <class ExecSpace, class MemorySpace> class TaskQueueMultiple : public TaskQueue<ExecSpace, MemorySpace> { private: using base_t = TaskQueue<ExecSpace, MemorySpace>; using queue_collection_t = <API key><ExecSpace, MemorySpace>; int m_league_rank = static_cast<int>(<API key>); // This pointer is owning only if m_league_rank == 0 queue_collection_t* m_other_queues = nullptr; public: struct Destroy { TaskQueueMultiple* m_queue; void <API key>(); }; using team_queue_type = TaskQueueMultiple; TaskQueueMultiple(int arg_league_rank, queue_collection_t* arg_other_queues, typename base_t::memory_pool const& arg_memory_pool) : base_t(arg_memory_pool), m_league_rank(arg_league_rank), m_other_queues(arg_other_queues) {} explicit TaskQueueMultiple( typename base_t::memory_pool const& arg_memory_pool) : base_t(arg_memory_pool), m_league_rank(0) { void* other_queues_buffer = typename base_t::memory_space{}.allocate(sizeof(queue_collection_t)); m_other_queues = new (other_queues_buffer) queue_collection_t(this); } ~TaskQueueMultiple() { if (m_league_rank == 0 && m_other_queues != nullptr) { m_other_queues->~queue_collection_t(); typename base_t::memory_space{}.deallocate(m_other_queues, sizeof(queue_collection_t)); } // rest of destruction is handled in the base class } void <API key>(int arg_league_size) const noexcept { m_other_queues-><API key>(arg_league_size, this->m_memory); } <API key> team_queue_type& get_team_queue(int arg_league_rank) noexcept { if (arg_league_rank == m_league_rank) return *this; else return m_other_queues->get_team_queue(arg_league_rank); } <API key> typename base_t::task_root_type* <API key>() noexcept { TaskBase* rv = nullptr; auto* const end_tag = reinterpret_cast<TaskBase*>(TaskBase::EndTag); if (m_other_queues == nullptr) { Kokkos::abort("attempted to steal task before queues were initialized!"); } // Loop by priority and then type, and then team for (int i = 0; i < base_t::NumQueue; ++i) { for (int j = 0; j < 2; ++j) { // for now, always start by trying to steal from team zero for (int iteam = 0; iteam < m_other_queues->size(); ++iteam) { if (iteam == m_league_rank) continue; auto& steal_from = get_team_queue(iteam); if (*((volatile int*)&steal_from.m_ready_count) > 0) { // we've found at least one queue that's not done, so even if we // can't pop something off of it we shouldn't return a nullptr // indicating completion. rv will be end_tag when the pop fails rv = base_t::pop_ready_task(&steal_from.m_ready[i][j]); if (rv != end_tag) { // task stolen. // first increment our ready count, then decrement the ready count // on the other queue: Kokkos::Impl::desul_atomic_inc( &this->m_ready_count, Kokkos::Impl::MemoryOrderSeqCst(), Kokkos::Impl::MemoryScopeDevice()); // TODO? // <API key> Kokkos::Impl::desul_atomic_dec( &steal_from.m_ready_count, Kokkos::Impl::MemoryOrderSeqCst(), Kokkos::Impl::MemoryScopeDevice()); // TODO? // <API key> return rv; } } } } } // at this point, rv will only be nullptr if *all* of the queues had an // m_ready_count of 0. This indicates quiescence. If at least some of them // had non-zero, there would have been at least one pop_ready_task that // was called and returned end_tag if it couldn't pop a task return rv; } }; template <typename ExecSpace, typename MemorySpace> class <API key> { private: using execution_space = ExecSpace; using memory_space = MemorySpace; using device_type = Kokkos::Device<execution_space, memory_space>; using memory_pool = Kokkos::MemoryPool<device_type>; using team_queue_type = TaskQueueMultiple<execution_space, memory_space>; using team_scheduler_type = BasicTaskScheduler<ExecSpace, team_queue_type>; using specialization = <API key><team_scheduler_type>; enum : long { max_num_queues = 6 }; // specialization::max_league_size }; // this is a non-owning pointer team_queue_type* m_rank_zero_queue = nullptr; // This really needs to be an optional<TaskQueue<ExecSpace>> union optional_queue { <API key> optional_queue() : uninitialized(0) {} <API key> ~optional_queue() { uninitialized = 0; } char uninitialized; team_queue_type initialized; } m_queues[max_num_queues]; int m_size = static_cast<int>(<API key>); public: <API key>() = delete; <API key>(<API key> const&) = delete; <API key>(<API key>&&) = delete; <API key>& operator=(<API key> const&) = delete; <API key>& operator=(<API key>&&) = delete; ~<API key>() { // destroy only the initialized queues that we own for (int iteam = 0; iteam < m_size - 1; ++iteam) { m_queues[iteam].initialized.~team_queue_type(); m_queues[iteam].uninitialized = 0; } } <API key> explicit <API key>(team_queue_type* arg_rank_zero_queue) : m_rank_zero_queue(arg_rank_zero_queue), m_size(1) {} void <API key>(int arg_count, memory_pool const& arg_memory_pool) noexcept { arg_count = std::min((int)max_num_queues, arg_count); // assert(arg_count <= max_num_queues); if (arg_count > m_size) { for (int i = m_size; i < arg_count; ++i) { new (&m_queues[i - 1].initialized) team_queue_type(i, this, arg_memory_pool); } m_size = arg_count; } } <API key> constexpr int size() const noexcept { return m_size; } <API key> constexpr bool initialized() const noexcept { return m_size != int(<API key>); } <API key> team_queue_type& get_team_queue(int iteam) { iteam %= max_num_queues; #if !defined(<API key>) && !defined(__CUDA_ARCH__) assert(initialized()); assert(iteam < m_size); assert(iteam >= 0); #endif if (iteam == 0) return *m_rank_zero_queue; else return m_queues[iteam - 1].initialized; } }; } /* namespace Impl */ } /* namespace Kokkos */ #include <impl/<API key>.hpp> #endif /* #if defined( <API key> ) */ #endif /* #ifndef <API key> */
#include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "diagnostic-core.h" #include "rtl.h" #include "ggc.h" static void free_list (rtx *, rtx *); /* Functions for maintaining cache-able lists of EXPR_LIST and INSN_LISTs. */ /* An INSN_LIST containing all INSN_LISTs allocated but currently unused. */ static GTY ((deletable)) rtx unused_insn_list; /* An EXPR_LIST containing all EXPR_LISTs allocated but currently unused. */ static GTY ((deletable)) rtx unused_expr_list; /* This function will free an entire list of either EXPR_LIST, INSN_LIST or DEPS_LIST nodes. This is to be used only on lists that consist exclusively of nodes of one type only. This is only called by free_EXPR_LIST_list, free_INSN_LIST_list and free_DEPS_LIST_list. */ static void free_list (rtx *listp, rtx *unused_listp) { rtx link, prev_link; prev_link = *listp; link = XEXP (prev_link, 1); gcc_assert (unused_listp != &unused_insn_list || GET_CODE (prev_link) == INSN_LIST); while (link) { gcc_assert (unused_listp != &unused_insn_list || GET_CODE (prev_link) == INSN_LIST); prev_link = link; link = XEXP (link, 1); } XEXP (prev_link, 1) = *unused_listp; *unused_listp = *listp; *listp = 0; } /* Find corresponding to ELEM node in the list pointed to by LISTP. This node must exist in the list. Returns pointer to that node. */ static rtx * find_list_elem (rtx elem, rtx *listp) { while (XEXP (*listp, 0) != elem) listp = &XEXP (*listp, 1); return listp; } /* Remove the node pointed to by LISTP from the list. */ static void remove_list_node (rtx *listp) { rtx node; node = *listp; *listp = XEXP (node, 1); XEXP (node, 1) = 0; } /* Removes corresponding to ELEM node from the list pointed to by LISTP. Returns that node. */ rtx remove_list_elem (rtx elem, rtx *listp) { rtx node; listp = find_list_elem (elem, listp); node = *listp; remove_list_node (listp); return node; } /* This call is used in place of a gen_rtx_INSN_LIST. If there is a cached node available, we'll use it, otherwise a call to gen_rtx_INSN_LIST is made. */ rtx_insn_list * alloc_INSN_LIST (rtx val, rtx next) { rtx_insn_list *r; if (unused_insn_list) { r = as_a <rtx_insn_list *> (unused_insn_list); unused_insn_list = r->next (); XEXP (r, 0) = val; XEXP (r, 1) = next; PUT_REG_NOTE_KIND (r, VOIDmode); gcc_assert (GET_CODE (r) == INSN_LIST); } else r = gen_rtx_INSN_LIST (VOIDmode, val, next); return r; } /* This call is used in place of a gen_rtx_EXPR_LIST. If there is a cached node available, we'll use it, otherwise a call to gen_rtx_EXPR_LIST is made. */ rtx_expr_list * alloc_EXPR_LIST (int kind, rtx val, rtx next) { rtx_expr_list *r; if (unused_expr_list) { r = as_a <rtx_expr_list *> (unused_expr_list); unused_expr_list = XEXP (r, 1); XEXP (r, 0) = val; XEXP (r, 1) = next; PUT_REG_NOTE_KIND (r, kind); } else r = gen_rtx_EXPR_LIST ((machine_mode) kind, val, next); return r; } /* This function will free up an entire list of EXPR_LIST nodes. */ void free_EXPR_LIST_list (rtx_expr_list **listp) { if (*listp == 0) return; free_list ((rtx *)listp, &unused_expr_list); } /* This function will free up an entire list of INSN_LIST nodes. */ void free_INSN_LIST_list (rtx_insn_list **listp) { if (*listp == 0) return; free_list ((rtx *)listp, &unused_insn_list); } /* Make a copy of the INSN_LIST list LINK and return it. */ rtx_insn_list * copy_INSN_LIST (rtx_insn_list *link) { rtx_insn_list *new_queue; rtx_insn_list **pqueue = &new_queue; for (; link; link = link->next ()) { rtx_insn *x = link->insn (); rtx_insn_list *newlink = alloc_INSN_LIST (x, NULL); *pqueue = newlink; pqueue = (rtx_insn_list **)&XEXP (newlink, 1); } *pqueue = NULL; return new_queue; } /* Duplicate the INSN_LIST elements of COPY and prepend them to OLD. */ rtx_insn_list * concat_INSN_LIST (rtx_insn_list *copy, rtx_insn_list *old) { rtx_insn_list *new_rtx = old; for (; copy ; copy = copy->next ()) { new_rtx = alloc_INSN_LIST (copy->insn (), new_rtx); PUT_REG_NOTE_KIND (new_rtx, REG_NOTE_KIND (copy)); } return new_rtx; } /* This function will free up an individual EXPR_LIST node. */ void free_EXPR_LIST_node (rtx ptr) { XEXP (ptr, 1) = unused_expr_list; unused_expr_list = ptr; } /* This function will free up an individual INSN_LIST node. */ void free_INSN_LIST_node (rtx ptr) { gcc_assert (GET_CODE (ptr) == INSN_LIST); XEXP (ptr, 1) = unused_insn_list; unused_insn_list = ptr; } /* Remove and free corresponding to ELEM node in the INSN_LIST pointed to by LISTP. */ void <API key> (rtx_insn *elem, rtx_insn_list **listp) { free_INSN_LIST_node (remove_list_elem (elem, (rtx *)listp)); } /* Remove and free the first node in the INSN_LIST pointed to by LISTP. */ rtx_insn * <API key> (rtx_insn_list **listp) { rtx_insn_list *node = *listp; rtx_insn *elem = node->insn (); remove_list_node ((rtx *)listp); free_INSN_LIST_node (node); return elem; } /* Remove and free the first node in the EXPR_LIST pointed to by LISTP. */ rtx <API key> (rtx_expr_list **listp) { rtx_expr_list *node = *listp; rtx elem = XEXP (node, 0); remove_list_node ((rtx *)listp); free_EXPR_LIST_node (node); return elem; } #include "gt-lists.h"
#ifndef _CRYPTO_INTERNAL_H #define _CRYPTO_INTERNAL_H #include <crypto/algapi.h> #include <linux/completion.h> #include <linux/mm.h> #include <linux/highmem.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/list.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/notifier.h> #include <linux/rwsem.h> #include <linux/slab.h> #include <linux/fips.h> /* * Use this only for FIPS Functional Test with CMT Lab. * FIPS_FUNC_TEST 1 will make self algorithm test (ecb aes) fail * FIPS_FUNC_TEST 12 will make self algorithm test (hmac sha1) fail * FIPS_FUNC_TEST 2 will make integrity check fail by corrupting the * kernel image * FIPS_FUNC_TEST 3 will make sure all the logs needed in no error mode * FIPS_FUNC_TEST 4 will make the necessary dumps for zeroization test * FIPS_FUNC_TEST 5 will make the continous PRNG test fail */ #ifdef CONFIG_CRYPTO_FIPS #define FIPS_FUNC_TEST 0 #else #define FIPS_FUNC_TEST 0 #endif /* Crypto notification events. */ enum { <API key>, <API key>, <API key>, <API key>, <API key>, }; struct crypto_instance; struct crypto_template; struct crypto_larval { struct crypto_alg alg; struct crypto_alg *adult; struct completion completion; u32 mask; }; extern struct list_head crypto_alg_list; extern struct rw_semaphore crypto_alg_sem; extern struct <API key> crypto_chain; #ifdef CONFIG_PROC_FS #ifdef CONFIG_CRYPTO_FIPS bool in_fips_err(void); void set_in_fips_err(void); void crypto_init_proc(int *fips_error); int do_integrity_check(void); int <API key>(void); #else void __init crypto_init_proc(void); #endif void __exit crypto_exit_proc(void); #else static inline void crypto_init_proc(void) { } static inline void crypto_exit_proc(void) { } #endif static inline unsigned int <API key>(struct crypto_alg *alg) { return alg->cra_ctxsize; } static inline unsigned int <API key>(struct crypto_alg *alg) { return alg->cra_ctxsize; } struct crypto_alg *crypto_mod_get(struct crypto_alg *alg); struct crypto_alg *crypto_alg_lookup(const char *name, u32 type, u32 mask); struct crypto_alg *<API key>(const char *name, u32 type, u32 mask); int <API key>(struct crypto_tfm *tfm); int <API key>(struct crypto_tfm *tfm); void <API key>(struct crypto_tfm *tfm); void <API key>(struct crypto_tfm *tfm); struct crypto_larval *crypto_larval_alloc(const char *name, u32 type, u32 mask); void crypto_larval_kill(struct crypto_alg *alg); struct crypto_alg *<API key>(const char *name, u32 type, u32 mask); void crypto_alg_tested(const char *name, int err); void <API key>(struct crypto_alg *alg, struct list_head *list, struct crypto_alg *nalg); void crypto_remove_final(struct list_head *list); void crypto_shoot_alg(struct crypto_alg *alg); struct crypto_tfm *__crypto_alloc_tfm(struct crypto_alg *alg, u32 type, u32 mask); void *crypto_create_tfm(struct crypto_alg *alg, const struct crypto_type *frontend); struct crypto_alg *crypto_find_alg(const char *alg_name, const struct crypto_type *frontend, u32 type, u32 mask); void *crypto_alloc_tfm(const char *alg_name, const struct crypto_type *frontend, u32 type, u32 mask); int <API key>(struct notifier_block *nb); int <API key>(struct notifier_block *nb); int <API key>(unsigned long val, void *v); static inline struct crypto_alg *crypto_alg_get(struct crypto_alg *alg) { atomic_inc(&alg->cra_refcnt); return alg; } static inline void crypto_alg_put(struct crypto_alg *alg) { if (atomic_dec_and_test(&alg->cra_refcnt) && alg->cra_destroy) alg->cra_destroy(alg); } static inline int crypto_tmpl_get(struct crypto_template *tmpl) { return try_module_get(tmpl->module); } static inline void crypto_tmpl_put(struct crypto_template *tmpl) { module_put(tmpl->module); } static inline int crypto_is_larval(struct crypto_alg *alg) { return alg->cra_flags & CRYPTO_ALG_LARVAL; } static inline int crypto_is_dead(struct crypto_alg *alg) { return alg->cra_flags & CRYPTO_ALG_DEAD; } static inline int crypto_is_moribund(struct crypto_alg *alg) { return alg->cra_flags & (CRYPTO_ALG_DEAD | CRYPTO_ALG_DYING); } static inline void crypto_notify(unsigned long val, void *v) { <API key>(&crypto_chain, val, v); } #endif /* _CRYPTO_INTERNAL_H */
// echoprint-codegen #ifndef CODEGEN_H #define CODEGEN_H // Entry point for generating codes from PCM data. #define ECHOPRINT_VERSION 4.12 #include <string> #include <vector> #ifdef _MSC_VER #ifdef CODEGEN_EXPORTS #define CODEGEN_API __declspec(dllexport) #pragma message("Exporting codegen.dll") #else #define CODEGEN_API __declspec(dllimport) #pragma message("Importing codegen.dll") #endif #else #define CODEGEN_API #endif class Fingerprint; class SubbandAnalysis; struct FPCode; class CODEGEN_API Codegen { public: Codegen(const float* pcm, unsigned int numSamples, int start_offset); std::string getCodeString(){return _CodeString;} int getNumCodes(){return _NumCodes;} static double getVersion() { return ECHOPRINT_VERSION; } private: Fingerprint* computeFingerprint(SubbandAnalysis *pSubbandAnalysis, int start_offset); std::string createCodeString(std::vector<FPCode> vCodes); std::string compress(const std::string& s); std::string _CodeString; int _NumCodes; }; #endif
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Invenio is free software; you can redistribute it and/or ## published by the Free Software Foundation; either version 2 of the ## Invenio is distributed in the hope that it will be useful, but ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Unit test for the hash functions. """ from invenio.utils.hash import md5, sha1 from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase class TestHashUtils(InvenioTestCase): """ hashutils TestSuite. """ def test_md5(self): self.assertEqual(md5('').hexdigest(), '<API key>') self.assertEqual(md5('test').hexdigest(), '<API key>') def test_sha1(self): self.assertEqual(sha1('').hexdigest(), '<SHA1-like>') self.assertEqual(sha1('test').hexdigest(), '<SHA1-like>') TEST_SUITE = make_test_suite(TestHashUtils, ) if __name__ == "__main__": run_test_suite(TEST_SUITE)
# implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. import sys from spacewalk.common.rhnLog import log_debug from spacewalk.server import rhnSQL from spacewalk.server.rhnLib import InvalidAction, ShadowAction from spacewalk.server.action.utils import SubscribedChannel, \ ChannelPackage, \ <API key>, \ NoActionInfo, \ PackageNotFound from spacewalk.server.rhnChannel import <API key> __rhnexport__ = ['initiate', '<API key>', 'add_tools_channel'] <API key> = rhnSQL.Statement(""" select ksd.label as profile_name, akg.kickstart_host, kvt.label as virt_type, akg.mem_kb, akg.vcpus, akg.disk_path, akg.virt_bridge, akg.cobbler_system_name, akg.disk_gb, akg.append_string, akg.guest_name, akg.ks_session_id from <API key> akg, rhnKSData ksd, rhnKickstartSession ksess, <API key> ksdef, <API key> kvt where akg.action_id = :action_id and ksess.kickstart_id = ksd.id and ksess.id = akg.ks_session_id and ksdef.kickstart_id = ksd.id and ksdef.virtualization_type = kvt.id """) def <API key>(server_id, action_id, dry_run=0): """ ShadowAction that schedules a package installation action for the <API key> package. """ log_debug(3) <API key> = "<API key>" tools_channel = SubscribedChannel(server_id, "rhn-tools") found_tools_channel = tools_channel.<API key>() if not found_tools_channel: raise InvalidAction("System not subscribed to the RHN Tools channel.") rhn_v12n_package = ChannelPackage(server_id, <API key>) if not rhn_v12n_package.exists(): raise InvalidAction("Could not find the <API key> package.") try: install_scheduler = <API key>(server_id, action_id, rhn_v12n_package) if (not dry_run): install_scheduler.<API key>() else: log_debug(4, "dry run requested") except NoActionInfo, nai: raise InvalidAction(str(nai)), None, sys.exc_info()[2] except PackageNotFound, pnf: raise InvalidAction(str(pnf)), None, sys.exc_info()[2] except Exception, e: raise InvalidAction(str(e)), None, sys.exc_info()[2] log_debug(3, "Completed scheduling install of <API key>!") raise ShadowAction("Scheduled installation of RHN Virtualization Guest packages.") def initiate(server_id, action_id, dry_run=0): log_debug(3) h = rhnSQL.prepare(<API key>) h.execute(action_id=action_id) row = h.fetchone_dict() if not row: raise InvalidAction("Kickstart action without an associated kickstart") kickstart_host = row['kickstart_host'] virt_type = row['virt_type'] name = row['guest_name'] boot_image = "spacewalk-koan" append_string = row['append_string'] vcpus = row['vcpus'] disk_gb = row['disk_gb'] mem_kb = row['mem_kb'] ks_session_id = row['ks_session_id'] virt_bridge = row['virt_bridge'] disk_path = row['disk_path'] cobbler_system_name = row['cobbler_system_name'] if not boot_image: raise InvalidAction("Boot image missing") return (kickstart_host, cobbler_system_name, virt_type, ks_session_id, name, mem_kb, vcpus, disk_gb, virt_bridge, disk_path, append_string) def add_tools_channel(server_id, action_id, dry_run=0): log_debug(3) if (not dry_run): <API key>(server_id) else: log_debug(4, "dry run requested") raise ShadowAction("Subscribed guest to tools channel.")
<?php /** * @file * Contains \Drupal\Tests\Core\TypedData\<API key>. */ namespace Drupal\Tests\Core\TypedData; use Drupal\Core\Cache\NullBackend; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\TypedData\DataDefinition; use Drupal\Core\TypedData\MapDataDefinition; use Drupal\Core\TypedData\TypedDataManager; use Drupal\Core\TypedData\Validation\RecursiveValidator; use Drupal\Core\Validation\ConstraintManager; use Drupal\Tests\UnitTestCase; use Symfony\Component\Validator\<API key>; use Symfony\Component\Validator\Context\<API key>; use Symfony\Component\Validator\Context\<API key>; /** * @coversDefaultClass \Drupal\Core\TypedData\Validation\<API key> * @group typedData */ class <API key> extends UnitTestCase { /** * The type data manager. * * @var \Drupal\Core\TypedData\TypedDataManager */ protected $typedDataManager; /** * The recursive validator. * * @var \Drupal\Core\TypedData\Validation\RecursiveValidator */ protected $recursiveValidator; /** * The validator factory. * * @var \Symfony\Component\Validator\<API key> */ protected $validatorFactory; /** * The execution context factory. * * @var \Symfony\Component\Validator\Context\<API key> */ protected $contextFactory; /** * {@inheritdoc} */ protected function setUp(): void { parent::setUp(); $cache_backend = new NullBackend('cache'); $namespaces = new \ArrayObject([ 'Drupal\\Core\\TypedData' => $this->root . '/core/lib/Drupal/Core/TypedData', 'Drupal\\Core\\Validation' => $this->root . '/core/lib/Drupal/Core/Validation', ]); $module_handler = $this->getMockBuilder('Drupal\Core\Extension\<API key>') -><API key>() ->getMock(); $class_resolver = $this->getMockBuilder('Drupal\Core\DependencyInjection\<API key>') -><API key>() ->getMock(); $this->typedDataManager = new TypedDataManager($namespaces, $cache_backend, $module_handler, $class_resolver); $this->typedDataManager-><API key>( new ConstraintManager($namespaces, $cache_backend, $module_handler) ); // Typed data definitions access the manager in the container. $container = new ContainerBuilder(); $container->set('typed_data_manager', $this->typedDataManager); \Drupal::setContainer($container); $translator = $this->createMock('Symfony\Contracts\Translation\TranslatorInterface'); $translator->expects($this->any()) ->method('trans') ->willReturnCallback(function ($id) { return $id; }); $this->contextFactory = new <API key>($translator); $this->validatorFactory = new <API key>(); $this->recursiveValidator = new RecursiveValidator($this->contextFactory, $this->validatorFactory, $this->typedDataManager); } /** * Ensures that passing an explicit group is not supported. * * @covers ::validate */ public function <API key>() { $this->expectException(\LogicException::class); $this->recursiveValidator->validate('test', NULL, 'test group'); } /** * Ensures that passing a non typed data value is not supported. * * @covers ::validate */ public function <API key>() { $this->expectException(\<API key>::class); $this->recursiveValidator->validate('test'); } /** * @covers ::validate */ public function <API key>() { $typed_data = $this->typedDataManager->create(DataDefinition::create('string')); $violations = $this->recursiveValidator->validate($typed_data); $this->assertCount(0, $violations); } /** * @covers ::validate */ public function <API key>() { $typed_data = $this->typedDataManager->create( DataDefinition::create('string') ->addConstraint('Callback', [ 'callback' => function ($value, <API key> $context) { $context->addViolation('test violation: ' . $value); }, ]) ); $typed_data->setValue('foo'); $violations = $this->recursiveValidator->validate($typed_data); $this->assertCount(1, $violations); // Ensure that the right value is passed into the validator. $this->assertEquals('test violation: foo', $violations->get(0)->getMessage()); } /** * @covers ::validate */ public function <API key>() { $options = [ 'callback' => function ($value, <API key> $context) { $context->addViolation('test violation'); }, ]; $typed_data = $this->typedDataManager->create( DataDefinition::create('string') ->addConstraint('Callback', $options) ->addConstraint('NotNull') ); $violations = $this->recursiveValidator->validate($typed_data); $this->assertCount(2, $violations); } /** * @covers ::validate */ public function <API key>() { $typed_data = $this-><API key>(); $violations = $this->recursiveValidator->validate($typed_data); $this->assertCount(6, $violations); $this->assertEquals('violation: 3', $violations->get(0)->getMessage()); $this->assertEquals('violation: value1', $violations->get(1)->getMessage()); $this->assertEquals('violation: value2', $violations->get(2)->getMessage()); $this->assertEquals('violation: 2', $violations->get(3)->getMessage()); $this->assertEquals('violation: subvalue1', $violations->get(4)->getMessage()); $this->assertEquals('violation: subvalue2', $violations->get(5)->getMessage()); $this->assertEquals('', $violations->get(0)->getPropertyPath()); $this->assertEquals('key1', $violations->get(1)->getPropertyPath()); $this->assertEquals('key2', $violations->get(2)->getPropertyPath()); $this->assertEquals('key_with_properties', $violations->get(3)->getPropertyPath()); $this->assertEquals('key_with_properties.subkey1', $violations->get(4)->getPropertyPath()); $this->assertEquals('key_with_properties.subkey2', $violations->get(5)->getPropertyPath()); } /** * Setups a typed data object used for test purposes. * * @param array $tree * An array of value, constraints and properties. * @param string $name * The name to use for the object. * * @return \Drupal\Core\TypedData\TypedDataInterface|\PHPUnit\Framework\MockObject\MockObject */ protected function setupTypedData(array $tree, $name = '') { $callback = function ($value, <API key> $context) { $context->addViolation('violation: ' . (is_array($value) ? count($value) : $value)); }; $tree += ['constraints' => []]; if (isset($tree['properties'])) { $map_data_definition = MapDataDefinition::create(); $map_data_definition->addConstraint('Callback', ['callback' => $callback]); foreach ($tree['properties'] as $property_name => $property) { $sub_typed_data = $this->setupTypedData($property, $property_name); $map_data_definition-><API key>($property_name, $sub_typed_data->getDataDefinition()); } $typed_data = $this->typedDataManager->create( $map_data_definition, $tree['value'], $name ); } else { /** @var \Drupal\Core\TypedData\TypedDataInterface $typed_data */ $typed_data = $this->typedDataManager->create( DataDefinition::create('string') ->addConstraint('Callback', ['callback' => $callback]), $tree['value'], $name ); } return $typed_data; } /** * @covers ::validateProperty */ public function <API key>() { $tree = [ 'value' => [], 'properties' => [ 'key1' => ['value' => 'value1'], ], ]; $typed_data = $this->setupTypedData($tree, 'test_name'); $this->expectException(\LogicException::class); $this->recursiveValidator->validateProperty($typed_data, 'key1', 'test group'); } /** * @covers ::validateProperty * * @dataProvider <API key> */ public function <API key>($object) { $this->expectException(\<API key>::class); $this->recursiveValidator->validateProperty($object, 'key1', NULL); } /** * Provides data for <API key>. * @return array */ public function <API key>() { $data = []; $data[] = [new \stdClass()]; $data[] = [new TestClass()]; $data[] = [$this->createMock('Drupal\Core\TypedData\TypedDataInterface')]; return $data; } /** * @covers ::validateProperty */ public function <API key>() { $typed_data = $this-><API key>(); $violations = $this->recursiveValidator->validateProperty($typed_data, 'key_with_properties'); $this->assertCount(3, $violations); $this->assertEquals('violation: 2', $violations->get(0)->getMessage()); $this->assertEquals('violation: subvalue1', $violations->get(1)->getMessage()); $this->assertEquals('violation: subvalue2', $violations->get(2)->getMessage()); $this->assertEquals('', $violations->get(0)->getPropertyPath()); $this->assertEquals('subkey1', $violations->get(1)->getPropertyPath()); $this->assertEquals('subkey2', $violations->get(2)->getPropertyPath()); } /** * @covers ::<API key> * * @dataProvider <API key> */ public function <API key>($object) { $this->expectException(\<API key>::class); $this->recursiveValidator-><API key>($object, 'key1', [], NULL); } /** * @covers ::<API key> */ public function <API key>() { $typed_data = $this-><API key>(['subkey1' => 'subvalue11', 'subkey2' => 'subvalue22']); $violations = $this->recursiveValidator-><API key>($typed_data, 'key_with_properties', $typed_data->get('key_with_properties')); $this->assertCount(3, $violations); $this->assertEquals('violation: 2', $violations->get(0)->getMessage()); $this->assertEquals('violation: subvalue11', $violations->get(1)->getMessage()); $this->assertEquals('violation: subvalue22', $violations->get(2)->getMessage()); $this->assertEquals('', $violations->get(0)->getPropertyPath()); $this->assertEquals('subkey1', $violations->get(1)->getPropertyPath()); $this->assertEquals('subkey2', $violations->get(2)->getPropertyPath()); } /** * Builds some example type data object. * * @return \Drupal\Core\TypedData\TypedDataInterface|\PHPUnit\Framework\MockObject\MockObject */ protected function <API key>($subkey_value = NULL) { $subkey_value = $subkey_value ?: ['subkey1' => 'subvalue1', 'subkey2' => 'subvalue2']; $tree = [ 'value' => [ 'key1' => 'value1', 'key2' => 'value2', 'key_with_properties' => $subkey_value, ], ]; $tree['properties'] = [ 'key1' => [ 'value' => 'value1', ], 'key2' => [ 'value' => 'value2', ], 'key_with_properties' => [ 'value' => $subkey_value ?: ['subkey1' => 'subvalue1', 'subkey2' => 'subvalue2'], ], ]; $tree['properties']['key_with_properties']['properties']['subkey1'] = ['value' => $tree['properties']['key_with_properties']['value']['subkey1']]; $tree['properties']['key_with_properties']['properties']['subkey2'] = ['value' => $tree['properties']['key_with_properties']['value']['subkey2']]; return $this->setupTypedData($tree, 'test_name'); } } class TestClass { }
#ifndef __drvNOI_h #define __drvNOI_h #include "drvbase.h" #include <dynload.h> #define NOI_XML_Proxy_DLL "pstoed_noi" #define <API key> "-r" #define RESOURCE_FILE_DESCR "Allplan resource file" #define <API key> "-bsl" #define <API key> 3 #define <API key> "Bezier Split Level (default 3)" #define DRIVER_NAME "noixml" #define DRIVER_DESCR "Nemetschek NOI XML format" #define DRIVER_LONG_DESCR "Nemetschek Object Interface XML format" #define FILE_SUFFIX "xml" #define DEFAULT_FONT_NAME "Arial" class drvNOI: public drvbase { public: derivedConstructor(drvNOI); ~drvNOI(); class DriverOptions: public ProgramOptions { public: OptionT <RSString, <API key>> ResourceFile; OptionT <int, IntValueExtractor> BezierSplitLevel; DriverOptions(): ResourceFile(true, <API key>, "string", 0, RESOURCE_FILE_DESCR, 0, (const char*) ""), BezierSplitLevel(true, <API key>, "number", 0, <API key>, 0, <API key>) { ADD (ResourceFile); ADD (BezierSplitLevel); } } *options; void show_rectangle(const float llx, const float lly, const float urx, const float ury); void show_text(const TextInfo &textInfo); virtual void show_image(const PSImage &imageinfo); // void translate(Point &p, float x, float y); private: int imgcount; DynLoader hProxyDLL; // Handle to DLL void LoadNOIProxy(); void draw_polyline(); void draw_polygon(); // const char * ResourceFile; // int BezierSplitLevel; // declare other private methods using include - pstoedit style #include "drvfuncs.h" }; #endif // __drvNOI_h
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Tue Aug 12 22:14:05 PDT 2014 --> <title>Uses of Class org.apache.nutch.indexwriter.solr.SolrUtils (apache-nutch 1.9 API)</title> <meta name="date" content="2014-08-12"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.nutch.indexwriter.solr.SolrUtils (apache-nutch 1.9 API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/nutch/indexwriter/solr/SolrUtils.html" title="class in org.apache.nutch.indexwriter.solr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/nutch/indexwriter/solr/class-use/SolrUtils.html" target="_top">Frames</a></li> <li><a href="SolrUtils.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.apache.nutch.indexwriter.solr.SolrUtils" class="title">Uses of Class<br>org.apache.nutch.indexwriter.solr.SolrUtils</h2> </div> <div class="classUseContainer">No usage of org.apache.nutch.indexwriter.solr.SolrUtils</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/nutch/indexwriter/solr/SolrUtils.html" title="class in org.apache.nutch.indexwriter.solr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/nutch/indexwriter/solr/class-use/SolrUtils.html" target="_top">Frames</a></li> <li><a href="SolrUtils.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>Copyright &copy; 2014 The Apache Software Foundation</small></p> </body> </html>